import { s as shallowRef, w as watchEffect, r as readonly, a as watch, c as customRef, g as getCurrentScope, o as onScopeDispose, e as effectScope, b as getCurrentInstance, h as hasInjectionContext, i as inject, p as provide, d as ref, f as isRef, u as unref, t as toValue$1, j as computed, k as reactive, l as toRefs$1, m as toRef$1, n as onBeforeMount, q as nextTick, v as onBeforeUnmount, x as onMounted, y as onUnmounted, z as isReactive, A as defineComponent, B as shallowReactive, C as h, F as Fragment, T as TransitionGroup, D as onUpdated, E as toRaw, G as markRaw, H as isReadonly, I as onBeforeUpdate, _ as __vitePreload, J as i18n, K as useI18n, L as openBlock, M as createElementBlock, N as createCommentVNode, O as createBaseVNode, P as withDirectives, Q as vModelText, R as renderSlot, S as normalizeClass, U as toDisplayString, V as withModifiers, W as vShow, X as createTextVNode, Y as renderList, Z as vModelSelect, $ as createVNode, a0 as createBlock, a1 as createSlots, a2 as withCtx, a3 as onDeactivated, a4 as onActivated, a5 as setupDevtoolsPlugin, a6 as resolveComponent, a7 as useSlots, a8 as Tooltip$1, a9 as withKeys, aa as createStaticVNode, ab as BLoading, ac as BIcon, ad as BButton, ae as createApp, af as version$2, ag as isProxy, ah as normalizeStyle, ai as resolveDynamicComponent, aj as useAttrs, ak as BDatepicker, al as mergeProps, am as useModel, an as mergeModels, ao as Switch, ap as BAutocomplete, aq as vModelCheckbox, ar as BCheckbox } from './index-6ljr7rTu.js';

const parseBoolean = (value, fallback = false) => {
  if (typeof value === "boolean") {
    return value;
  }
  if (typeof value === "string") {
    const normalized = value.trim().toLowerCase();
    if (["1", "true", "yes", "on"].includes(normalized)) {
      return true;
    }
    if (["0", "false", "no", "off"].includes(normalized)) {
      return false;
    }
  }
  return fallback;
};
const normalizeApiUrl$1 = (value) => String(value || "").replace(/\/+$/, "");
const IS_DEV = parseBoolean(
  undefined                           ,
  false
);
const normalizeReleaseSource = (value) => {
  const normalized = String(value || "").trim().toLowerCase();
  if (["local", "deployment", "auto"].includes(normalized)) {
    return normalized;
  }
  return IS_DEV ? "local" : "deployment";
};
const RELEASE_SOURCE_ENV = String(undefined                                    || "").trim().toLowerCase();
const RELEASE_SOURCE = normalizeReleaseSource(RELEASE_SOURCE_ENV);
const DEFAULT_LEGACY_API_URL = "https://api.truckwash.io";
const DEFAULT_PUBLIC_GATEWAY_API_URL = "https://api-v2.truckwash.io";
const DEFAULT_STABLE_API_URL = `${DEFAULT_PUBLIC_GATEWAY_API_URL}/master/api`;
const POS_STEP_1_VERSION = 2;
const API_URL = normalizeApiUrl$1(
  undefined                             || (IS_DEV ? "/api" : DEFAULT_STABLE_API_URL)
);
const RELEASE_MANAGER_CONTROL_API_URL = normalizeApiUrl$1(
  undefined                                                     || API_URL
);
const RELEASE_PUBLIC_GATEWAY_API_URL = normalizeApiUrl$1(
  undefined                                                    || DEFAULT_PUBLIC_GATEWAY_API_URL
);
const RELEASE_MANAGER_CONTROL_API_FALLBACK_URLS = String(
  undefined                                                               || (IS_DEV ? `${DEFAULT_STABLE_API_URL},${DEFAULT_PUBLIC_GATEWAY_API_URL}` : "")
).split(",").map((url) => normalizeApiUrl$1(url.trim())).filter(Boolean);
const RELEASE_TRUSTED_ORIGINS = String(undefined                                             || "").split(",").map((origin) => origin.trim().replace(/\/+$/, "")).filter(Boolean);
const SELF_SERVE_ATTACHMENT_TRUSTED_ORIGINS = String(
  undefined                                                           || ""
).split(",").map((origin) => origin.trim().replace(/\/+$/, "")).filter(Boolean);
const ALLOWED_ORIGINS = [
  "https://truckwash.io",
  "https://www.truckwash.io",
  new URL(DEFAULT_PUBLIC_GATEWAY_API_URL).origin,
  "http://localhost:5173",
  "http://localhost:4173",
  "http://localhost:4174",
  "http://127.0.0.1:5173",
  "http://127.0.0.1:4173",
  "http://127.0.0.1:4174",
  "https://dev.truckwash.io"
];
const MIGRATION_ORIGIN = "https://truckwash.io";
const REQUEST_QUEUE_CONFIG = Object.freeze({
  // Per-method concurrency limits
  concurrency: Object.freeze({
    GET: 10,
    POST: 4,
    PATCH: 4,
    PUT: 4,
    DELETE: 4,
    DEFAULT: 4
  }),
  // Delay between queue starts (0 = no pacing delay)
  spacingMs: 0,
  // Retries by HTTP status code
  retryByStatusCode: Object.freeze({
    429: 4,
    500: 1,
    502: 2,
    503: 2,
    504: 2
  }),
  retryDelay: Object.freeze({
    baseMs: 300,
    maxMs: 3e3,
    jitterMs: 50
  }),
  ping: Object.freeze({
    endpoint: "/ping",
    intervalMs: 3e4,
    timeoutMs: 5e3
  }),
  inspector: Object.freeze({
    expandedByDefault: false,
    timerRefreshMs: 250,
    recentRequestsLimit: 8,
    errorHistoryLimit: 10,
    missingPermissionsLimit: 20,
    componentPermissionReportWindowMs: 2e3,
    payloadMaxChars: 4e3
  }),
  // Queue progress widget behavior
  progress: Object.freeze({
    minBatchSizeToShow: 2,
    completedVisibleMs: 2500
  })
});

function computedEager(fn, options) {
  var _a;
  const result = shallowRef();
  watchEffect(() => {
    result.value = fn();
  }, {
    ...options,
    flush: (_a = options == null ? void 0 : options.flush) != null ? _a : "sync"
  });
  return readonly(result);
}

function computedWithControl(source, fn) {
  let v = void 0;
  let track;
  let trigger;
  const dirty = shallowRef(true);
  const update = () => {
    dirty.value = true;
    trigger();
  };
  watch(source, update, { flush: "sync" });
  const get = typeof fn === "function" ? fn : fn.get;
  const set = typeof fn === "function" ? void 0 : fn.set;
  const result = customRef((_track, _trigger) => {
    track = _track;
    trigger = _trigger;
    return {
      get() {
        if (dirty.value) {
          v = get(v);
          dirty.value = false;
        }
        track();
        return v;
      },
      set(v2) {
        set == null ? void 0 : set(v2);
      }
    };
  });
  if (Object.isExtensible(result))
    result.trigger = update;
  return result;
}

function tryOnScopeDispose(fn) {
  if (getCurrentScope()) {
    onScopeDispose(fn);
    return true;
  }
  return false;
}

function createEventHook() {
  const fns = /* @__PURE__ */ new Set();
  const off = (fn) => {
    fns.delete(fn);
  };
  const clear = () => {
    fns.clear();
  };
  const on = (fn) => {
    fns.add(fn);
    const offFn = () => off(fn);
    tryOnScopeDispose(offFn);
    return {
      off: offFn
    };
  };
  const trigger = (...args) => {
    return Promise.all(Array.from(fns).map((fn) => fn(...args)));
  };
  return {
    on,
    off,
    trigger,
    clear
  };
}

function createGlobalState(stateFactory) {
  let initialized = false;
  let state;
  const scope = effectScope(true);
  return (...args) => {
    if (!initialized) {
      state = scope.run(() => stateFactory(...args));
      initialized = true;
    }
    return state;
  };
}

const localProvidedStateMap = /* @__PURE__ */ new WeakMap();

const injectLocal = (...args) => {
  var _a;
  const key = args[0];
  const instance = (_a = getCurrentInstance()) == null ? void 0 : _a.proxy;
  if (instance == null && !hasInjectionContext())
    throw new Error("injectLocal must be called in setup");
  if (instance && localProvidedStateMap.has(instance) && key in localProvidedStateMap.get(instance))
    return localProvidedStateMap.get(instance)[key];
  return inject(...args);
};

const provideLocal = (key, value) => {
  var _a;
  const instance = (_a = getCurrentInstance()) == null ? void 0 : _a.proxy;
  if (instance == null)
    throw new Error("provideLocal must be called in setup");
  if (!localProvidedStateMap.has(instance))
    localProvidedStateMap.set(instance, /* @__PURE__ */ Object.create(null));
  const localProvidedState = localProvidedStateMap.get(instance);
  localProvidedState[key] = value;
  provide(key, value);
};

function createInjectionState(composable, options) {
  const key = (options == null ? void 0 : options.injectionKey) || Symbol(composable.name || "InjectionState");
  const defaultValue = options == null ? void 0 : options.defaultValue;
  const useProvidingState = (...args) => {
    const state = composable(...args);
    provideLocal(key, state);
    return state;
  };
  const useInjectedState = () => injectLocal(key, defaultValue);
  return [useProvidingState, useInjectedState];
}

function createRef(value, deep) {
  if (deep === true) {
    return ref(value);
  } else {
    return shallowRef(value);
  }
}

function createSharedComposable(composable) {
  let subscribers = 0;
  let state;
  let scope;
  const dispose = () => {
    subscribers -= 1;
    if (scope && subscribers <= 0) {
      scope.stop();
      state = void 0;
      scope = void 0;
    }
  };
  return (...args) => {
    subscribers += 1;
    if (!scope) {
      scope = effectScope(true);
      state = scope.run(() => composable(...args));
    }
    tryOnScopeDispose(dispose);
    return state;
  };
}

function extendRef(ref, extend, { enumerable = false, unwrap = true } = {}) {
  for (const [key, value] of Object.entries(extend)) {
    if (key === "value")
      continue;
    if (isRef(value) && unwrap) {
      Object.defineProperty(ref, key, {
        get() {
          return value.value;
        },
        set(v) {
          value.value = v;
        },
        enumerable
      });
    } else {
      Object.defineProperty(ref, key, { value, enumerable });
    }
  }
  return ref;
}

function get(obj, key) {
  if (key == null)
    return unref(obj);
  return unref(obj)[key];
}

function isDefined(v) {
  return unref(v) != null;
}

function makeDestructurable(obj, arr) {
  if (typeof Symbol !== "undefined") {
    const clone = { ...obj };
    Object.defineProperty(clone, Symbol.iterator, {
      enumerable: false,
      value() {
        let index = 0;
        return {
          next: () => ({
            value: arr[index++],
            done: index > arr.length
          })
        };
      }
    });
    return clone;
  } else {
    return Object.assign([...arr], obj);
  }
}

function reactify(fn, options) {
  const unrefFn = (options == null ? void 0 : options.computedGetter) === false ? unref : toValue$1;
  return function(...args) {
    return computed(() => fn.apply(this, args.map((i) => unrefFn(i))));
  };
}

function reactifyObject(obj, optionsOrKeys = {}) {
  let keys = [];
  let options;
  if (Array.isArray(optionsOrKeys)) {
    keys = optionsOrKeys;
  } else {
    options = optionsOrKeys;
    const { includeOwnProperties = true } = optionsOrKeys;
    keys.push(...Object.keys(obj));
    if (includeOwnProperties)
      keys.push(...Object.getOwnPropertyNames(obj));
  }
  return Object.fromEntries(
    keys.map((key) => {
      const value = obj[key];
      return [
        key,
        typeof value === "function" ? reactify(value.bind(obj), options) : value
      ];
    })
  );
}

function toReactive(objectRef) {
  if (!isRef(objectRef))
    return reactive(objectRef);
  const proxy = new Proxy({}, {
    get(_, p, receiver) {
      return unref(Reflect.get(objectRef.value, p, receiver));
    },
    set(_, p, value) {
      if (isRef(objectRef.value[p]) && !isRef(value))
        objectRef.value[p].value = value;
      else
        objectRef.value[p] = value;
      return true;
    },
    deleteProperty(_, p) {
      return Reflect.deleteProperty(objectRef.value, p);
    },
    has(_, p) {
      return Reflect.has(objectRef.value, p);
    },
    ownKeys() {
      return Object.keys(objectRef.value);
    },
    getOwnPropertyDescriptor() {
      return {
        enumerable: true,
        configurable: true
      };
    }
  });
  return reactive(proxy);
}

function reactiveComputed(fn) {
  return toReactive(computed(fn));
}

function reactiveOmit(obj, ...keys) {
  const flatKeys = keys.flat();
  const predicate = flatKeys[0];
  return reactiveComputed(() => typeof predicate === "function" ? Object.fromEntries(Object.entries(toRefs$1(obj)).filter(([k, v]) => !predicate(toValue$1(v), k))) : Object.fromEntries(Object.entries(toRefs$1(obj)).filter((e) => !flatKeys.includes(e[0]))));
}

const isClient = typeof window !== "undefined" && typeof document !== "undefined";
const isWorker = typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope;
const isDef = (val) => typeof val !== "undefined";
const notNullish = (val) => val != null;
const assert = (condition, ...infos) => {
  if (!condition)
    console.warn(...infos);
};
const toString$1 = Object.prototype.toString;
const isObject$2 = (val) => toString$1.call(val) === "[object Object]";
const now = () => Date.now();
const timestamp = () => +Date.now();
const clamp = (n, min, max) => Math.min(max, Math.max(min, n));
const noop$3 = () => {
};
const rand = (min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
};
const hasOwn$2 = (val, key) => Object.prototype.hasOwnProperty.call(val, key);
const isIOS = /* @__PURE__ */ getIsIOS();
function getIsIOS() {
  var _a, _b;
  return isClient && ((_a = window == null ? void 0 : window.navigator) == null ? void 0 : _a.userAgent) && (/iP(?:ad|hone|od)/.test(window.navigator.userAgent) || ((_b = window == null ? void 0 : window.navigator) == null ? void 0 : _b.maxTouchPoints) > 2 && /iPad|Macintosh/.test(window == null ? void 0 : window.navigator.userAgent));
}

function createFilterWrapper(filter, fn) {
  function wrapper(...args) {
    return new Promise((resolve, reject) => {
      Promise.resolve(filter(() => fn.apply(this, args), { fn, thisArg: this, args })).then(resolve).catch(reject);
    });
  }
  return wrapper;
}
const bypassFilter = (invoke) => {
  return invoke();
};
function debounceFilter(ms, options = {}) {
  let timer;
  let maxTimer;
  let lastRejector = noop$3;
  const _clearTimeout = (timer2) => {
    clearTimeout(timer2);
    lastRejector();
    lastRejector = noop$3;
  };
  let lastInvoker;
  const filter = (invoke) => {
    const duration = toValue$1(ms);
    const maxDuration = toValue$1(options.maxWait);
    if (timer)
      _clearTimeout(timer);
    if (duration <= 0 || maxDuration !== void 0 && maxDuration <= 0) {
      if (maxTimer) {
        _clearTimeout(maxTimer);
        maxTimer = null;
      }
      return Promise.resolve(invoke());
    }
    return new Promise((resolve, reject) => {
      lastRejector = options.rejectOnCancel ? reject : resolve;
      lastInvoker = invoke;
      if (maxDuration && !maxTimer) {
        maxTimer = setTimeout(() => {
          if (timer)
            _clearTimeout(timer);
          maxTimer = null;
          resolve(lastInvoker());
        }, maxDuration);
      }
      timer = setTimeout(() => {
        if (maxTimer)
          _clearTimeout(maxTimer);
        maxTimer = null;
        resolve(invoke());
      }, duration);
    });
  };
  return filter;
}
function throttleFilter(...args) {
  let lastExec = 0;
  let timer;
  let isLeading = true;
  let lastRejector = noop$3;
  let lastValue;
  let ms;
  let trailing;
  let leading;
  let rejectOnCancel;
  if (!isRef(args[0]) && typeof args[0] === "object")
    ({ delay: ms, trailing = true, leading = true, rejectOnCancel = false } = args[0]);
  else
    [ms, trailing = true, leading = true, rejectOnCancel = false] = args;
  const clear = () => {
    if (timer) {
      clearTimeout(timer);
      timer = void 0;
      lastRejector();
      lastRejector = noop$3;
    }
  };
  const filter = (_invoke) => {
    const duration = toValue$1(ms);
    const elapsed = Date.now() - lastExec;
    const invoke = () => {
      return lastValue = _invoke();
    };
    clear();
    if (duration <= 0) {
      lastExec = Date.now();
      return invoke();
    }
    if (elapsed > duration && (leading || !isLeading)) {
      lastExec = Date.now();
      invoke();
    } else if (trailing) {
      lastValue = new Promise((resolve, reject) => {
        lastRejector = rejectOnCancel ? reject : resolve;
        timer = setTimeout(() => {
          lastExec = Date.now();
          isLeading = true;
          resolve(invoke());
          clear();
        }, Math.max(0, duration - elapsed));
      });
    }
    if (!leading && !timer)
      timer = setTimeout(() => isLeading = true, duration);
    isLeading = false;
    return lastValue;
  };
  return filter;
}
function pausableFilter(extendFilter = bypassFilter, options = {}) {
  const {
    initialState = "active"
  } = options;
  const isActive = toRef(initialState === "active");
  function pause() {
    isActive.value = false;
  }
  function resume() {
    isActive.value = true;
  }
  const eventFilter = (...args) => {
    if (isActive.value)
      extendFilter(...args);
  };
  return { isActive: readonly(isActive), pause, resume, eventFilter };
}

function cacheStringFunction(fn) {
  const cache = /* @__PURE__ */ Object.create(null);
  return (str) => {
    const hit = cache[str];
    return hit || (cache[str] = fn(str));
  };
}
const hyphenateRE = /\B([A-Z])/g;
const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase());
const camelizeRE = /-(\w)/g;
const camelize = cacheStringFunction((str) => {
  return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : "");
});

function promiseTimeout(ms, throwOnTimeout = false, reason = "Timeout") {
  return new Promise((resolve, reject) => {
    if (throwOnTimeout)
      setTimeout(() => reject(reason), ms);
    else
      setTimeout(resolve, ms);
  });
}
function identity(arg) {
  return arg;
}
function createSingletonPromise(fn) {
  let _promise;
  function wrapper() {
    if (!_promise)
      _promise = fn();
    return _promise;
  }
  wrapper.reset = async () => {
    const _prev = _promise;
    _promise = void 0;
    if (_prev)
      await _prev;
  };
  return wrapper;
}
function invoke(fn) {
  return fn();
}
function containsProp(obj, ...props) {
  return props.some((k) => k in obj);
}
function increaseWithUnit(target, delta) {
  var _a;
  if (typeof target === "number")
    return target + delta;
  const value = ((_a = target.match(/^-?\d+\.?\d*/)) == null ? void 0 : _a[0]) || "";
  const unit = target.slice(value.length);
  const result = Number.parseFloat(value) + delta;
  if (Number.isNaN(result))
    return target;
  return result + unit;
}
function pxValue(px) {
  return px.endsWith("rem") ? Number.parseFloat(px) * 16 : Number.parseFloat(px);
}
function objectPick(obj, keys, omitUndefined = false) {
  return keys.reduce((n, k) => {
    if (k in obj) {
      if (!omitUndefined || obj[k] !== void 0)
        n[k] = obj[k];
    }
    return n;
  }, {});
}
function objectOmit(obj, keys, omitUndefined = false) {
  return Object.fromEntries(Object.entries(obj).filter(([key, value]) => {
    return (!omitUndefined || value !== void 0) && !keys.includes(key);
  }));
}
function objectEntries(obj) {
  return Object.entries(obj);
}
function getLifeCycleTarget(target) {
  return target || getCurrentInstance();
}
function toArray$1(value) {
  return Array.isArray(value) ? value : [value];
}

function toRef(...args) {
  if (args.length !== 1)
    return toRef$1(...args);
  const r = args[0];
  return typeof r === "function" ? readonly(customRef(() => ({ get: r, set: noop$3 }))) : ref(r);
}
const resolveRef = toRef;

function reactivePick(obj, ...keys) {
  const flatKeys = keys.flat();
  const predicate = flatKeys[0];
  return reactiveComputed(() => typeof predicate === "function" ? Object.fromEntries(Object.entries(toRefs$1(obj)).filter(([k, v]) => predicate(toValue$1(v), k))) : Object.fromEntries(flatKeys.map((k) => [k, toRef(obj, k)])));
}

function refAutoReset(defaultValue, afterMs = 1e4) {
  return customRef((track, trigger) => {
    let value = toValue$1(defaultValue);
    let timer;
    const resetAfter = () => setTimeout(() => {
      value = toValue$1(defaultValue);
      trigger();
    }, toValue$1(afterMs));
    tryOnScopeDispose(() => {
      clearTimeout(timer);
    });
    return {
      get() {
        track();
        return value;
      },
      set(newValue) {
        value = newValue;
        trigger();
        clearTimeout(timer);
        timer = resetAfter();
      }
    };
  });
}

function useDebounceFn(fn, ms = 200, options = {}) {
  return createFilterWrapper(
    debounceFilter(ms, options),
    fn
  );
}

function refDebounced(value, ms = 200, options = {}) {
  const debounced = ref(value.value);
  const updater = useDebounceFn(() => {
    debounced.value = value.value;
  }, ms, options);
  watch(value, () => updater());
  return debounced;
}

function refDefault(source, defaultValue) {
  return computed({
    get() {
      var _a;
      return (_a = source.value) != null ? _a : defaultValue;
    },
    set(value) {
      source.value = value;
    }
  });
}

function useThrottleFn(fn, ms = 200, trailing = false, leading = true, rejectOnCancel = false) {
  return createFilterWrapper(
    throttleFilter(ms, trailing, leading, rejectOnCancel),
    fn
  );
}

function refThrottled(value, delay = 200, trailing = true, leading = true) {
  if (delay <= 0)
    return value;
  const throttled = ref(value.value);
  const updater = useThrottleFn(() => {
    throttled.value = value.value;
  }, delay, trailing, leading);
  watch(value, () => updater());
  return throttled;
}

function refWithControl(initial, options = {}) {
  let source = initial;
  let track;
  let trigger;
  const ref = customRef((_track, _trigger) => {
    track = _track;
    trigger = _trigger;
    return {
      get() {
        return get();
      },
      set(v) {
        set(v);
      }
    };
  });
  function get(tracking = true) {
    if (tracking)
      track();
    return source;
  }
  function set(value, triggering = true) {
    var _a, _b;
    if (value === source)
      return;
    const old = source;
    if (((_a = options.onBeforeChange) == null ? void 0 : _a.call(options, value, old)) === false)
      return;
    source = value;
    (_b = options.onChanged) == null ? void 0 : _b.call(options, value, old);
    if (triggering)
      trigger();
  }
  const untrackedGet = () => get(false);
  const silentSet = (v) => set(v, false);
  const peek = () => get(false);
  const lay = (v) => set(v, false);
  return extendRef(
    ref,
    {
      get,
      set,
      untrackedGet,
      silentSet,
      peek,
      lay
    },
    { enumerable: true }
  );
}
const controlledRef = refWithControl;

function set$1(...args) {
  if (args.length === 2) {
    const [ref, value] = args;
    ref.value = value;
  }
  if (args.length === 3) {
    const [target, key, value] = args;
    target[key] = value;
  }
}

function watchWithFilter(source, cb, options = {}) {
  const {
    eventFilter = bypassFilter,
    ...watchOptions
  } = options;
  return watch(
    source,
    createFilterWrapper(
      eventFilter,
      cb
    ),
    watchOptions
  );
}

function watchPausable(source, cb, options = {}) {
  const {
    eventFilter: filter,
    initialState = "active",
    ...watchOptions
  } = options;
  const { eventFilter, pause, resume, isActive } = pausableFilter(filter, { initialState });
  const stop = watchWithFilter(
    source,
    cb,
    {
      ...watchOptions,
      eventFilter
    }
  );
  return { stop, pause, resume, isActive };
}

function syncRef(left, right, ...[options]) {
  const {
    flush = "sync",
    deep = false,
    immediate = true,
    direction = "both",
    transform = {}
  } = options || {};
  const watchers = [];
  const transformLTR = "ltr" in transform && transform.ltr || ((v) => v);
  const transformRTL = "rtl" in transform && transform.rtl || ((v) => v);
  if (direction === "both" || direction === "ltr") {
    watchers.push(watchPausable(
      left,
      (newValue) => {
        watchers.forEach((w) => w.pause());
        right.value = transformLTR(newValue);
        watchers.forEach((w) => w.resume());
      },
      { flush, deep, immediate }
    ));
  }
  if (direction === "both" || direction === "rtl") {
    watchers.push(watchPausable(
      right,
      (newValue) => {
        watchers.forEach((w) => w.pause());
        left.value = transformRTL(newValue);
        watchers.forEach((w) => w.resume());
      },
      { flush, deep, immediate }
    ));
  }
  const stop = () => {
    watchers.forEach((w) => w.stop());
  };
  return stop;
}

function syncRefs(source, targets, options = {}) {
  const {
    flush = "sync",
    deep = false,
    immediate = true
  } = options;
  const targetsArray = toArray$1(targets);
  return watch(
    source,
    (newValue) => targetsArray.forEach((target) => target.value = newValue),
    { flush, deep, immediate }
  );
}

function toRefs(objectRef, options = {}) {
  if (!isRef(objectRef))
    return toRefs$1(objectRef);
  const result = Array.isArray(objectRef.value) ? Array.from({ length: objectRef.value.length }) : {};
  for (const key in objectRef.value) {
    result[key] = customRef(() => ({
      get() {
        return objectRef.value[key];
      },
      set(v) {
        var _a;
        const replaceRef = (_a = toValue$1(options.replaceRef)) != null ? _a : true;
        if (replaceRef) {
          if (Array.isArray(objectRef.value)) {
            const copy = [...objectRef.value];
            copy[key] = v;
            objectRef.value = copy;
          } else {
            const newObject = { ...objectRef.value, [key]: v };
            Object.setPrototypeOf(newObject, Object.getPrototypeOf(objectRef.value));
            objectRef.value = newObject;
          }
        } else {
          objectRef.value[key] = v;
        }
      }
    }));
  }
  return result;
}

const toValue = toValue$1;
const resolveUnref = toValue$1;

function tryOnBeforeMount(fn, sync = true, target) {
  const instance = getLifeCycleTarget(target);
  if (instance)
    onBeforeMount(fn, target);
  else if (sync)
    fn();
  else
    nextTick(fn);
}

function tryOnBeforeUnmount(fn, target) {
  const instance = getLifeCycleTarget(target);
  if (instance)
    onBeforeUnmount(fn, target);
}

function tryOnMounted(fn, sync = true, target) {
  const instance = getLifeCycleTarget();
  if (instance)
    onMounted(fn, target);
  else if (sync)
    fn();
  else
    nextTick(fn);
}

function tryOnUnmounted(fn, target) {
  const instance = getLifeCycleTarget(target);
  if (instance)
    onUnmounted(fn, target);
}

function createUntil(r, isNot = false) {
  function toMatch(condition, { flush = "sync", deep = false, timeout, throwOnTimeout } = {}) {
    let stop = null;
    const watcher = new Promise((resolve) => {
      stop = watch(
        r,
        (v) => {
          if (condition(v) !== isNot) {
            if (stop)
              stop();
            else
              nextTick(() => stop == null ? void 0 : stop());
            resolve(v);
          }
        },
        {
          flush,
          deep,
          immediate: true
        }
      );
    });
    const promises = [watcher];
    if (timeout != null) {
      promises.push(
        promiseTimeout(timeout, throwOnTimeout).then(() => toValue$1(r)).finally(() => stop == null ? void 0 : stop())
      );
    }
    return Promise.race(promises);
  }
  function toBe(value, options) {
    if (!isRef(value))
      return toMatch((v) => v === value, options);
    const { flush = "sync", deep = false, timeout, throwOnTimeout } = options != null ? options : {};
    let stop = null;
    const watcher = new Promise((resolve) => {
      stop = watch(
        [r, value],
        ([v1, v2]) => {
          if (isNot !== (v1 === v2)) {
            if (stop)
              stop();
            else
              nextTick(() => stop == null ? void 0 : stop());
            resolve(v1);
          }
        },
        {
          flush,
          deep,
          immediate: true
        }
      );
    });
    const promises = [watcher];
    if (timeout != null) {
      promises.push(
        promiseTimeout(timeout, throwOnTimeout).then(() => toValue$1(r)).finally(() => {
          stop == null ? void 0 : stop();
          return toValue$1(r);
        })
      );
    }
    return Promise.race(promises);
  }
  function toBeTruthy(options) {
    return toMatch((v) => Boolean(v), options);
  }
  function toBeNull(options) {
    return toBe(null, options);
  }
  function toBeUndefined(options) {
    return toBe(void 0, options);
  }
  function toBeNaN(options) {
    return toMatch(Number.isNaN, options);
  }
  function toContains(value, options) {
    return toMatch((v) => {
      const array = Array.from(v);
      return array.includes(value) || array.includes(toValue$1(value));
    }, options);
  }
  function changed(options) {
    return changedTimes(1, options);
  }
  function changedTimes(n = 1, options) {
    let count = -1;
    return toMatch(() => {
      count += 1;
      return count >= n;
    }, options);
  }
  if (Array.isArray(toValue$1(r))) {
    const instance = {
      toMatch,
      toContains,
      changed,
      changedTimes,
      get not() {
        return createUntil(r, !isNot);
      }
    };
    return instance;
  } else {
    const instance = {
      toMatch,
      toBe,
      toBeTruthy,
      toBeNull,
      toBeNaN,
      toBeUndefined,
      changed,
      changedTimes,
      get not() {
        return createUntil(r, !isNot);
      }
    };
    return instance;
  }
}
function until(r) {
  return createUntil(r);
}

function defaultComparator(value, othVal) {
  return value === othVal;
}
function useArrayDifference(...args) {
  var _a, _b;
  const list = args[0];
  const values = args[1];
  let compareFn = (_a = args[2]) != null ? _a : defaultComparator;
  const {
    symmetric = false
  } = (_b = args[3]) != null ? _b : {};
  if (typeof compareFn === "string") {
    const key = compareFn;
    compareFn = (value, othVal) => value[key] === othVal[key];
  }
  const diff1 = computed(() => toValue$1(list).filter((x) => toValue$1(values).findIndex((y) => compareFn(x, y)) === -1));
  if (symmetric) {
    const diff2 = computed(() => toValue$1(values).filter((x) => toValue$1(list).findIndex((y) => compareFn(x, y)) === -1));
    return computed(() => symmetric ? [...toValue$1(diff1), ...toValue$1(diff2)] : toValue$1(diff1));
  } else {
    return diff1;
  }
}

function useArrayEvery(list, fn) {
  return computed(() => toValue$1(list).every((element, index, array) => fn(toValue$1(element), index, array)));
}

function useArrayFilter(list, fn) {
  return computed(() => toValue$1(list).map((i) => toValue$1(i)).filter(fn));
}

function useArrayFind(list, fn) {
  return computed(() => toValue$1(
    toValue$1(list).find((element, index, array) => fn(toValue$1(element), index, array))
  ));
}

function useArrayFindIndex(list, fn) {
  return computed(() => toValue$1(list).findIndex((element, index, array) => fn(toValue$1(element), index, array)));
}

function findLast(arr, cb) {
  let index = arr.length;
  while (index-- > 0) {
    if (cb(arr[index], index, arr))
      return arr[index];
  }
  return void 0;
}
function useArrayFindLast(list, fn) {
  return computed(() => toValue$1(
    !Array.prototype.findLast ? findLast(toValue$1(list), (element, index, array) => fn(toValue$1(element), index, array)) : toValue$1(list).findLast((element, index, array) => fn(toValue$1(element), index, array))
  ));
}

function isArrayIncludesOptions(obj) {
  return isObject$2(obj) && containsProp(obj, "formIndex", "comparator");
}
function useArrayIncludes(...args) {
  var _a;
  const list = args[0];
  const value = args[1];
  let comparator = args[2];
  let formIndex = 0;
  if (isArrayIncludesOptions(comparator)) {
    formIndex = (_a = comparator.fromIndex) != null ? _a : 0;
    comparator = comparator.comparator;
  }
  if (typeof comparator === "string") {
    const key = comparator;
    comparator = (element, value2) => element[key] === toValue$1(value2);
  }
  comparator = comparator != null ? comparator : (element, value2) => element === toValue$1(value2);
  return computed(() => toValue$1(list).slice(formIndex).some((element, index, array) => comparator(
    toValue$1(element),
    toValue$1(value),
    index,
    toValue$1(array)
  )));
}

function useArrayJoin(list, separator) {
  return computed(() => toValue$1(list).map((i) => toValue$1(i)).join(toValue$1(separator)));
}

function useArrayMap(list, fn) {
  return computed(() => toValue$1(list).map((i) => toValue$1(i)).map(fn));
}

function useArrayReduce(list, reducer, ...args) {
  const reduceCallback = (sum, value, index) => reducer(toValue$1(sum), toValue$1(value), index);
  return computed(() => {
    const resolved = toValue$1(list);
    return args.length ? resolved.reduce(reduceCallback, typeof args[0] === "function" ? toValue$1(args[0]()) : toValue$1(args[0])) : resolved.reduce(reduceCallback);
  });
}

function useArraySome(list, fn) {
  return computed(() => toValue$1(list).some((element, index, array) => fn(toValue$1(element), index, array)));
}

function uniq(array) {
  return Array.from(new Set(array));
}
function uniqueElementsBy(array, fn) {
  return array.reduce((acc, v) => {
    if (!acc.some((x) => fn(v, x, array)))
      acc.push(v);
    return acc;
  }, []);
}
function useArrayUnique(list, compareFn) {
  return computed(() => {
    const resolvedList = toValue$1(list).map((element) => toValue$1(element));
    return compareFn ? uniqueElementsBy(resolvedList, compareFn) : uniq(resolvedList);
  });
}

function useCounter(initialValue = 0, options = {}) {
  let _initialValue = unref(initialValue);
  const count = shallowRef(initialValue);
  const {
    max = Number.POSITIVE_INFINITY,
    min = Number.NEGATIVE_INFINITY
  } = options;
  const inc = (delta = 1) => count.value = Math.max(Math.min(max, count.value + delta), min);
  const dec = (delta = 1) => count.value = Math.min(Math.max(min, count.value - delta), max);
  const get = () => count.value;
  const set = (val) => count.value = Math.max(min, Math.min(max, val));
  const reset = (val = _initialValue) => {
    _initialValue = val;
    return set(val);
  };
  return { count, inc, dec, get, set, reset };
}

const REGEX_PARSE = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[T\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/i;
const REGEX_FORMAT = /[YMDHhms]o|\[([^\]]+)\]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a{1,2}|A{1,2}|m{1,2}|s{1,2}|Z{1,2}|z{1,4}|SSS/g;
function defaultMeridiem(hours, minutes, isLowercase, hasPeriod) {
  let m = hours < 12 ? "AM" : "PM";
  if (hasPeriod)
    m = m.split("").reduce((acc, curr) => acc += `${curr}.`, "");
  return isLowercase ? m.toLowerCase() : m;
}
function formatOrdinal(num) {
  const suffixes = ["th", "st", "nd", "rd"];
  const v = num % 100;
  return num + (suffixes[(v - 20) % 10] || suffixes[v] || suffixes[0]);
}
function formatDate$1(date, formatStr, options = {}) {
  var _a;
  const years = date.getFullYear();
  const month = date.getMonth();
  const days = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();
  const milliseconds = date.getMilliseconds();
  const day = date.getDay();
  const meridiem = (_a = options.customMeridiem) != null ? _a : defaultMeridiem;
  const stripTimeZone = (dateString) => {
    var _a2;
    return (_a2 = dateString.split(" ")[1]) != null ? _a2 : "";
  };
  const matches = {
    Yo: () => formatOrdinal(years),
    YY: () => String(years).slice(-2),
    YYYY: () => years,
    M: () => month + 1,
    Mo: () => formatOrdinal(month + 1),
    MM: () => `${month + 1}`.padStart(2, "0"),
    MMM: () => date.toLocaleDateString(toValue$1(options.locales), { month: "short" }),
    MMMM: () => date.toLocaleDateString(toValue$1(options.locales), { month: "long" }),
    D: () => String(days),
    Do: () => formatOrdinal(days),
    DD: () => `${days}`.padStart(2, "0"),
    H: () => String(hours),
    Ho: () => formatOrdinal(hours),
    HH: () => `${hours}`.padStart(2, "0"),
    h: () => `${hours % 12 || 12}`.padStart(1, "0"),
    ho: () => formatOrdinal(hours % 12 || 12),
    hh: () => `${hours % 12 || 12}`.padStart(2, "0"),
    m: () => String(minutes),
    mo: () => formatOrdinal(minutes),
    mm: () => `${minutes}`.padStart(2, "0"),
    s: () => String(seconds),
    so: () => formatOrdinal(seconds),
    ss: () => `${seconds}`.padStart(2, "0"),
    SSS: () => `${milliseconds}`.padStart(3, "0"),
    d: () => day,
    dd: () => date.toLocaleDateString(toValue$1(options.locales), { weekday: "narrow" }),
    ddd: () => date.toLocaleDateString(toValue$1(options.locales), { weekday: "short" }),
    dddd: () => date.toLocaleDateString(toValue$1(options.locales), { weekday: "long" }),
    A: () => meridiem(hours, minutes),
    AA: () => meridiem(hours, minutes, false, true),
    a: () => meridiem(hours, minutes, true),
    aa: () => meridiem(hours, minutes, true, true),
    z: () => stripTimeZone(date.toLocaleDateString(toValue$1(options.locales), { timeZoneName: "shortOffset" })),
    zz: () => stripTimeZone(date.toLocaleDateString(toValue$1(options.locales), { timeZoneName: "shortOffset" })),
    zzz: () => stripTimeZone(date.toLocaleDateString(toValue$1(options.locales), { timeZoneName: "shortOffset" })),
    zzzz: () => stripTimeZone(date.toLocaleDateString(toValue$1(options.locales), { timeZoneName: "longOffset" }))
  };
  return formatStr.replace(REGEX_FORMAT, (match, $1) => {
    var _a2, _b;
    return (_b = $1 != null ? $1 : (_a2 = matches[match]) == null ? void 0 : _a2.call(matches)) != null ? _b : match;
  });
}
function normalizeDate(date) {
  if (date === null)
    return new Date(Number.NaN);
  if (date === void 0)
    return /* @__PURE__ */ new Date();
  if (date instanceof Date)
    return new Date(date);
  if (typeof date === "string" && !/Z$/i.test(date)) {
    const d = date.match(REGEX_PARSE);
    if (d) {
      const m = d[2] - 1 || 0;
      const ms = (d[7] || "0").substring(0, 3);
      return new Date(d[1], m, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, ms);
    }
  }
  return new Date(date);
}
function useDateFormat(date, formatStr = "HH:mm:ss", options = {}) {
  return computed(() => formatDate$1(normalizeDate(toValue$1(date)), toValue$1(formatStr), options));
}

function useIntervalFn(cb, interval = 1e3, options = {}) {
  const {
    immediate = true,
    immediateCallback = false
  } = options;
  let timer = null;
  const isActive = shallowRef(false);
  function clean() {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  }
  function pause() {
    isActive.value = false;
    clean();
  }
  function resume() {
    const intervalValue = toValue$1(interval);
    if (intervalValue <= 0)
      return;
    isActive.value = true;
    if (immediateCallback)
      cb();
    clean();
    if (isActive.value)
      timer = setInterval(cb, intervalValue);
  }
  if (immediate && isClient)
    resume();
  if (isRef(interval) || typeof interval === "function") {
    const stopWatch = watch(interval, () => {
      if (isActive.value && isClient)
        resume();
    });
    tryOnScopeDispose(stopWatch);
  }
  tryOnScopeDispose(pause);
  return {
    isActive,
    pause,
    resume
  };
}

function useInterval(interval = 1e3, options = {}) {
  const {
    controls: exposeControls = false,
    immediate = true,
    callback
  } = options;
  const counter = shallowRef(0);
  const update = () => counter.value += 1;
  const reset = () => {
    counter.value = 0;
  };
  const controls = useIntervalFn(
    callback ? () => {
      update();
      callback(counter.value);
    } : update,
    interval,
    { immediate }
  );
  if (exposeControls) {
    return {
      counter,
      reset,
      ...controls
    };
  } else {
    return counter;
  }
}

function useLastChanged(source, options = {}) {
  var _a;
  const ms = shallowRef((_a = options.initialValue) != null ? _a : null);
  watch(
    source,
    () => ms.value = timestamp(),
    options
  );
  return ms;
}

function useTimeoutFn(cb, interval, options = {}) {
  const {
    immediate = true,
    immediateCallback = false
  } = options;
  const isPending = shallowRef(false);
  let timer = null;
  function clear() {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
  }
  function stop() {
    isPending.value = false;
    clear();
  }
  function start(...args) {
    if (immediateCallback)
      cb();
    clear();
    isPending.value = true;
    timer = setTimeout(() => {
      isPending.value = false;
      timer = null;
      cb(...args);
    }, toValue$1(interval));
  }
  if (immediate) {
    isPending.value = true;
    if (isClient)
      start();
  }
  tryOnScopeDispose(stop);
  return {
    isPending: readonly(isPending),
    start,
    stop
  };
}

function useTimeout(interval = 1e3, options = {}) {
  const {
    controls: exposeControls = false,
    callback
  } = options;
  const controls = useTimeoutFn(
    callback != null ? callback : noop$3,
    interval,
    options
  );
  const ready = computed(() => !controls.isPending.value);
  if (exposeControls) {
    return {
      ready,
      ...controls
    };
  } else {
    return ready;
  }
}

function useToNumber(value, options = {}) {
  const {
    method = "parseFloat",
    radix,
    nanToZero
  } = options;
  return computed(() => {
    let resolved = toValue$1(value);
    if (typeof method === "function")
      resolved = method(resolved);
    else if (typeof resolved === "string")
      resolved = Number[method](resolved, radix);
    if (nanToZero && Number.isNaN(resolved))
      resolved = 0;
    return resolved;
  });
}

function useToString(value) {
  return computed(() => `${toValue$1(value)}`);
}

function useToggle(initialValue = false, options = {}) {
  const {
    truthyValue = true,
    falsyValue = false
  } = options;
  const valueIsRef = isRef(initialValue);
  const _value = shallowRef(initialValue);
  function toggle(value) {
    if (arguments.length) {
      _value.value = value;
      return _value.value;
    } else {
      const truthy = toValue$1(truthyValue);
      _value.value = _value.value === truthy ? toValue$1(falsyValue) : truthy;
      return _value.value;
    }
  }
  if (valueIsRef)
    return toggle;
  else
    return [_value, toggle];
}

function watchArray(source, cb, options) {
  let oldList = (options == null ? void 0 : options.immediate) ? [] : [...typeof source === "function" ? source() : Array.isArray(source) ? source : toValue$1(source)];
  return watch(source, (newList, _, onCleanup) => {
    const oldListRemains = Array.from({ length: oldList.length });
    const added = [];
    for (const obj of newList) {
      let found = false;
      for (let i = 0; i < oldList.length; i++) {
        if (!oldListRemains[i] && obj === oldList[i]) {
          oldListRemains[i] = true;
          found = true;
          break;
        }
      }
      if (!found)
        added.push(obj);
    }
    const removed = oldList.filter((_2, i) => !oldListRemains[i]);
    cb(newList, oldList, added, removed, onCleanup);
    oldList = [...newList];
  }, options);
}

function watchAtMost(source, cb, options) {
  const {
    count,
    ...watchOptions
  } = options;
  const current = shallowRef(0);
  const stop = watchWithFilter(
    source,
    (...args) => {
      current.value += 1;
      if (current.value >= toValue$1(count))
        nextTick(() => stop());
      cb(...args);
    },
    watchOptions
  );
  return { count: current, stop };
}

function watchDebounced(source, cb, options = {}) {
  const {
    debounce = 0,
    maxWait = void 0,
    ...watchOptions
  } = options;
  return watchWithFilter(
    source,
    cb,
    {
      ...watchOptions,
      eventFilter: debounceFilter(debounce, { maxWait })
    }
  );
}

function watchDeep(source, cb, options) {
  return watch(
    source,
    cb,
    {
      ...options,
      deep: true
    }
  );
}

function watchIgnorable(source, cb, options = {}) {
  const {
    eventFilter = bypassFilter,
    ...watchOptions
  } = options;
  const filteredCb = createFilterWrapper(
    eventFilter,
    cb
  );
  let ignoreUpdates;
  let ignorePrevAsyncUpdates;
  let stop;
  if (watchOptions.flush === "sync") {
    const ignore = shallowRef(false);
    ignorePrevAsyncUpdates = () => {
    };
    ignoreUpdates = (updater) => {
      ignore.value = true;
      updater();
      ignore.value = false;
    };
    stop = watch(
      source,
      (...args) => {
        if (!ignore.value)
          filteredCb(...args);
      },
      watchOptions
    );
  } else {
    const disposables = [];
    const ignoreCounter = shallowRef(0);
    const syncCounter = shallowRef(0);
    ignorePrevAsyncUpdates = () => {
      ignoreCounter.value = syncCounter.value;
    };
    disposables.push(
      watch(
        source,
        () => {
          syncCounter.value++;
        },
        { ...watchOptions, flush: "sync" }
      )
    );
    ignoreUpdates = (updater) => {
      const syncCounterPrev = syncCounter.value;
      updater();
      ignoreCounter.value += syncCounter.value - syncCounterPrev;
    };
    disposables.push(
      watch(
        source,
        (...args) => {
          const ignore = ignoreCounter.value > 0 && ignoreCounter.value === syncCounter.value;
          ignoreCounter.value = 0;
          syncCounter.value = 0;
          if (ignore)
            return;
          filteredCb(...args);
        },
        watchOptions
      )
    );
    stop = () => {
      disposables.forEach((fn) => fn());
    };
  }
  return { stop, ignoreUpdates, ignorePrevAsyncUpdates };
}

function watchImmediate(source, cb, options) {
  return watch(
    source,
    cb,
    {
      ...options,
      immediate: true
    }
  );
}

function watchOnce(source, cb, options) {
  const stop = watch(source, (...args) => {
    nextTick(() => stop());
    return cb(...args);
  }, options);
  return stop;
}

function watchThrottled(source, cb, options = {}) {
  const {
    throttle = 0,
    trailing = true,
    leading = true,
    ...watchOptions
  } = options;
  return watchWithFilter(
    source,
    cb,
    {
      ...watchOptions,
      eventFilter: throttleFilter(throttle, trailing, leading)
    }
  );
}

function watchTriggerable(source, cb, options = {}) {
  let cleanupFn;
  function onEffect() {
    if (!cleanupFn)
      return;
    const fn = cleanupFn;
    cleanupFn = void 0;
    fn();
  }
  function onCleanup(callback) {
    cleanupFn = callback;
  }
  const _cb = (value, oldValue) => {
    onEffect();
    return cb(value, oldValue, onCleanup);
  };
  const res = watchIgnorable(source, _cb, options);
  const { ignoreUpdates } = res;
  const trigger = () => {
    let res2;
    ignoreUpdates(() => {
      res2 = _cb(getWatchSources(source), getOldValue(source));
    });
    return res2;
  };
  return {
    ...res,
    trigger
  };
}
function getWatchSources(sources) {
  if (isReactive(sources))
    return sources;
  if (Array.isArray(sources))
    return sources.map((item) => toValue$1(item));
  return toValue$1(sources);
}
function getOldValue(source) {
  return Array.isArray(source) ? source.map(() => void 0) : void 0;
}

function whenever(source, cb, options) {
  const stop = watch(
    source,
    (v, ov, onInvalidate) => {
      if (v) {
        if (options == null ? void 0 : options.once)
          nextTick(() => stop());
        cb(v, ov, onInvalidate);
      }
    },
    {
      ...options,
      once: false
    }
  );
  return stop;
}

function computedAsync(evaluationCallback, initialState, optionsOrRef) {
  let options;
  if (isRef(optionsOrRef)) {
    options = {
      evaluating: optionsOrRef
    };
  } else {
    options = optionsOrRef || {};
  }
  const {
    lazy = false,
    evaluating = void 0,
    shallow = true,
    onError = noop$3
  } = options;
  const started = shallowRef(!lazy);
  const current = shallow ? shallowRef(initialState) : ref(initialState);
  let counter = 0;
  watchEffect(async (onInvalidate) => {
    if (!started.value)
      return;
    counter++;
    const counterAtBeginning = counter;
    let hasFinished = false;
    if (evaluating) {
      Promise.resolve().then(() => {
        evaluating.value = true;
      });
    }
    try {
      const result = await evaluationCallback((cancelCallback) => {
        onInvalidate(() => {
          if (evaluating)
            evaluating.value = false;
          if (!hasFinished)
            cancelCallback();
        });
      });
      if (counterAtBeginning === counter)
        current.value = result;
    } catch (e) {
      onError(e);
    } finally {
      if (evaluating && counterAtBeginning === counter)
        evaluating.value = false;
      hasFinished = true;
    }
  });
  if (lazy) {
    return computed(() => {
      started.value = true;
      return current.value;
    });
  } else {
    return current;
  }
}
function computedInject(key, options, defaultSource, treatDefaultAsFactory) {
  let source = inject(key);
  if (defaultSource)
    source = inject(key, defaultSource);
  if (treatDefaultAsFactory)
    source = inject(key, defaultSource, treatDefaultAsFactory);
  if (typeof options === "function") {
    return computed((ctx) => options(source, ctx));
  } else {
    return computed({
      get: (ctx) => options.get(source, ctx),
      set: options.set
    });
  }
}
function createReusableTemplate(options = {}) {
  const {
    inheritAttrs = true
  } = options;
  const render = shallowRef();
  const define = /* @__PURE__ */ defineComponent({
    setup(_, { slots }) {
      return () => {
        render.value = slots.default;
      };
    }
  });
  const reuse = /* @__PURE__ */ defineComponent({
    inheritAttrs,
    props: options.props,
    setup(props, { attrs, slots }) {
      return () => {
        var _a;
        if (!render.value && false)
          throw new Error("[VueUse] Failed to find the definition of reusable template");
        const vnode = (_a = render.value) == null ? void 0 : _a.call(render, {
          ...options.props == null ? keysToCamelKebabCase(attrs) : props,
          $slots: slots
        });
        return inheritAttrs && (vnode == null ? void 0 : vnode.length) === 1 ? vnode[0] : vnode;
      };
    }
  });
  return makeDestructurable(
    { define, reuse },
    [define, reuse]
  );
}
function keysToCamelKebabCase(obj) {
  const newObj = {};
  for (const key in obj)
    newObj[camelize(key)] = obj[key];
  return newObj;
}
function createTemplatePromise(options = {}) {
  let index = 0;
  const instances = ref([]);
  function create(...args) {
    const props = shallowReactive({
      key: index++,
      args,
      promise: void 0,
      resolve: () => {
      },
      reject: () => {
      },
      isResolving: false,
      options
    });
    instances.value.push(props);
    props.promise = new Promise((_resolve, _reject) => {
      props.resolve = (v) => {
        props.isResolving = true;
        return _resolve(v);
      };
      props.reject = _reject;
    }).finally(() => {
      props.promise = void 0;
      const index2 = instances.value.indexOf(props);
      if (index2 !== -1)
        instances.value.splice(index2, 1);
    });
    return props.promise;
  }
  function start(...args) {
    if (options.singleton && instances.value.length > 0)
      return instances.value[0].promise;
    return create(...args);
  }
  const component = /* @__PURE__ */ defineComponent((_, { slots }) => {
    const renderList = () => instances.value.map((props) => {
      var _a;
      return h(Fragment, { key: props.key }, (_a = slots.default) == null ? void 0 : _a.call(slots, props));
    });
    if (options.transition)
      return () => h(TransitionGroup, options.transition, renderList);
    return renderList;
  });
  component.start = start;
  return component;
}
function createUnrefFn(fn) {
  return function(...args) {
    return fn.apply(this, args.map((i) => toValue$1(i)));
  };
}
const defaultWindow = isClient ? window : void 0;
const defaultDocument = isClient ? window.document : void 0;
const defaultNavigator = isClient ? window.navigator : void 0;
const defaultLocation = isClient ? window.location : void 0;
function unrefElement(elRef) {
  var _a;
  const plain = toValue$1(elRef);
  return (_a = plain == null ? void 0 : plain.$el) != null ? _a : plain;
}
function useEventListener(...args) {
  const cleanups = [];
  const cleanup = () => {
    cleanups.forEach((fn) => fn());
    cleanups.length = 0;
  };
  const register = (el, event, listener, options) => {
    el.addEventListener(event, listener, options);
    return () => el.removeEventListener(event, listener, options);
  };
  const firstParamTargets = computed(() => {
    const test = toArray$1(toValue$1(args[0])).filter((e) => e != null);
    return test.every((e) => typeof e !== "string") ? test : void 0;
  });
  const stopWatch = watchImmediate(
    () => {
      var _a, _b;
      return [
        (_b = (_a = firstParamTargets.value) == null ? void 0 : _a.map((e) => unrefElement(e))) != null ? _b : [defaultWindow].filter((e) => e != null),
        toArray$1(toValue$1(firstParamTargets.value ? args[1] : args[0])),
        toArray$1(unref(firstParamTargets.value ? args[2] : args[1])),
        // @ts-expect-error - TypeScript gets the correct types, but somehow still complains
        toValue$1(firstParamTargets.value ? args[3] : args[2])
      ];
    },
    ([raw_targets, raw_events, raw_listeners, raw_options]) => {
      cleanup();
      if (!(raw_targets == null ? void 0 : raw_targets.length) || !(raw_events == null ? void 0 : raw_events.length) || !(raw_listeners == null ? void 0 : raw_listeners.length))
        return;
      const optionsClone = isObject$2(raw_options) ? { ...raw_options } : raw_options;
      cleanups.push(
        ...raw_targets.flatMap(
          (el) => raw_events.flatMap(
            (event) => raw_listeners.map((listener) => register(el, event, listener, optionsClone))
          )
        )
      );
    },
    { flush: "post" }
  );
  const stop = () => {
    stopWatch();
    cleanup();
  };
  tryOnScopeDispose(cleanup);
  return stop;
}
let _iOSWorkaround = false;
function onClickOutside(target, handler, options = {}) {
  const { window: window2 = defaultWindow, ignore = [], capture = true, detectIframe = false, controls = false } = options;
  if (!window2) {
    return controls ? { stop: noop$3, cancel: noop$3, trigger: noop$3 } : noop$3;
  }
  if (isIOS && !_iOSWorkaround) {
    _iOSWorkaround = true;
    const listenerOptions = { passive: true };
    Array.from(window2.document.body.children).forEach((el) => useEventListener(el, "click", noop$3, listenerOptions));
    useEventListener(window2.document.documentElement, "click", noop$3, listenerOptions);
  }
  let shouldListen = true;
  const shouldIgnore = (event) => {
    return toValue$1(ignore).some((target2) => {
      if (typeof target2 === "string") {
        return Array.from(window2.document.querySelectorAll(target2)).some((el) => el === event.target || event.composedPath().includes(el));
      } else {
        const el = unrefElement(target2);
        return el && (event.target === el || event.composedPath().includes(el));
      }
    });
  };
  function hasMultipleRoots(target2) {
    const vm = toValue$1(target2);
    return vm && vm.$.subTree.shapeFlag === 16;
  }
  function checkMultipleRoots(target2, event) {
    const vm = toValue$1(target2);
    const children = vm.$.subTree && vm.$.subTree.children;
    if (children == null || !Array.isArray(children))
      return false;
    return children.some((child) => child.el === event.target || event.composedPath().includes(child.el));
  }
  const listener = (event) => {
    const el = unrefElement(target);
    if (event.target == null)
      return;
    if (!(el instanceof Element) && hasMultipleRoots(target) && checkMultipleRoots(target, event))
      return;
    if (!el || el === event.target || event.composedPath().includes(el))
      return;
    if ("detail" in event && event.detail === 0)
      shouldListen = !shouldIgnore(event);
    if (!shouldListen) {
      shouldListen = true;
      return;
    }
    handler(event);
  };
  let isProcessingClick = false;
  const cleanup = [
    useEventListener(window2, "click", (event) => {
      if (!isProcessingClick) {
        isProcessingClick = true;
        setTimeout(() => {
          isProcessingClick = false;
        }, 0);
        listener(event);
      }
    }, { passive: true, capture }),
    useEventListener(window2, "pointerdown", (e) => {
      const el = unrefElement(target);
      shouldListen = !shouldIgnore(e) && !!(el && !e.composedPath().includes(el));
    }, { passive: true }),
    detectIframe && useEventListener(window2, "blur", (event) => {
      setTimeout(() => {
        var _a;
        const el = unrefElement(target);
        if (((_a = window2.document.activeElement) == null ? void 0 : _a.tagName) === "IFRAME" && !(el == null ? void 0 : el.contains(window2.document.activeElement))) {
          handler(event);
        }
      }, 0);
    }, { passive: true })
  ].filter(Boolean);
  const stop = () => cleanup.forEach((fn) => fn());
  if (controls) {
    return {
      stop,
      cancel: () => {
        shouldListen = false;
      },
      trigger: (event) => {
        shouldListen = true;
        listener(event);
        shouldListen = false;
      }
    };
  }
  return stop;
}
function useMounted() {
  const isMounted = shallowRef(false);
  const instance = getCurrentInstance();
  if (instance) {
    onMounted(() => {
      isMounted.value = true;
    }, instance);
  }
  return isMounted;
}
function useSupported(callback) {
  const isMounted = useMounted();
  return computed(() => {
    isMounted.value;
    return Boolean(callback());
  });
}
function useMutationObserver(target, callback, options = {}) {
  const { window: window2 = defaultWindow, ...mutationOptions } = options;
  let observer;
  const isSupported = useSupported(() => window2 && "MutationObserver" in window2);
  const cleanup = () => {
    if (observer) {
      observer.disconnect();
      observer = void 0;
    }
  };
  const targets = computed(() => {
    const value = toValue$1(target);
    const items = toArray$1(value).map(unrefElement).filter(notNullish);
    return new Set(items);
  });
  const stopWatch = watch(
    () => targets.value,
    (targets2) => {
      cleanup();
      if (isSupported.value && targets2.size) {
        observer = new MutationObserver(callback);
        targets2.forEach((el) => observer.observe(el, mutationOptions));
      }
    },
    { immediate: true, flush: "post" }
  );
  const takeRecords = () => {
    return observer == null ? void 0 : observer.takeRecords();
  };
  const stop = () => {
    stopWatch();
    cleanup();
  };
  tryOnScopeDispose(stop);
  return {
    isSupported,
    stop,
    takeRecords
  };
}
function onElementRemoval(target, callback, options = {}) {
  const {
    window: window2 = defaultWindow,
    document: document2 = window2 == null ? void 0 : window2.document,
    flush = "sync"
  } = options;
  if (!window2 || !document2)
    return noop$3;
  let stopFn;
  const cleanupAndUpdate = (fn) => {
    stopFn == null ? void 0 : stopFn();
    stopFn = fn;
  };
  const stopWatch = watchEffect(() => {
    const el = unrefElement(target);
    if (el) {
      const { stop } = useMutationObserver(
        document2,
        (mutationsList) => {
          const targetRemoved = mutationsList.map((mutation) => [...mutation.removedNodes]).flat().some((node) => node === el || node.contains(el));
          if (targetRemoved) {
            callback(mutationsList);
          }
        },
        {
          window: window2,
          childList: true,
          subtree: true
        }
      );
      cleanupAndUpdate(stop);
    }
  }, { flush });
  const stopHandle = () => {
    stopWatch();
    cleanupAndUpdate();
  };
  tryOnScopeDispose(stopHandle);
  return stopHandle;
}
function createKeyPredicate(keyFilter) {
  if (typeof keyFilter === "function")
    return keyFilter;
  else if (typeof keyFilter === "string")
    return (event) => event.key === keyFilter;
  else if (Array.isArray(keyFilter))
    return (event) => keyFilter.includes(event.key);
  return () => true;
}
function onKeyStroke(...args) {
  let key;
  let handler;
  let options = {};
  if (args.length === 3) {
    key = args[0];
    handler = args[1];
    options = args[2];
  } else if (args.length === 2) {
    if (typeof args[1] === "object") {
      key = true;
      handler = args[0];
      options = args[1];
    } else {
      key = args[0];
      handler = args[1];
    }
  } else {
    key = true;
    handler = args[0];
  }
  const {
    target = defaultWindow,
    eventName = "keydown",
    passive = false,
    dedupe = false
  } = options;
  const predicate = createKeyPredicate(key);
  const listener = (e) => {
    if (e.repeat && toValue$1(dedupe))
      return;
    if (predicate(e))
      handler(e);
  };
  return useEventListener(target, eventName, listener, passive);
}
function onKeyDown(key, handler, options = {}) {
  return onKeyStroke(key, handler, { ...options, eventName: "keydown" });
}
function onKeyPressed(key, handler, options = {}) {
  return onKeyStroke(key, handler, { ...options, eventName: "keypress" });
}
function onKeyUp(key, handler, options = {}) {
  return onKeyStroke(key, handler, { ...options, eventName: "keyup" });
}
const DEFAULT_DELAY = 500;
const DEFAULT_THRESHOLD = 10;
function onLongPress(target, handler, options) {
  var _a, _b;
  const elementRef = computed(() => unrefElement(target));
  let timeout;
  let posStart;
  let startTimestamp;
  let hasLongPressed = false;
  function clear() {
    if (timeout) {
      clearTimeout(timeout);
      timeout = void 0;
    }
    posStart = void 0;
    startTimestamp = void 0;
    hasLongPressed = false;
  }
  function onRelease(ev) {
    var _a2, _b2, _c;
    const [_startTimestamp, _posStart, _hasLongPressed] = [startTimestamp, posStart, hasLongPressed];
    clear();
    if (!(options == null ? void 0 : options.onMouseUp) || !_posStart || !_startTimestamp)
      return;
    if (((_a2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _a2.self) && ev.target !== elementRef.value)
      return;
    if ((_b2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _b2.prevent)
      ev.preventDefault();
    if ((_c = options == null ? void 0 : options.modifiers) == null ? void 0 : _c.stop)
      ev.stopPropagation();
    const dx = ev.x - _posStart.x;
    const dy = ev.y - _posStart.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    options.onMouseUp(ev.timeStamp - _startTimestamp, distance, _hasLongPressed);
  }
  function onDown(ev) {
    var _a2, _b2, _c, _d;
    if (((_a2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _a2.self) && ev.target !== elementRef.value)
      return;
    clear();
    if ((_b2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _b2.prevent)
      ev.preventDefault();
    if ((_c = options == null ? void 0 : options.modifiers) == null ? void 0 : _c.stop)
      ev.stopPropagation();
    posStart = {
      x: ev.x,
      y: ev.y
    };
    startTimestamp = ev.timeStamp;
    timeout = setTimeout(
      () => {
        hasLongPressed = true;
        handler(ev);
      },
      (_d = options == null ? void 0 : options.delay) != null ? _d : DEFAULT_DELAY
    );
  }
  function onMove(ev) {
    var _a2, _b2, _c, _d;
    if (((_a2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _a2.self) && ev.target !== elementRef.value)
      return;
    if (!posStart || (options == null ? void 0 : options.distanceThreshold) === false)
      return;
    if ((_b2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _b2.prevent)
      ev.preventDefault();
    if ((_c = options == null ? void 0 : options.modifiers) == null ? void 0 : _c.stop)
      ev.stopPropagation();
    const dx = ev.x - posStart.x;
    const dy = ev.y - posStart.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    if (distance >= ((_d = options == null ? void 0 : options.distanceThreshold) != null ? _d : DEFAULT_THRESHOLD))
      clear();
  }
  const listenerOptions = {
    capture: (_a = options == null ? void 0 : options.modifiers) == null ? void 0 : _a.capture,
    once: (_b = options == null ? void 0 : options.modifiers) == null ? void 0 : _b.once
  };
  const cleanup = [
    useEventListener(elementRef, "pointerdown", onDown, listenerOptions),
    useEventListener(elementRef, "pointermove", onMove, listenerOptions),
    useEventListener(elementRef, ["pointerup", "pointerleave"], onRelease, listenerOptions)
  ];
  const stop = () => cleanup.forEach((fn) => fn());
  return stop;
}
function isFocusedElementEditable() {
  const { activeElement, body } = document;
  if (!activeElement)
    return false;
  if (activeElement === body)
    return false;
  switch (activeElement.tagName) {
    case "INPUT":
    case "TEXTAREA":
      return true;
  }
  return activeElement.hasAttribute("contenteditable");
}
function isTypedCharValid({
  keyCode,
  metaKey,
  ctrlKey,
  altKey
}) {
  if (metaKey || ctrlKey || altKey)
    return false;
  if (keyCode >= 48 && keyCode <= 57 || keyCode >= 96 && keyCode <= 105)
    return true;
  if (keyCode >= 65 && keyCode <= 90)
    return true;
  return false;
}
function onStartTyping(callback, options = {}) {
  const { document: document2 = defaultDocument } = options;
  const keydown = (event) => {
    if (!isFocusedElementEditable() && isTypedCharValid(event)) {
      callback(event);
    }
  };
  if (document2)
    useEventListener(document2, "keydown", keydown, { passive: true });
}
function templateRef(key, initialValue = null) {
  const instance = getCurrentInstance();
  let _trigger = () => {
  };
  const element = customRef((track, trigger) => {
    _trigger = trigger;
    return {
      get() {
        var _a, _b;
        track();
        return (_b = (_a = instance == null ? void 0 : instance.proxy) == null ? void 0 : _a.$refs[key]) != null ? _b : initialValue;
      },
      set() {
      }
    };
  });
  tryOnMounted(_trigger);
  onUpdated(_trigger);
  return element;
}
function useActiveElement(options = {}) {
  var _a;
  const {
    window: window2 = defaultWindow,
    deep = true,
    triggerOnRemoval = false
  } = options;
  const document2 = (_a = options.document) != null ? _a : window2 == null ? void 0 : window2.document;
  const getDeepActiveElement = () => {
    var _a2;
    let element = document2 == null ? void 0 : document2.activeElement;
    if (deep) {
      while (element == null ? void 0 : element.shadowRoot)
        element = (_a2 = element == null ? void 0 : element.shadowRoot) == null ? void 0 : _a2.activeElement;
    }
    return element;
  };
  const activeElement = shallowRef();
  const trigger = () => {
    activeElement.value = getDeepActiveElement();
  };
  if (window2) {
    const listenerOptions = {
      capture: true,
      passive: true
    };
    useEventListener(
      window2,
      "blur",
      (event) => {
        if (event.relatedTarget !== null)
          return;
        trigger();
      },
      listenerOptions
    );
    useEventListener(
      window2,
      "focus",
      trigger,
      listenerOptions
    );
  }
  if (triggerOnRemoval) {
    onElementRemoval(activeElement, trigger, { document: document2 });
  }
  trigger();
  return activeElement;
}
function useRafFn(fn, options = {}) {
  const {
    immediate = true,
    fpsLimit = void 0,
    window: window2 = defaultWindow,
    once = false
  } = options;
  const isActive = shallowRef(false);
  const intervalLimit = computed(() => {
    return fpsLimit ? 1e3 / toValue$1(fpsLimit) : null;
  });
  let previousFrameTimestamp = 0;
  let rafId = null;
  function loop(timestamp2) {
    if (!isActive.value || !window2)
      return;
    if (!previousFrameTimestamp)
      previousFrameTimestamp = timestamp2;
    const delta = timestamp2 - previousFrameTimestamp;
    if (intervalLimit.value && delta < intervalLimit.value) {
      rafId = window2.requestAnimationFrame(loop);
      return;
    }
    previousFrameTimestamp = timestamp2;
    fn({ delta, timestamp: timestamp2 });
    if (once) {
      isActive.value = false;
      rafId = null;
      return;
    }
    rafId = window2.requestAnimationFrame(loop);
  }
  function resume() {
    if (!isActive.value && window2) {
      isActive.value = true;
      previousFrameTimestamp = 0;
      rafId = window2.requestAnimationFrame(loop);
    }
  }
  function pause() {
    isActive.value = false;
    if (rafId != null && window2) {
      window2.cancelAnimationFrame(rafId);
      rafId = null;
    }
  }
  if (immediate)
    resume();
  tryOnScopeDispose(pause);
  return {
    isActive: readonly(isActive),
    pause,
    resume
  };
}
function useAnimate(target, keyframes, options) {
  let config;
  let animateOptions;
  if (isObject$2(options)) {
    config = options;
    animateOptions = objectOmit(options, ["window", "immediate", "commitStyles", "persist", "onReady", "onError"]);
  } else {
    config = { duration: options };
    animateOptions = options;
  }
  const {
    window: window2 = defaultWindow,
    immediate = true,
    commitStyles,
    persist,
    playbackRate: _playbackRate = 1,
    onReady,
    onError = (e) => {
      console.error(e);
    }
  } = config;
  const isSupported = useSupported(() => window2 && HTMLElement && "animate" in HTMLElement.prototype);
  const animate = shallowRef(void 0);
  const store = shallowReactive({
    startTime: null,
    currentTime: null,
    timeline: null,
    playbackRate: _playbackRate,
    pending: false,
    playState: immediate ? "idle" : "paused",
    replaceState: "active"
  });
  const pending = computed(() => store.pending);
  const playState = computed(() => store.playState);
  const replaceState = computed(() => store.replaceState);
  const startTime = computed({
    get() {
      return store.startTime;
    },
    set(value) {
      store.startTime = value;
      if (animate.value)
        animate.value.startTime = value;
    }
  });
  const currentTime = computed({
    get() {
      return store.currentTime;
    },
    set(value) {
      store.currentTime = value;
      if (animate.value) {
        animate.value.currentTime = value;
        syncResume();
      }
    }
  });
  const timeline = computed({
    get() {
      return store.timeline;
    },
    set(value) {
      store.timeline = value;
      if (animate.value)
        animate.value.timeline = value;
    }
  });
  const playbackRate = computed({
    get() {
      return store.playbackRate;
    },
    set(value) {
      store.playbackRate = value;
      if (animate.value)
        animate.value.playbackRate = value;
    }
  });
  const play = () => {
    if (animate.value) {
      try {
        animate.value.play();
        syncResume();
      } catch (e) {
        syncPause();
        onError(e);
      }
    } else {
      update();
    }
  };
  const pause = () => {
    var _a;
    try {
      (_a = animate.value) == null ? void 0 : _a.pause();
      syncPause();
    } catch (e) {
      onError(e);
    }
  };
  const reverse = () => {
    var _a;
    if (!animate.value)
      update();
    try {
      (_a = animate.value) == null ? void 0 : _a.reverse();
      syncResume();
    } catch (e) {
      syncPause();
      onError(e);
    }
  };
  const finish = () => {
    var _a;
    try {
      (_a = animate.value) == null ? void 0 : _a.finish();
      syncPause();
    } catch (e) {
      onError(e);
    }
  };
  const cancel = () => {
    var _a;
    try {
      (_a = animate.value) == null ? void 0 : _a.cancel();
      syncPause();
    } catch (e) {
      onError(e);
    }
  };
  watch(() => unrefElement(target), (el) => {
    if (el) {
      update();
    } else {
      animate.value = void 0;
    }
  });
  watch(() => keyframes, (value) => {
    if (animate.value) {
      update();
      const targetEl = unrefElement(target);
      if (targetEl) {
        animate.value.effect = new KeyframeEffect(
          targetEl,
          toValue$1(value),
          animateOptions
        );
      }
    }
  }, { deep: true });
  tryOnMounted(() => update(true), false);
  tryOnScopeDispose(cancel);
  function update(init) {
    const el = unrefElement(target);
    if (!isSupported.value || !el)
      return;
    if (!animate.value)
      animate.value = el.animate(toValue$1(keyframes), animateOptions);
    if (persist)
      animate.value.persist();
    if (_playbackRate !== 1)
      animate.value.playbackRate = _playbackRate;
    if (init && !immediate)
      animate.value.pause();
    else
      syncResume();
    onReady == null ? void 0 : onReady(animate.value);
  }
  const listenerOptions = { passive: true };
  useEventListener(animate, ["cancel", "finish", "remove"], syncPause, listenerOptions);
  useEventListener(animate, "finish", () => {
    var _a;
    if (commitStyles)
      (_a = animate.value) == null ? void 0 : _a.commitStyles();
  }, listenerOptions);
  const { resume: resumeRef, pause: pauseRef } = useRafFn(() => {
    if (!animate.value)
      return;
    store.pending = animate.value.pending;
    store.playState = animate.value.playState;
    store.replaceState = animate.value.replaceState;
    store.startTime = animate.value.startTime;
    store.currentTime = animate.value.currentTime;
    store.timeline = animate.value.timeline;
    store.playbackRate = animate.value.playbackRate;
  }, { immediate: false });
  function syncResume() {
    if (isSupported.value)
      resumeRef();
  }
  function syncPause() {
    if (isSupported.value && window2)
      window2.requestAnimationFrame(pauseRef);
  }
  return {
    isSupported,
    animate,
    // actions
    play,
    pause,
    reverse,
    finish,
    cancel,
    // state
    pending,
    playState,
    replaceState,
    startTime,
    currentTime,
    timeline,
    playbackRate
  };
}
function useAsyncQueue(tasks, options) {
  const {
    interrupt = true,
    onError = noop$3,
    onFinished = noop$3,
    signal
  } = options || {};
  const promiseState = {
    aborted: "aborted",
    fulfilled: "fulfilled",
    pending: "pending",
    rejected: "rejected"
  };
  const initialResult = Array.from(Array.from({ length: tasks.length }), () => ({ state: promiseState.pending, data: null }));
  const result = reactive(initialResult);
  const activeIndex = shallowRef(-1);
  if (!tasks || tasks.length === 0) {
    onFinished();
    return {
      activeIndex,
      result
    };
  }
  function updateResult(state, res) {
    activeIndex.value++;
    result[activeIndex.value].data = res;
    result[activeIndex.value].state = state;
  }
  tasks.reduce((prev, curr) => {
    return prev.then((prevRes) => {
      var _a;
      if (signal == null ? void 0 : signal.aborted) {
        updateResult(promiseState.aborted, new Error("aborted"));
        return;
      }
      if (((_a = result[activeIndex.value]) == null ? void 0 : _a.state) === promiseState.rejected && interrupt) {
        onFinished();
        return;
      }
      const done = curr(prevRes).then((currentRes) => {
        updateResult(promiseState.fulfilled, currentRes);
        if (activeIndex.value === tasks.length - 1)
          onFinished();
        return currentRes;
      });
      if (!signal)
        return done;
      return Promise.race([done, whenAborted(signal)]);
    }).catch((e) => {
      if (signal == null ? void 0 : signal.aborted) {
        updateResult(promiseState.aborted, e);
        return e;
      }
      updateResult(promiseState.rejected, e);
      onError();
      return e;
    });
  }, Promise.resolve());
  return {
    activeIndex,
    result
  };
}
function whenAborted(signal) {
  return new Promise((resolve, reject) => {
    const error = new Error("aborted");
    if (signal.aborted)
      reject(error);
    else
      signal.addEventListener("abort", () => reject(error), { once: true });
  });
}
function useAsyncState(promise, initialState, options) {
  const {
    immediate = true,
    delay = 0,
    onError = noop$3,
    onSuccess = noop$3,
    resetOnExecute = true,
    shallow = true,
    throwError
  } = options != null ? options : {};
  const state = shallow ? shallowRef(initialState) : ref(initialState);
  const isReady = shallowRef(false);
  const isLoading = shallowRef(false);
  const error = shallowRef(void 0);
  async function execute(delay2 = 0, ...args) {
    if (resetOnExecute)
      state.value = initialState;
    error.value = void 0;
    isReady.value = false;
    isLoading.value = true;
    if (delay2 > 0)
      await promiseTimeout(delay2);
    const _promise = typeof promise === "function" ? promise(...args) : promise;
    try {
      const data = await _promise;
      state.value = data;
      isReady.value = true;
      onSuccess(data);
    } catch (e) {
      error.value = e;
      onError(e);
      if (throwError)
        throw e;
    } finally {
      isLoading.value = false;
    }
    return state.value;
  }
  if (immediate) {
    execute(delay);
  }
  const shell = {
    state,
    isReady,
    isLoading,
    error,
    execute
  };
  function waitUntilIsLoaded() {
    return new Promise((resolve, reject) => {
      until(isLoading).toBe(false).then(() => resolve(shell)).catch(reject);
    });
  }
  return {
    ...shell,
    then(onFulfilled, onRejected) {
      return waitUntilIsLoaded().then(onFulfilled, onRejected);
    }
  };
}
const defaults$2 = {
  array: (v) => JSON.stringify(v),
  object: (v) => JSON.stringify(v),
  set: (v) => JSON.stringify(Array.from(v)),
  map: (v) => JSON.stringify(Object.fromEntries(v)),
  null: () => ""
};
function getDefaultSerialization(target) {
  if (!target)
    return defaults$2.null;
  if (target instanceof Map)
    return defaults$2.map;
  else if (target instanceof Set)
    return defaults$2.set;
  else if (Array.isArray(target))
    return defaults$2.array;
  else
    return defaults$2.object;
}
function useBase64(target, options) {
  const base64 = shallowRef("");
  const promise = shallowRef();
  function execute() {
    if (!isClient)
      return;
    promise.value = new Promise((resolve, reject) => {
      try {
        const _target = toValue$1(target);
        if (_target == null) {
          resolve("");
        } else if (typeof _target === "string") {
          resolve(blobToBase64(new Blob([_target], { type: "text/plain" })));
        } else if (_target instanceof Blob) {
          resolve(blobToBase64(_target));
        } else if (_target instanceof ArrayBuffer) {
          resolve(window.btoa(String.fromCharCode(...new Uint8Array(_target))));
        } else if (_target instanceof HTMLCanvasElement) {
          resolve(_target.toDataURL(options == null ? void 0 : options.type, options == null ? void 0 : options.quality));
        } else if (_target instanceof HTMLImageElement) {
          const img = _target.cloneNode(false);
          img.crossOrigin = "Anonymous";
          imgLoaded(img).then(() => {
            const canvas = document.createElement("canvas");
            const ctx = canvas.getContext("2d");
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            resolve(canvas.toDataURL(options == null ? void 0 : options.type, options == null ? void 0 : options.quality));
          }).catch(reject);
        } else if (typeof _target === "object") {
          const _serializeFn = (options == null ? void 0 : options.serializer) || getDefaultSerialization(_target);
          const serialized = _serializeFn(_target);
          return resolve(blobToBase64(new Blob([serialized], { type: "application/json" })));
        } else {
          reject(new Error("target is unsupported types"));
        }
      } catch (error) {
        reject(error);
      }
    });
    promise.value.then((res) => {
      base64.value = (options == null ? void 0 : options.dataUrl) === false ? res.replace(/^data:.*?;base64,/, "") : res;
    });
    return promise.value;
  }
  if (isRef(target) || typeof target === "function")
    watch(target, execute, { immediate: true });
  else
    execute();
  return {
    base64,
    promise,
    execute
  };
}
function imgLoaded(img) {
  return new Promise((resolve, reject) => {
    if (!img.complete) {
      img.onload = () => {
        resolve();
      };
      img.onerror = reject;
    } else {
      resolve();
    }
  });
}
function blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const fr = new FileReader();
    fr.onload = (e) => {
      resolve(e.target.result);
    };
    fr.onerror = reject;
    fr.readAsDataURL(blob);
  });
}
function useBattery(options = {}) {
  const { navigator: navigator2 = defaultNavigator } = options;
  const events2 = ["chargingchange", "chargingtimechange", "dischargingtimechange", "levelchange"];
  const isSupported = useSupported(() => navigator2 && "getBattery" in navigator2 && typeof navigator2.getBattery === "function");
  const charging = shallowRef(false);
  const chargingTime = shallowRef(0);
  const dischargingTime = shallowRef(0);
  const level = shallowRef(1);
  let battery;
  function updateBatteryInfo() {
    charging.value = this.charging;
    chargingTime.value = this.chargingTime || 0;
    dischargingTime.value = this.dischargingTime || 0;
    level.value = this.level;
  }
  if (isSupported.value) {
    navigator2.getBattery().then((_battery) => {
      battery = _battery;
      updateBatteryInfo.call(battery);
      useEventListener(battery, events2, updateBatteryInfo, { passive: true });
    });
  }
  return {
    isSupported,
    charging,
    chargingTime,
    dischargingTime,
    level
  };
}
function useBluetooth(options) {
  let {
    acceptAllDevices = false
  } = options || {};
  const {
    filters = void 0,
    optionalServices = void 0,
    navigator: navigator2 = defaultNavigator
  } = options || {};
  const isSupported = useSupported(() => navigator2 && "bluetooth" in navigator2);
  const device = shallowRef();
  const error = shallowRef(null);
  watch(device, () => {
    connectToBluetoothGATTServer();
  });
  async function requestDevice() {
    if (!isSupported.value)
      return;
    error.value = null;
    if (filters && filters.length > 0)
      acceptAllDevices = false;
    try {
      device.value = await (navigator2 == null ? void 0 : navigator2.bluetooth.requestDevice({
        acceptAllDevices,
        filters,
        optionalServices
      }));
    } catch (err) {
      error.value = err;
    }
  }
  const server = shallowRef();
  const isConnected = shallowRef(false);
  function reset() {
    isConnected.value = false;
    device.value = void 0;
    server.value = void 0;
  }
  async function connectToBluetoothGATTServer() {
    error.value = null;
    if (device.value && device.value.gatt) {
      useEventListener(device, "gattserverdisconnected", reset, { passive: true });
      try {
        server.value = await device.value.gatt.connect();
        isConnected.value = server.value.connected;
      } catch (err) {
        error.value = err;
      }
    }
  }
  tryOnMounted(() => {
    var _a;
    if (device.value)
      (_a = device.value.gatt) == null ? void 0 : _a.connect();
  });
  tryOnScopeDispose(() => {
    var _a;
    if (device.value)
      (_a = device.value.gatt) == null ? void 0 : _a.disconnect();
  });
  return {
    isSupported,
    isConnected: readonly(isConnected),
    // Device:
    device,
    requestDevice,
    // Server:
    server,
    // Errors:
    error
  };
}
const ssrWidthSymbol = Symbol("vueuse-ssr-width");
function useSSRWidth() {
  const ssrWidth = hasInjectionContext() ? injectLocal(ssrWidthSymbol, null) : null;
  return typeof ssrWidth === "number" ? ssrWidth : void 0;
}
function provideSSRWidth(width, app) {
  if (app !== void 0) {
    app.provide(ssrWidthSymbol, width);
  } else {
    provideLocal(ssrWidthSymbol, width);
  }
}
function useMediaQuery(query, options = {}) {
  const { window: window2 = defaultWindow, ssrWidth = useSSRWidth() } = options;
  const isSupported = useSupported(() => window2 && "matchMedia" in window2 && typeof window2.matchMedia === "function");
  const ssrSupport = shallowRef(typeof ssrWidth === "number");
  const mediaQuery = shallowRef();
  const matches = shallowRef(false);
  const handler = (event) => {
    matches.value = event.matches;
  };
  watchEffect(() => {
    if (ssrSupport.value) {
      ssrSupport.value = !isSupported.value;
      const queryStrings = toValue$1(query).split(",");
      matches.value = queryStrings.some((queryString) => {
        const not = queryString.includes("not all");
        const minWidth = queryString.match(/\(\s*min-width:\s*(-?\d+(?:\.\d*)?[a-z]+\s*)\)/);
        const maxWidth = queryString.match(/\(\s*max-width:\s*(-?\d+(?:\.\d*)?[a-z]+\s*)\)/);
        let res = Boolean(minWidth || maxWidth);
        if (minWidth && res) {
          res = ssrWidth >= pxValue(minWidth[1]);
        }
        if (maxWidth && res) {
          res = ssrWidth <= pxValue(maxWidth[1]);
        }
        return not ? !res : res;
      });
      return;
    }
    if (!isSupported.value)
      return;
    mediaQuery.value = window2.matchMedia(toValue$1(query));
    matches.value = mediaQuery.value.matches;
  });
  useEventListener(mediaQuery, "change", handler, { passive: true });
  return computed(() => matches.value);
}
const breakpointsTailwind = {
  "sm": 640,
  "md": 768,
  "lg": 1024,
  "xl": 1280,
  "2xl": 1536
};
const breakpointsBootstrapV5 = {
  xs: 0,
  sm: 576,
  md: 768,
  lg: 992,
  xl: 1200,
  xxl: 1400
};
const breakpointsVuetifyV2 = {
  xs: 0,
  sm: 600,
  md: 960,
  lg: 1264,
  xl: 1904
};
const breakpointsVuetifyV3 = {
  xs: 0,
  sm: 600,
  md: 960,
  lg: 1280,
  xl: 1920,
  xxl: 2560
};
const breakpointsVuetify = breakpointsVuetifyV2;
const breakpointsAntDesign = {
  xs: 480,
  sm: 576,
  md: 768,
  lg: 992,
  xl: 1200,
  xxl: 1600
};
const breakpointsQuasar = {
  xs: 0,
  sm: 600,
  md: 1024,
  lg: 1440,
  xl: 1920
};
const breakpointsSematic = {
  mobileS: 320,
  mobileM: 375,
  mobileL: 425,
  tablet: 768,
  laptop: 1024,
  laptopL: 1440,
  desktop4K: 2560
};
const breakpointsMasterCss = {
  "3xs": 360,
  "2xs": 480,
  "xs": 600,
  "sm": 768,
  "md": 1024,
  "lg": 1280,
  "xl": 1440,
  "2xl": 1600,
  "3xl": 1920,
  "4xl": 2560
};
const breakpointsPrimeFlex = {
  sm: 576,
  md: 768,
  lg: 992,
  xl: 1200
};
const breakpointsElement = {
  xs: 0,
  sm: 768,
  md: 992,
  lg: 1200,
  xl: 1920
};
function useBreakpoints(breakpoints, options = {}) {
  function getValue2(k, delta) {
    let v = toValue$1(breakpoints[toValue$1(k)]);
    if (delta != null)
      v = increaseWithUnit(v, delta);
    if (typeof v === "number")
      v = `${v}px`;
    return v;
  }
  const { window: window2 = defaultWindow, strategy = "min-width", ssrWidth = useSSRWidth() } = options;
  const ssrSupport = typeof ssrWidth === "number";
  const mounted = ssrSupport ? shallowRef(false) : { value: true };
  if (ssrSupport) {
    tryOnMounted(() => mounted.value = !!window2);
  }
  function match(query, size) {
    if (!mounted.value && ssrSupport) {
      return query === "min" ? ssrWidth >= pxValue(size) : ssrWidth <= pxValue(size);
    }
    if (!window2)
      return false;
    return window2.matchMedia(`(${query}-width: ${size})`).matches;
  }
  const greaterOrEqual = (k) => {
    return useMediaQuery(() => `(min-width: ${getValue2(k)})`, options);
  };
  const smallerOrEqual = (k) => {
    return useMediaQuery(() => `(max-width: ${getValue2(k)})`, options);
  };
  const shortcutMethods = Object.keys(breakpoints).reduce((shortcuts, k) => {
    Object.defineProperty(shortcuts, k, {
      get: () => strategy === "min-width" ? greaterOrEqual(k) : smallerOrEqual(k),
      enumerable: true,
      configurable: true
    });
    return shortcuts;
  }, {});
  function current() {
    const points = Object.keys(breakpoints).map((k) => [k, shortcutMethods[k], pxValue(getValue2(k))]).sort((a, b) => a[2] - b[2]);
    return computed(() => points.filter(([, v]) => v.value).map(([k]) => k));
  }
  return Object.assign(shortcutMethods, {
    greaterOrEqual,
    smallerOrEqual,
    greater(k) {
      return useMediaQuery(() => `(min-width: ${getValue2(k, 0.1)})`, options);
    },
    smaller(k) {
      return useMediaQuery(() => `(max-width: ${getValue2(k, -0.1)})`, options);
    },
    between(a, b) {
      return useMediaQuery(() => `(min-width: ${getValue2(a)}) and (max-width: ${getValue2(b, -0.1)})`, options);
    },
    isGreater(k) {
      return match("min", getValue2(k, 0.1));
    },
    isGreaterOrEqual(k) {
      return match("min", getValue2(k));
    },
    isSmaller(k) {
      return match("max", getValue2(k, -0.1));
    },
    isSmallerOrEqual(k) {
      return match("max", getValue2(k));
    },
    isInBetween(a, b) {
      return match("min", getValue2(a)) && match("max", getValue2(b, -0.1));
    },
    current,
    active() {
      const bps = current();
      return computed(() => bps.value.length === 0 ? "" : bps.value.at(strategy === "min-width" ? -1 : 0));
    }
  });
}
function useBroadcastChannel(options) {
  const {
    name,
    window: window2 = defaultWindow
  } = options;
  const isSupported = useSupported(() => window2 && "BroadcastChannel" in window2);
  const isClosed = shallowRef(false);
  const channel = ref();
  const data = ref();
  const error = shallowRef(null);
  const post = (data2) => {
    if (channel.value)
      channel.value.postMessage(data2);
  };
  const close = () => {
    if (channel.value)
      channel.value.close();
    isClosed.value = true;
  };
  if (isSupported.value) {
    tryOnMounted(() => {
      error.value = null;
      channel.value = new BroadcastChannel(name);
      const listenerOptions = {
        passive: true
      };
      useEventListener(channel, "message", (e) => {
        data.value = e.data;
      }, listenerOptions);
      useEventListener(channel, "messageerror", (e) => {
        error.value = e;
      }, listenerOptions);
      useEventListener(channel, "close", () => {
        isClosed.value = true;
      }, listenerOptions);
    });
  }
  tryOnScopeDispose(() => {
    close();
  });
  return {
    isSupported,
    channel,
    data,
    post,
    close,
    error,
    isClosed
  };
}
const WRITABLE_PROPERTIES = [
  "hash",
  "host",
  "hostname",
  "href",
  "pathname",
  "port",
  "protocol",
  "search"
];
function useBrowserLocation(options = {}) {
  const { window: window2 = defaultWindow } = options;
  const refs = Object.fromEntries(
    WRITABLE_PROPERTIES.map((key) => [key, ref()])
  );
  for (const [key, ref2] of objectEntries(refs)) {
    watch(ref2, (value) => {
      if (!(window2 == null ? void 0 : window2.location) || window2.location[key] === value)
        return;
      window2.location[key] = value;
    });
  }
  const buildState = (trigger) => {
    var _a;
    const { state: state2, length } = (window2 == null ? void 0 : window2.history) || {};
    const { origin } = (window2 == null ? void 0 : window2.location) || {};
    for (const key of WRITABLE_PROPERTIES)
      refs[key].value = (_a = window2 == null ? void 0 : window2.location) == null ? void 0 : _a[key];
    return reactive({
      trigger,
      state: state2,
      length,
      origin,
      ...refs
    });
  };
  const state = ref(buildState("load"));
  if (window2) {
    const listenerOptions = { passive: true };
    useEventListener(window2, "popstate", () => state.value = buildState("popstate"), listenerOptions);
    useEventListener(window2, "hashchange", () => state.value = buildState("hashchange"), listenerOptions);
  }
  return state;
}
function useCached(refValue, comparator = (a, b) => a === b, options) {
  const { deepRefs = true, ...watchOptions } = options || {};
  const cachedValue = createRef(refValue.value, deepRefs);
  watch(() => refValue.value, (value) => {
    if (!comparator(value, cachedValue.value))
      cachedValue.value = value;
  }, watchOptions);
  return cachedValue;
}
function usePermission(permissionDesc, options = {}) {
  const {
    controls = false,
    navigator: navigator2 = defaultNavigator
  } = options;
  const isSupported = useSupported(() => navigator2 && "permissions" in navigator2);
  const permissionStatus = shallowRef();
  const desc = typeof permissionDesc === "string" ? { name: permissionDesc } : permissionDesc;
  const state = shallowRef();
  const update = () => {
    var _a, _b;
    state.value = (_b = (_a = permissionStatus.value) == null ? void 0 : _a.state) != null ? _b : "prompt";
  };
  useEventListener(permissionStatus, "change", update, { passive: true });
  const query = createSingletonPromise(async () => {
    if (!isSupported.value)
      return;
    if (!permissionStatus.value) {
      try {
        permissionStatus.value = await navigator2.permissions.query(desc);
      } catch (e) {
        permissionStatus.value = void 0;
      } finally {
        update();
      }
    }
    if (controls)
      return toRaw(permissionStatus.value);
  });
  query();
  if (controls) {
    return {
      state,
      isSupported,
      query
    };
  } else {
    return state;
  }
}
function useClipboard(options = {}) {
  const {
    navigator: navigator2 = defaultNavigator,
    read = false,
    source,
    copiedDuring = 1500,
    legacy = false
  } = options;
  const isClipboardApiSupported = useSupported(() => navigator2 && "clipboard" in navigator2);
  const permissionRead = usePermission("clipboard-read");
  const permissionWrite = usePermission("clipboard-write");
  const isSupported = computed(() => isClipboardApiSupported.value || legacy);
  const text = shallowRef("");
  const copied = shallowRef(false);
  const timeout = useTimeoutFn(() => copied.value = false, copiedDuring, { immediate: false });
  async function updateText() {
    let useLegacy = !(isClipboardApiSupported.value && isAllowed(permissionRead.value));
    if (!useLegacy) {
      try {
        text.value = await navigator2.clipboard.readText();
      } catch (e) {
        useLegacy = true;
      }
    }
    if (useLegacy) {
      text.value = legacyRead();
    }
  }
  if (isSupported.value && read)
    useEventListener(["copy", "cut"], updateText, { passive: true });
  async function copy(value = toValue$1(source)) {
    if (isSupported.value && value != null) {
      let useLegacy = !(isClipboardApiSupported.value && isAllowed(permissionWrite.value));
      if (!useLegacy) {
        try {
          await navigator2.clipboard.writeText(value);
        } catch (e) {
          useLegacy = true;
        }
      }
      if (useLegacy)
        legacyCopy(value);
      text.value = value;
      copied.value = true;
      timeout.start();
    }
  }
  function legacyCopy(value) {
    const ta = document.createElement("textarea");
    ta.value = value != null ? value : "";
    ta.style.position = "absolute";
    ta.style.opacity = "0";
    document.body.appendChild(ta);
    ta.select();
    document.execCommand("copy");
    ta.remove();
  }
  function legacyRead() {
    var _a, _b, _c;
    return (_c = (_b = (_a = document == null ? void 0 : document.getSelection) == null ? void 0 : _a.call(document)) == null ? void 0 : _b.toString()) != null ? _c : "";
  }
  function isAllowed(status) {
    return status === "granted" || status === "prompt";
  }
  return {
    isSupported,
    text,
    copied,
    copy
  };
}
function useClipboardItems(options = {}) {
  const {
    navigator: navigator2 = defaultNavigator,
    read = false,
    source,
    copiedDuring = 1500
  } = options;
  const isSupported = useSupported(() => navigator2 && "clipboard" in navigator2);
  const content = ref([]);
  const copied = shallowRef(false);
  const timeout = useTimeoutFn(() => copied.value = false, copiedDuring, { immediate: false });
  function updateContent() {
    if (isSupported.value) {
      navigator2.clipboard.read().then((items) => {
        content.value = items;
      });
    }
  }
  if (isSupported.value && read)
    useEventListener(["copy", "cut"], updateContent, { passive: true });
  async function copy(value = toValue$1(source)) {
    if (isSupported.value && value != null) {
      await navigator2.clipboard.write(value);
      content.value = value;
      copied.value = true;
      timeout.start();
    }
  }
  return {
    isSupported,
    content,
    copied,
    copy
  };
}
function cloneFnJSON(source) {
  return JSON.parse(JSON.stringify(source));
}
function useCloned(source, options = {}) {
  const cloned = ref({});
  const isModified = shallowRef(false);
  let _lastSync = false;
  const {
    manual,
    clone = cloneFnJSON,
    // watch options
    deep = true,
    immediate = true
  } = options;
  watch(cloned, () => {
    if (_lastSync) {
      _lastSync = false;
      return;
    }
    isModified.value = true;
  }, {
    deep: true,
    flush: "sync"
  });
  function sync() {
    _lastSync = true;
    isModified.value = false;
    cloned.value = clone(toValue$1(source));
  }
  if (!manual && (isRef(source) || typeof source === "function")) {
    watch(source, sync, {
      ...options,
      deep,
      immediate
    });
  } else {
    sync();
  }
  return { cloned, isModified, sync };
}
const _global$1 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
const globalKey = "__vueuse_ssr_handlers__";
const handlers = /* @__PURE__ */ getHandlers();
function getHandlers() {
  if (!(globalKey in _global$1))
    _global$1[globalKey] = _global$1[globalKey] || {};
  return _global$1[globalKey];
}
function getSSRHandler(key, fallback) {
  return handlers[key] || fallback;
}
function setSSRHandler(key, fn) {
  handlers[key] = fn;
}
function usePreferredDark(options) {
  return useMediaQuery("(prefers-color-scheme: dark)", options);
}
function guessSerializerType(rawInit) {
  return rawInit == null ? "any" : rawInit instanceof Set ? "set" : rawInit instanceof Map ? "map" : rawInit instanceof Date ? "date" : typeof rawInit === "boolean" ? "boolean" : typeof rawInit === "string" ? "string" : typeof rawInit === "object" ? "object" : !Number.isNaN(rawInit) ? "number" : "any";
}
const StorageSerializers = {
  boolean: {
    read: (v) => v === "true",
    write: (v) => String(v)
  },
  object: {
    read: (v) => JSON.parse(v),
    write: (v) => JSON.stringify(v)
  },
  number: {
    read: (v) => Number.parseFloat(v),
    write: (v) => String(v)
  },
  any: {
    read: (v) => v,
    write: (v) => String(v)
  },
  string: {
    read: (v) => v,
    write: (v) => String(v)
  },
  map: {
    read: (v) => new Map(JSON.parse(v)),
    write: (v) => JSON.stringify(Array.from(v.entries()))
  },
  set: {
    read: (v) => new Set(JSON.parse(v)),
    write: (v) => JSON.stringify(Array.from(v))
  },
  date: {
    read: (v) => new Date(v),
    write: (v) => v.toISOString()
  }
};
const customStorageEventName = "vueuse-storage";
function useStorage(key, defaults2, storage, options = {}) {
  var _a;
  const {
    flush = "pre",
    deep = true,
    listenToStorageChanges = true,
    writeDefaults = true,
    mergeDefaults = false,
    shallow,
    window: window2 = defaultWindow,
    eventFilter,
    onError = (e) => {
      console.error(e);
    },
    initOnMounted
  } = options;
  const data = (shallow ? shallowRef : ref)(typeof defaults2 === "function" ? defaults2() : defaults2);
  const keyComputed = computed(() => toValue$1(key));
  if (!storage) {
    try {
      storage = getSSRHandler("getDefaultStorage", () => {
        var _a2;
        return (_a2 = defaultWindow) == null ? void 0 : _a2.localStorage;
      })();
    } catch (e) {
      onError(e);
    }
  }
  if (!storage)
    return data;
  const rawInit = toValue$1(defaults2);
  const type = guessSerializerType(rawInit);
  const serializer = (_a = options.serializer) != null ? _a : StorageSerializers[type];
  const { pause: pauseWatch, resume: resumeWatch } = watchPausable(
    data,
    () => write(data.value),
    { flush, deep, eventFilter }
  );
  watch(keyComputed, () => update(), { flush });
  if (window2 && listenToStorageChanges) {
    tryOnMounted(() => {
      if (storage instanceof Storage)
        useEventListener(window2, "storage", update, { passive: true });
      else
        useEventListener(window2, customStorageEventName, updateFromCustomEvent);
      if (initOnMounted)
        update();
    });
  }
  if (!initOnMounted)
    update();
  function dispatchWriteEvent(oldValue, newValue) {
    if (window2) {
      const payload = {
        key: keyComputed.value,
        oldValue,
        newValue,
        storageArea: storage
      };
      window2.dispatchEvent(storage instanceof Storage ? new StorageEvent("storage", payload) : new CustomEvent(customStorageEventName, {
        detail: payload
      }));
    }
  }
  function write(v) {
    try {
      const oldValue = storage.getItem(keyComputed.value);
      if (v == null) {
        dispatchWriteEvent(oldValue, null);
        storage.removeItem(keyComputed.value);
      } else {
        const serialized = serializer.write(v);
        if (oldValue !== serialized) {
          storage.setItem(keyComputed.value, serialized);
          dispatchWriteEvent(oldValue, serialized);
        }
      }
    } catch (e) {
      onError(e);
    }
  }
  function read(event) {
    const rawValue = event ? event.newValue : storage.getItem(keyComputed.value);
    if (rawValue == null) {
      if (writeDefaults && rawInit != null)
        storage.setItem(keyComputed.value, serializer.write(rawInit));
      return rawInit;
    } else if (!event && mergeDefaults) {
      const value = serializer.read(rawValue);
      if (typeof mergeDefaults === "function")
        return mergeDefaults(value, rawInit);
      else if (type === "object" && !Array.isArray(value))
        return { ...rawInit, ...value };
      return value;
    } else if (typeof rawValue !== "string") {
      return rawValue;
    } else {
      return serializer.read(rawValue);
    }
  }
  function update(event) {
    if (event && event.storageArea !== storage)
      return;
    if (event && event.key == null) {
      data.value = rawInit;
      return;
    }
    if (event && event.key !== keyComputed.value)
      return;
    pauseWatch();
    try {
      if ((event == null ? void 0 : event.newValue) !== serializer.write(data.value))
        data.value = read(event);
    } catch (e) {
      onError(e);
    } finally {
      if (event)
        nextTick(resumeWatch);
      else
        resumeWatch();
    }
  }
  function updateFromCustomEvent(event) {
    update(event.detail);
  }
  return data;
}
const CSS_DISABLE_TRANS = "*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}";
function useColorMode(options = {}) {
  const {
    selector = "html",
    attribute = "class",
    initialValue = "auto",
    window: window2 = defaultWindow,
    storage,
    storageKey = "vueuse-color-scheme",
    listenToStorageChanges = true,
    storageRef,
    emitAuto,
    disableTransition = true
  } = options;
  const modes = {
    auto: "",
    light: "light",
    dark: "dark",
    ...options.modes || {}
  };
  const preferredDark = usePreferredDark({ window: window2 });
  const system = computed(() => preferredDark.value ? "dark" : "light");
  const store = storageRef || (storageKey == null ? toRef(initialValue) : useStorage(storageKey, initialValue, storage, { window: window2, listenToStorageChanges }));
  const state = computed(() => store.value === "auto" ? system.value : store.value);
  const updateHTMLAttrs = getSSRHandler(
    "updateHTMLAttrs",
    (selector2, attribute2, value) => {
      const el = typeof selector2 === "string" ? window2 == null ? void 0 : window2.document.querySelector(selector2) : unrefElement(selector2);
      if (!el)
        return;
      const classesToAdd = /* @__PURE__ */ new Set();
      const classesToRemove = /* @__PURE__ */ new Set();
      let attributeToChange = null;
      if (attribute2 === "class") {
        const current = value.split(/\s/g);
        Object.values(modes).flatMap((i) => (i || "").split(/\s/g)).filter(Boolean).forEach((v) => {
          if (current.includes(v))
            classesToAdd.add(v);
          else
            classesToRemove.add(v);
        });
      } else {
        attributeToChange = { key: attribute2, value };
      }
      if (classesToAdd.size === 0 && classesToRemove.size === 0 && attributeToChange === null)
        return;
      let style;
      if (disableTransition) {
        style = window2.document.createElement("style");
        style.appendChild(document.createTextNode(CSS_DISABLE_TRANS));
        window2.document.head.appendChild(style);
      }
      for (const c of classesToAdd) {
        el.classList.add(c);
      }
      for (const c of classesToRemove) {
        el.classList.remove(c);
      }
      if (attributeToChange) {
        el.setAttribute(attributeToChange.key, attributeToChange.value);
      }
      if (disableTransition) {
        window2.getComputedStyle(style).opacity;
        document.head.removeChild(style);
      }
    }
  );
  function defaultOnChanged(mode) {
    var _a;
    updateHTMLAttrs(selector, attribute, (_a = modes[mode]) != null ? _a : mode);
  }
  function onChanged(mode) {
    if (options.onChanged)
      options.onChanged(mode, defaultOnChanged);
    else
      defaultOnChanged(mode);
  }
  watch(state, onChanged, { flush: "post", immediate: true });
  tryOnMounted(() => onChanged(state.value));
  const auto = computed({
    get() {
      return emitAuto ? store.value : state.value;
    },
    set(v) {
      store.value = v;
    }
  });
  return Object.assign(auto, { store, system, state });
}
function useConfirmDialog(revealed = shallowRef(false)) {
  const confirmHook = createEventHook();
  const cancelHook = createEventHook();
  const revealHook = createEventHook();
  let _resolve = noop$3;
  const reveal = (data) => {
    revealHook.trigger(data);
    revealed.value = true;
    return new Promise((resolve) => {
      _resolve = resolve;
    });
  };
  const confirm = (data) => {
    revealed.value = false;
    confirmHook.trigger(data);
    _resolve({ data, isCanceled: false });
  };
  const cancel = (data) => {
    revealed.value = false;
    cancelHook.trigger(data);
    _resolve({ data, isCanceled: true });
  };
  return {
    isRevealed: computed(() => revealed.value),
    reveal,
    confirm,
    cancel,
    onReveal: revealHook.on,
    onConfirm: confirmHook.on,
    onCancel: cancelHook.on
  };
}
function useCountdown(initialCountdown, options) {
  var _a, _b;
  const remaining = shallowRef(toValue$1(initialCountdown));
  const intervalController = useIntervalFn(() => {
    var _a2, _b2;
    const value = remaining.value - 1;
    remaining.value = value < 0 ? 0 : value;
    (_a2 = options == null ? void 0 : options.onTick) == null ? void 0 : _a2.call(options);
    if (remaining.value <= 0) {
      intervalController.pause();
      (_b2 = options == null ? void 0 : options.onComplete) == null ? void 0 : _b2.call(options);
    }
  }, (_a = options == null ? void 0 : options.interval) != null ? _a : 1e3, { immediate: (_b = options == null ? void 0 : options.immediate) != null ? _b : false });
  const reset = (countdown) => {
    var _a2;
    remaining.value = (_a2 = toValue$1(countdown)) != null ? _a2 : toValue$1(initialCountdown);
  };
  const stop = () => {
    intervalController.pause();
    reset();
  };
  const resume = () => {
    if (!intervalController.isActive.value) {
      if (remaining.value > 0) {
        intervalController.resume();
      }
    }
  };
  const start = (countdown) => {
    reset(countdown);
    intervalController.resume();
  };
  return {
    remaining,
    reset,
    stop,
    start,
    pause: intervalController.pause,
    resume,
    isActive: intervalController.isActive
  };
}
function useCssVar(prop, target, options = {}) {
  const { window: window2 = defaultWindow, initialValue, observe = false } = options;
  const variable = shallowRef(initialValue);
  const elRef = computed(() => {
    var _a;
    return unrefElement(target) || ((_a = window2 == null ? void 0 : window2.document) == null ? void 0 : _a.documentElement);
  });
  function updateCssVar() {
    var _a;
    const key = toValue$1(prop);
    const el = toValue$1(elRef);
    if (el && window2 && key) {
      const value = (_a = window2.getComputedStyle(el).getPropertyValue(key)) == null ? void 0 : _a.trim();
      variable.value = value || variable.value || initialValue;
    }
  }
  if (observe) {
    useMutationObserver(elRef, updateCssVar, {
      attributeFilter: ["style", "class"],
      window: window2
    });
  }
  watch(
    [elRef, () => toValue$1(prop)],
    (_, old) => {
      if (old[0] && old[1])
        old[0].style.removeProperty(old[1]);
      updateCssVar();
    },
    { immediate: true }
  );
  watch(
    [variable, elRef],
    ([val, el]) => {
      const raw_prop = toValue$1(prop);
      if ((el == null ? void 0 : el.style) && raw_prop) {
        if (val == null)
          el.style.removeProperty(raw_prop);
        else
          el.style.setProperty(raw_prop, val);
      }
    },
    { immediate: true }
  );
  return variable;
}
function useCurrentElement(rootComponent) {
  const vm = getCurrentInstance();
  const currentElement = computedWithControl(
    () => null,
    () => rootComponent ? unrefElement(rootComponent) : vm.proxy.$el
  );
  onUpdated(currentElement.trigger);
  onMounted(currentElement.trigger);
  return currentElement;
}
function useCycleList(list, options) {
  const state = shallowRef(getInitialValue());
  const listRef = toRef(list);
  const index = computed({
    get() {
      var _a;
      const targetList = listRef.value;
      let index2 = (options == null ? void 0 : options.getIndexOf) ? options.getIndexOf(state.value, targetList) : targetList.indexOf(state.value);
      if (index2 < 0)
        index2 = (_a = options == null ? void 0 : options.fallbackIndex) != null ? _a : 0;
      return index2;
    },
    set(v) {
      set(v);
    }
  });
  function set(i) {
    const targetList = listRef.value;
    const length = targetList.length;
    const index2 = (i % length + length) % length;
    const value = targetList[index2];
    state.value = value;
    return value;
  }
  function shift(delta = 1) {
    return set(index.value + delta);
  }
  function next(n = 1) {
    return shift(n);
  }
  function prev(n = 1) {
    return shift(-n);
  }
  function getInitialValue() {
    var _a, _b;
    return (_b = toValue$1((_a = options == null ? void 0 : options.initialValue) != null ? _a : toValue$1(list)[0])) != null ? _b : void 0;
  }
  watch(listRef, () => set(index.value));
  return {
    state,
    index,
    next,
    prev,
    go: set
  };
}
function useDark(options = {}) {
  const {
    valueDark = "dark",
    valueLight = ""
  } = options;
  const mode = useColorMode({
    ...options,
    onChanged: (mode2, defaultHandler) => {
      var _a;
      if (options.onChanged)
        (_a = options.onChanged) == null ? void 0 : _a.call(options, mode2 === "dark", defaultHandler, mode2);
      else
        defaultHandler(mode2);
    },
    modes: {
      dark: valueDark,
      light: valueLight
    }
  });
  const system = computed(() => mode.system.value);
  const isDark = computed({
    get() {
      return mode.value === "dark";
    },
    set(v) {
      const modeVal = v ? "dark" : "light";
      if (system.value === modeVal)
        mode.value = "auto";
      else
        mode.value = modeVal;
    }
  });
  return isDark;
}
function fnBypass(v) {
  return v;
}
function fnSetSource(source, value) {
  return source.value = value;
}
function defaultDump(clone) {
  return clone ? typeof clone === "function" ? clone : cloneFnJSON : fnBypass;
}
function defaultParse(clone) {
  return clone ? typeof clone === "function" ? clone : cloneFnJSON : fnBypass;
}
function useManualRefHistory(source, options = {}) {
  const {
    clone = false,
    dump = defaultDump(clone),
    parse = defaultParse(clone),
    setSource = fnSetSource
  } = options;
  function _createHistoryRecord() {
    return markRaw({
      snapshot: dump(source.value),
      timestamp: timestamp()
    });
  }
  const last = ref(_createHistoryRecord());
  const undoStack = ref([]);
  const redoStack = ref([]);
  const _setSource = (record) => {
    setSource(source, parse(record.snapshot));
    last.value = record;
  };
  const commit = () => {
    undoStack.value.unshift(last.value);
    last.value = _createHistoryRecord();
    if (options.capacity && undoStack.value.length > options.capacity)
      undoStack.value.splice(options.capacity, Number.POSITIVE_INFINITY);
    if (redoStack.value.length)
      redoStack.value.splice(0, redoStack.value.length);
  };
  const clear = () => {
    undoStack.value.splice(0, undoStack.value.length);
    redoStack.value.splice(0, redoStack.value.length);
  };
  const undo = () => {
    const state = undoStack.value.shift();
    if (state) {
      redoStack.value.unshift(last.value);
      _setSource(state);
    }
  };
  const redo = () => {
    const state = redoStack.value.shift();
    if (state) {
      undoStack.value.unshift(last.value);
      _setSource(state);
    }
  };
  const reset = () => {
    _setSource(last.value);
  };
  const history = computed(() => [last.value, ...undoStack.value]);
  const canUndo = computed(() => undoStack.value.length > 0);
  const canRedo = computed(() => redoStack.value.length > 0);
  return {
    source,
    undoStack,
    redoStack,
    last,
    history,
    canUndo,
    canRedo,
    clear,
    commit,
    reset,
    undo,
    redo
  };
}
function useRefHistory(source, options = {}) {
  const {
    deep = false,
    flush = "pre",
    eventFilter
  } = options;
  const {
    eventFilter: composedFilter,
    pause,
    resume: resumeTracking,
    isActive: isTracking
  } = pausableFilter(eventFilter);
  const {
    ignoreUpdates,
    ignorePrevAsyncUpdates,
    stop
  } = watchIgnorable(
    source,
    commit,
    { deep, flush, eventFilter: composedFilter }
  );
  function setSource(source2, value) {
    ignorePrevAsyncUpdates();
    ignoreUpdates(() => {
      source2.value = value;
    });
  }
  const manualHistory = useManualRefHistory(source, { ...options, clone: options.clone || deep, setSource });
  const { clear, commit: manualCommit } = manualHistory;
  function commit() {
    ignorePrevAsyncUpdates();
    manualCommit();
  }
  function resume(commitNow) {
    resumeTracking();
    if (commitNow)
      commit();
  }
  function batch(fn) {
    let canceled = false;
    const cancel = () => canceled = true;
    ignoreUpdates(() => {
      fn(cancel);
    });
    if (!canceled)
      commit();
  }
  function dispose() {
    stop();
    clear();
  }
  return {
    ...manualHistory,
    isTracking,
    pause,
    resume,
    commit,
    batch,
    dispose
  };
}
function useDebouncedRefHistory(source, options = {}) {
  const filter = options.debounce ? debounceFilter(options.debounce) : void 0;
  const history = useRefHistory(source, { ...options, eventFilter: filter });
  return {
    ...history
  };
}
function useDeviceMotion(options = {}) {
  const {
    window: window2 = defaultWindow,
    requestPermissions = false,
    eventFilter = bypassFilter
  } = options;
  const isSupported = useSupported(() => typeof DeviceMotionEvent !== "undefined");
  const requirePermissions = useSupported(() => isSupported.value && "requestPermission" in DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === "function");
  const permissionGranted = shallowRef(false);
  const acceleration = ref({ x: null, y: null, z: null });
  const rotationRate = ref({ alpha: null, beta: null, gamma: null });
  const interval = shallowRef(0);
  const accelerationIncludingGravity = ref({
    x: null,
    y: null,
    z: null
  });
  function init() {
    if (window2) {
      const onDeviceMotion = createFilterWrapper(
        eventFilter,
        (event) => {
          var _a, _b, _c, _d, _e, _f, _g, _h, _i;
          acceleration.value = {
            x: ((_a = event.acceleration) == null ? void 0 : _a.x) || null,
            y: ((_b = event.acceleration) == null ? void 0 : _b.y) || null,
            z: ((_c = event.acceleration) == null ? void 0 : _c.z) || null
          };
          accelerationIncludingGravity.value = {
            x: ((_d = event.accelerationIncludingGravity) == null ? void 0 : _d.x) || null,
            y: ((_e = event.accelerationIncludingGravity) == null ? void 0 : _e.y) || null,
            z: ((_f = event.accelerationIncludingGravity) == null ? void 0 : _f.z) || null
          };
          rotationRate.value = {
            alpha: ((_g = event.rotationRate) == null ? void 0 : _g.alpha) || null,
            beta: ((_h = event.rotationRate) == null ? void 0 : _h.beta) || null,
            gamma: ((_i = event.rotationRate) == null ? void 0 : _i.gamma) || null
          };
          interval.value = event.interval;
        }
      );
      useEventListener(window2, "devicemotion", onDeviceMotion, { passive: true });
    }
  }
  const ensurePermissions = async () => {
    if (!requirePermissions.value)
      permissionGranted.value = true;
    if (permissionGranted.value)
      return;
    if (requirePermissions.value) {
      const requestPermission = DeviceMotionEvent.requestPermission;
      try {
        const response = await requestPermission();
        if (response === "granted") {
          permissionGranted.value = true;
          init();
        }
      } catch (error) {
        console.error(error);
      }
    }
  };
  if (isSupported.value) {
    if (requestPermissions && requirePermissions.value) {
      ensurePermissions().then(() => init());
    } else {
      init();
    }
  }
  return {
    acceleration,
    accelerationIncludingGravity,
    rotationRate,
    interval,
    isSupported,
    requirePermissions,
    ensurePermissions,
    permissionGranted
  };
}
function useDeviceOrientation(options = {}) {
  const { window: window2 = defaultWindow } = options;
  const isSupported = useSupported(() => window2 && "DeviceOrientationEvent" in window2);
  const isAbsolute = shallowRef(false);
  const alpha = shallowRef(null);
  const beta = shallowRef(null);
  const gamma = shallowRef(null);
  if (window2 && isSupported.value) {
    useEventListener(window2, "deviceorientation", (event) => {
      isAbsolute.value = event.absolute;
      alpha.value = event.alpha;
      beta.value = event.beta;
      gamma.value = event.gamma;
    }, { passive: true });
  }
  return {
    isSupported,
    isAbsolute,
    alpha,
    beta,
    gamma
  };
}
function useDevicePixelRatio(options = {}) {
  const {
    window: window2 = defaultWindow
  } = options;
  const pixelRatio = shallowRef(1);
  const query = useMediaQuery(() => `(resolution: ${pixelRatio.value}dppx)`, options);
  let stop = noop$3;
  if (window2) {
    stop = watchImmediate(query, () => pixelRatio.value = window2.devicePixelRatio);
  }
  return {
    pixelRatio: readonly(pixelRatio),
    stop
  };
}
function useDevicesList(options = {}) {
  const {
    navigator: navigator2 = defaultNavigator,
    requestPermissions = false,
    constraints = { audio: true, video: true },
    onUpdated: onUpdated2
  } = options;
  const devices = ref([]);
  const videoInputs = computed(() => devices.value.filter((i) => i.kind === "videoinput"));
  const audioInputs = computed(() => devices.value.filter((i) => i.kind === "audioinput"));
  const audioOutputs = computed(() => devices.value.filter((i) => i.kind === "audiooutput"));
  const isSupported = useSupported(() => navigator2 && navigator2.mediaDevices && navigator2.mediaDevices.enumerateDevices);
  const permissionGranted = shallowRef(false);
  let stream;
  async function update() {
    if (!isSupported.value)
      return;
    devices.value = await navigator2.mediaDevices.enumerateDevices();
    onUpdated2 == null ? void 0 : onUpdated2(devices.value);
    if (stream) {
      stream.getTracks().forEach((t) => t.stop());
      stream = null;
    }
  }
  async function ensurePermissions() {
    const deviceName = constraints.video ? "camera" : "microphone";
    if (!isSupported.value)
      return false;
    if (permissionGranted.value)
      return true;
    const { state, query } = usePermission(deviceName, { controls: true });
    await query();
    if (state.value !== "granted") {
      let granted = true;
      try {
        stream = await navigator2.mediaDevices.getUserMedia(constraints);
      } catch (e) {
        stream = null;
        granted = false;
      }
      update();
      permissionGranted.value = granted;
    } else {
      permissionGranted.value = true;
    }
    return permissionGranted.value;
  }
  if (isSupported.value) {
    if (requestPermissions)
      ensurePermissions();
    useEventListener(navigator2.mediaDevices, "devicechange", update, { passive: true });
    update();
  }
  return {
    devices,
    ensurePermissions,
    permissionGranted,
    videoInputs,
    audioInputs,
    audioOutputs,
    isSupported
  };
}
function useDisplayMedia(options = {}) {
  var _a;
  const enabled = shallowRef((_a = options.enabled) != null ? _a : false);
  const video = options.video;
  const audio = options.audio;
  const { navigator: navigator2 = defaultNavigator } = options;
  const isSupported = useSupported(() => {
    var _a2;
    return (_a2 = navigator2 == null ? void 0 : navigator2.mediaDevices) == null ? void 0 : _a2.getDisplayMedia;
  });
  const constraint = { audio, video };
  const stream = shallowRef();
  async function _start() {
    var _a2;
    if (!isSupported.value || stream.value)
      return;
    stream.value = await navigator2.mediaDevices.getDisplayMedia(constraint);
    (_a2 = stream.value) == null ? void 0 : _a2.getTracks().forEach((t) => useEventListener(t, "ended", stop, { passive: true }));
    return stream.value;
  }
  async function _stop() {
    var _a2;
    (_a2 = stream.value) == null ? void 0 : _a2.getTracks().forEach((t) => t.stop());
    stream.value = void 0;
  }
  function stop() {
    _stop();
    enabled.value = false;
  }
  async function start() {
    await _start();
    if (stream.value)
      enabled.value = true;
    return stream.value;
  }
  watch(
    enabled,
    (v) => {
      if (v)
        _start();
      else
        _stop();
    },
    { immediate: true }
  );
  return {
    isSupported,
    stream,
    start,
    stop,
    enabled
  };
}
function useDocumentVisibility(options = {}) {
  const { document: document2 = defaultDocument } = options;
  if (!document2)
    return shallowRef("visible");
  const visibility = shallowRef(document2.visibilityState);
  useEventListener(document2, "visibilitychange", () => {
    visibility.value = document2.visibilityState;
  }, { passive: true });
  return visibility;
}
function useDraggable(target, options = {}) {
  var _a;
  const {
    pointerTypes,
    preventDefault: preventDefault2,
    stopPropagation,
    exact,
    onMove,
    onEnd,
    onStart,
    initialValue,
    axis = "both",
    draggingElement = defaultWindow,
    containerElement,
    handle: draggingHandle = target,
    buttons = [0]
  } = options;
  const position = ref(
    (_a = toValue$1(initialValue)) != null ? _a : { x: 0, y: 0 }
  );
  const pressedDelta = ref();
  const filterEvent = (e) => {
    if (pointerTypes)
      return pointerTypes.includes(e.pointerType);
    return true;
  };
  const handleEvent = (e) => {
    if (toValue$1(preventDefault2))
      e.preventDefault();
    if (toValue$1(stopPropagation))
      e.stopPropagation();
  };
  const start = (e) => {
    var _a2;
    if (!toValue$1(buttons).includes(e.button))
      return;
    if (toValue$1(options.disabled) || !filterEvent(e))
      return;
    if (toValue$1(exact) && e.target !== toValue$1(target))
      return;
    const container = toValue$1(containerElement);
    const containerRect = (_a2 = container == null ? void 0 : container.getBoundingClientRect) == null ? void 0 : _a2.call(container);
    const targetRect = toValue$1(target).getBoundingClientRect();
    const pos = {
      x: e.clientX - (container ? targetRect.left - containerRect.left + container.scrollLeft : targetRect.left),
      y: e.clientY - (container ? targetRect.top - containerRect.top + container.scrollTop : targetRect.top)
    };
    if ((onStart == null ? void 0 : onStart(pos, e)) === false)
      return;
    pressedDelta.value = pos;
    handleEvent(e);
  };
  const move = (e) => {
    if (toValue$1(options.disabled) || !filterEvent(e))
      return;
    if (!pressedDelta.value)
      return;
    const container = toValue$1(containerElement);
    const targetRect = toValue$1(target).getBoundingClientRect();
    let { x, y } = position.value;
    if (axis === "x" || axis === "both") {
      x = e.clientX - pressedDelta.value.x;
      if (container)
        x = Math.min(Math.max(0, x), container.scrollWidth - targetRect.width);
    }
    if (axis === "y" || axis === "both") {
      y = e.clientY - pressedDelta.value.y;
      if (container)
        y = Math.min(Math.max(0, y), container.scrollHeight - targetRect.height);
    }
    position.value = {
      x,
      y
    };
    onMove == null ? void 0 : onMove(position.value, e);
    handleEvent(e);
  };
  const end = (e) => {
    if (toValue$1(options.disabled) || !filterEvent(e))
      return;
    if (!pressedDelta.value)
      return;
    pressedDelta.value = void 0;
    onEnd == null ? void 0 : onEnd(position.value, e);
    handleEvent(e);
  };
  if (isClient) {
    const config = () => {
      var _a2;
      return {
        capture: (_a2 = options.capture) != null ? _a2 : true,
        passive: !toValue$1(preventDefault2)
      };
    };
    useEventListener(draggingHandle, "pointerdown", start, config);
    useEventListener(draggingElement, "pointermove", move, config);
    useEventListener(draggingElement, "pointerup", end, config);
  }
  return {
    ...toRefs(position),
    position,
    isDragging: computed(() => !!pressedDelta.value),
    style: computed(
      () => `left:${position.value.x}px;top:${position.value.y}px;`
    )
  };
}
function useDropZone(target, options = {}) {
  var _a, _b;
  const isOverDropZone = shallowRef(false);
  const files = shallowRef(null);
  let counter = 0;
  let isValid = true;
  if (isClient) {
    const _options = typeof options === "function" ? { onDrop: options } : options;
    const multiple = (_a = _options.multiple) != null ? _a : true;
    const preventDefaultForUnhandled = (_b = _options.preventDefaultForUnhandled) != null ? _b : false;
    const getFiles = (event) => {
      var _a2, _b2;
      const list = Array.from((_b2 = (_a2 = event.dataTransfer) == null ? void 0 : _a2.files) != null ? _b2 : []);
      return list.length === 0 ? null : multiple ? list : [list[0]];
    };
    const checkDataTypes = (types) => {
      const dataTypes = unref(_options.dataTypes);
      if (typeof dataTypes === "function")
        return dataTypes(types);
      if (!(dataTypes == null ? void 0 : dataTypes.length))
        return true;
      if (types.length === 0)
        return false;
      return types.every(
        (type) => dataTypes.some((allowedType) => type.includes(allowedType))
      );
    };
    const checkValidity = (items) => {
      const types = Array.from(items != null ? items : []).map((item) => item.type);
      const dataTypesValid = checkDataTypes(types);
      const multipleFilesValid = multiple || items.length <= 1;
      return dataTypesValid && multipleFilesValid;
    };
    const isSafari = () => /^(?:(?!chrome|android).)*safari/i.test(navigator.userAgent) && !("chrome" in window);
    const handleDragEvent = (event, eventType) => {
      var _a2, _b2, _c, _d, _e, _f;
      const dataTransferItemList = (_a2 = event.dataTransfer) == null ? void 0 : _a2.items;
      isValid = (_b2 = dataTransferItemList && checkValidity(dataTransferItemList)) != null ? _b2 : false;
      if (preventDefaultForUnhandled) {
        event.preventDefault();
      }
      if (!isSafari() && !isValid) {
        if (event.dataTransfer) {
          event.dataTransfer.dropEffect = "none";
        }
        return;
      }
      event.preventDefault();
      if (event.dataTransfer) {
        event.dataTransfer.dropEffect = "copy";
      }
      const currentFiles = getFiles(event);
      switch (eventType) {
        case "enter":
          counter += 1;
          isOverDropZone.value = true;
          (_c = _options.onEnter) == null ? void 0 : _c.call(_options, null, event);
          break;
        case "over":
          (_d = _options.onOver) == null ? void 0 : _d.call(_options, null, event);
          break;
        case "leave":
          counter -= 1;
          if (counter === 0)
            isOverDropZone.value = false;
          (_e = _options.onLeave) == null ? void 0 : _e.call(_options, null, event);
          break;
        case "drop":
          counter = 0;
          isOverDropZone.value = false;
          if (isValid) {
            files.value = currentFiles;
            (_f = _options.onDrop) == null ? void 0 : _f.call(_options, currentFiles, event);
          }
          break;
      }
    };
    useEventListener(target, "dragenter", (event) => handleDragEvent(event, "enter"));
    useEventListener(target, "dragover", (event) => handleDragEvent(event, "over"));
    useEventListener(target, "dragleave", (event) => handleDragEvent(event, "leave"));
    useEventListener(target, "drop", (event) => handleDragEvent(event, "drop"));
  }
  return {
    files,
    isOverDropZone
  };
}
function useResizeObserver(target, callback, options = {}) {
  const { window: window2 = defaultWindow, ...observerOptions } = options;
  let observer;
  const isSupported = useSupported(() => window2 && "ResizeObserver" in window2);
  const cleanup = () => {
    if (observer) {
      observer.disconnect();
      observer = void 0;
    }
  };
  const targets = computed(() => {
    const _targets = toValue$1(target);
    return Array.isArray(_targets) ? _targets.map((el) => unrefElement(el)) : [unrefElement(_targets)];
  });
  const stopWatch = watch(
    targets,
    (els) => {
      cleanup();
      if (isSupported.value && window2) {
        observer = new ResizeObserver(callback);
        for (const _el of els) {
          if (_el)
            observer.observe(_el, observerOptions);
        }
      }
    },
    { immediate: true, flush: "post" }
  );
  const stop = () => {
    cleanup();
    stopWatch();
  };
  tryOnScopeDispose(stop);
  return {
    isSupported,
    stop
  };
}
function useElementBounding(target, options = {}) {
  const {
    reset = true,
    windowResize = true,
    windowScroll = true,
    immediate = true,
    updateTiming = "sync"
  } = options;
  const height = shallowRef(0);
  const bottom = shallowRef(0);
  const left = shallowRef(0);
  const right = shallowRef(0);
  const top = shallowRef(0);
  const width = shallowRef(0);
  const x = shallowRef(0);
  const y = shallowRef(0);
  function recalculate() {
    const el = unrefElement(target);
    if (!el) {
      if (reset) {
        height.value = 0;
        bottom.value = 0;
        left.value = 0;
        right.value = 0;
        top.value = 0;
        width.value = 0;
        x.value = 0;
        y.value = 0;
      }
      return;
    }
    const rect = el.getBoundingClientRect();
    height.value = rect.height;
    bottom.value = rect.bottom;
    left.value = rect.left;
    right.value = rect.right;
    top.value = rect.top;
    width.value = rect.width;
    x.value = rect.x;
    y.value = rect.y;
  }
  function update() {
    if (updateTiming === "sync")
      recalculate();
    else if (updateTiming === "next-frame")
      requestAnimationFrame(() => recalculate());
  }
  useResizeObserver(target, update);
  watch(() => unrefElement(target), (ele) => !ele && update());
  useMutationObserver(target, update, {
    attributeFilter: ["style", "class"]
  });
  if (windowScroll)
    useEventListener("scroll", update, { capture: true, passive: true });
  if (windowResize)
    useEventListener("resize", update, { passive: true });
  tryOnMounted(() => {
    if (immediate)
      update();
  });
  return {
    height,
    bottom,
    left,
    right,
    top,
    width,
    x,
    y,
    update
  };
}
function useElementByPoint(options) {
  const {
    x,
    y,
    document: document2 = defaultDocument,
    multiple,
    interval = "requestAnimationFrame",
    immediate = true
  } = options;
  const isSupported = useSupported(() => {
    if (toValue$1(multiple))
      return document2 && "elementsFromPoint" in document2;
    return document2 && "elementFromPoint" in document2;
  });
  const element = shallowRef(null);
  const cb = () => {
    var _a, _b;
    element.value = toValue$1(multiple) ? (_a = document2 == null ? void 0 : document2.elementsFromPoint(toValue$1(x), toValue$1(y))) != null ? _a : [] : (_b = document2 == null ? void 0 : document2.elementFromPoint(toValue$1(x), toValue$1(y))) != null ? _b : null;
  };
  const controls = interval === "requestAnimationFrame" ? useRafFn(cb, { immediate }) : useIntervalFn(cb, interval, { immediate });
  return {
    isSupported,
    element,
    ...controls
  };
}
function useElementHover(el, options = {}) {
  const {
    delayEnter = 0,
    delayLeave = 0,
    triggerOnRemoval = false,
    window: window2 = defaultWindow
  } = options;
  const isHovered = shallowRef(false);
  let timer;
  const toggle = (entering) => {
    const delay = entering ? delayEnter : delayLeave;
    if (timer) {
      clearTimeout(timer);
      timer = void 0;
    }
    if (delay)
      timer = setTimeout(() => isHovered.value = entering, delay);
    else
      isHovered.value = entering;
  };
  if (!window2)
    return isHovered;
  useEventListener(el, "mouseenter", () => toggle(true), { passive: true });
  useEventListener(el, "mouseleave", () => toggle(false), { passive: true });
  if (triggerOnRemoval) {
    onElementRemoval(
      computed(() => unrefElement(el)),
      () => toggle(false)
    );
  }
  return isHovered;
}
function useElementSize(target, initialSize = { width: 0, height: 0 }, options = {}) {
  const { window: window2 = defaultWindow, box = "content-box" } = options;
  const isSVG = computed(() => {
    var _a, _b;
    return (_b = (_a = unrefElement(target)) == null ? void 0 : _a.namespaceURI) == null ? void 0 : _b.includes("svg");
  });
  const width = shallowRef(initialSize.width);
  const height = shallowRef(initialSize.height);
  const { stop: stop1 } = useResizeObserver(
    target,
    ([entry]) => {
      const boxSize = box === "border-box" ? entry.borderBoxSize : box === "content-box" ? entry.contentBoxSize : entry.devicePixelContentBoxSize;
      if (window2 && isSVG.value) {
        const $elem = unrefElement(target);
        if ($elem) {
          const rect = $elem.getBoundingClientRect();
          width.value = rect.width;
          height.value = rect.height;
        }
      } else {
        if (boxSize) {
          const formatBoxSize = toArray$1(boxSize);
          width.value = formatBoxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0);
          height.value = formatBoxSize.reduce((acc, { blockSize }) => acc + blockSize, 0);
        } else {
          width.value = entry.contentRect.width;
          height.value = entry.contentRect.height;
        }
      }
    },
    options
  );
  tryOnMounted(() => {
    const ele = unrefElement(target);
    if (ele) {
      width.value = "offsetWidth" in ele ? ele.offsetWidth : initialSize.width;
      height.value = "offsetHeight" in ele ? ele.offsetHeight : initialSize.height;
    }
  });
  const stop2 = watch(
    () => unrefElement(target),
    (ele) => {
      width.value = ele ? initialSize.width : 0;
      height.value = ele ? initialSize.height : 0;
    }
  );
  function stop() {
    stop1();
    stop2();
  }
  return {
    width,
    height,
    stop
  };
}
function useIntersectionObserver(target, callback, options = {}) {
  const {
    root,
    rootMargin = "0px",
    threshold = 0,
    window: window2 = defaultWindow,
    immediate = true
  } = options;
  const isSupported = useSupported(() => window2 && "IntersectionObserver" in window2);
  const targets = computed(() => {
    const _target = toValue$1(target);
    return toArray$1(_target).map(unrefElement).filter(notNullish);
  });
  let cleanup = noop$3;
  const isActive = shallowRef(immediate);
  const stopWatch = isSupported.value ? watch(
    () => [targets.value, unrefElement(root), isActive.value],
    ([targets2, root2]) => {
      cleanup();
      if (!isActive.value)
        return;
      if (!targets2.length)
        return;
      const observer = new IntersectionObserver(
        callback,
        {
          root: unrefElement(root2),
          rootMargin,
          threshold
        }
      );
      targets2.forEach((el) => el && observer.observe(el));
      cleanup = () => {
        observer.disconnect();
        cleanup = noop$3;
      };
    },
    { immediate, flush: "post" }
  ) : noop$3;
  const stop = () => {
    cleanup();
    stopWatch();
    isActive.value = false;
  };
  tryOnScopeDispose(stop);
  return {
    isSupported,
    isActive,
    pause() {
      cleanup();
      isActive.value = false;
    },
    resume() {
      isActive.value = true;
    },
    stop
  };
}
function useElementVisibility(element, options = {}) {
  const {
    window: window2 = defaultWindow,
    scrollTarget,
    threshold = 0,
    rootMargin,
    once = false
  } = options;
  const elementIsVisible = shallowRef(false);
  const { stop } = useIntersectionObserver(
    element,
    (intersectionObserverEntries) => {
      let isIntersecting = elementIsVisible.value;
      let latestTime = 0;
      for (const entry of intersectionObserverEntries) {
        if (entry.time >= latestTime) {
          latestTime = entry.time;
          isIntersecting = entry.isIntersecting;
        }
      }
      elementIsVisible.value = isIntersecting;
      if (once) {
        watchOnce(elementIsVisible, () => {
          stop();
        });
      }
    },
    {
      root: scrollTarget,
      window: window2,
      threshold,
      rootMargin: toValue$1(rootMargin)
    }
  );
  return elementIsVisible;
}
const events = /* @__PURE__ */ new Map();
function useEventBus(key) {
  const scope = getCurrentScope();
  function on(listener) {
    var _a;
    const listeners = events.get(key) || /* @__PURE__ */ new Set();
    listeners.add(listener);
    events.set(key, listeners);
    const _off = () => off(listener);
    (_a = scope == null ? void 0 : scope.cleanups) == null ? void 0 : _a.push(_off);
    return _off;
  }
  function once(listener) {
    function _listener(...args) {
      off(_listener);
      listener(...args);
    }
    return on(_listener);
  }
  function off(listener) {
    const listeners = events.get(key);
    if (!listeners)
      return;
    listeners.delete(listener);
    if (!listeners.size)
      reset();
  }
  function reset() {
    events.delete(key);
  }
  function emit(event, payload) {
    var _a;
    (_a = events.get(key)) == null ? void 0 : _a.forEach((v) => v(event, payload));
  }
  return { on, once, off, emit, reset };
}
function resolveNestedOptions$1(options) {
  if (options === true)
    return {};
  return options;
}
function useEventSource(url, events2 = [], options = {}) {
  const event = shallowRef(null);
  const data = shallowRef(null);
  const status = shallowRef("CONNECTING");
  const eventSource = ref(null);
  const error = shallowRef(null);
  const urlRef = toRef(url);
  const lastEventId = shallowRef(null);
  let explicitlyClosed = false;
  let retried = 0;
  const {
    withCredentials = false,
    immediate = true,
    autoConnect = true,
    autoReconnect
  } = options;
  const close = () => {
    if (isClient && eventSource.value) {
      eventSource.value.close();
      eventSource.value = null;
      status.value = "CLOSED";
      explicitlyClosed = true;
    }
  };
  const _init = () => {
    if (explicitlyClosed || typeof urlRef.value === "undefined")
      return;
    const es = new EventSource(urlRef.value, { withCredentials });
    status.value = "CONNECTING";
    eventSource.value = es;
    es.onopen = () => {
      status.value = "OPEN";
      error.value = null;
    };
    es.onerror = (e) => {
      status.value = "CLOSED";
      error.value = e;
      if (es.readyState === 2 && !explicitlyClosed && autoReconnect) {
        es.close();
        const {
          retries = -1,
          delay = 1e3,
          onFailed
        } = resolveNestedOptions$1(autoReconnect);
        retried += 1;
        if (typeof retries === "number" && (retries < 0 || retried < retries))
          setTimeout(_init, delay);
        else if (typeof retries === "function" && retries())
          setTimeout(_init, delay);
        else
          onFailed == null ? void 0 : onFailed();
      }
    };
    es.onmessage = (e) => {
      event.value = null;
      data.value = e.data;
      lastEventId.value = e.lastEventId;
    };
    for (const event_name of events2) {
      useEventListener(es, event_name, (e) => {
        event.value = event_name;
        data.value = e.data || null;
      }, { passive: true });
    }
  };
  const open = () => {
    if (!isClient)
      return;
    close();
    explicitlyClosed = false;
    retried = 0;
    _init();
  };
  if (immediate)
    open();
  if (autoConnect)
    watch(urlRef, open);
  tryOnScopeDispose(close);
  return {
    eventSource,
    event,
    data,
    status,
    error,
    open,
    close,
    lastEventId
  };
}
function useEyeDropper(options = {}) {
  const { initialValue = "" } = options;
  const isSupported = useSupported(() => typeof window !== "undefined" && "EyeDropper" in window);
  const sRGBHex = shallowRef(initialValue);
  async function open(openOptions) {
    if (!isSupported.value)
      return;
    const eyeDropper = new window.EyeDropper();
    const result = await eyeDropper.open(openOptions);
    sRGBHex.value = result.sRGBHex;
    return result;
  }
  return { isSupported, sRGBHex, open };
}
function useFavicon(newIcon = null, options = {}) {
  const {
    baseUrl = "",
    rel = "icon",
    document: document2 = defaultDocument
  } = options;
  const favicon = toRef(newIcon);
  const applyIcon = (icon) => {
    const elements = document2 == null ? void 0 : document2.head.querySelectorAll(`link[rel*="${rel}"]`);
    if (!elements || elements.length === 0) {
      const link = document2 == null ? void 0 : document2.createElement("link");
      if (link) {
        link.rel = rel;
        link.href = `${baseUrl}${icon}`;
        link.type = `image/${icon.split(".").pop()}`;
        document2 == null ? void 0 : document2.head.append(link);
      }
      return;
    }
    elements == null ? void 0 : elements.forEach((el) => el.href = `${baseUrl}${icon}`);
  };
  watch(
    favicon,
    (i, o) => {
      if (typeof i === "string" && i !== o)
        applyIcon(i);
    },
    { immediate: true }
  );
  return favicon;
}
const payloadMapping = {
  json: "application/json",
  text: "text/plain"
};
function isFetchOptions(obj) {
  return obj && containsProp(obj, "immediate", "refetch", "initialData", "timeout", "beforeFetch", "afterFetch", "onFetchError", "fetch", "updateDataOnError");
}
const reAbsolute = /^(?:[a-z][a-z\d+\-.]*:)?\/\//i;
function isAbsoluteURL$1(url) {
  return reAbsolute.test(url);
}
function headersToObject$1(headers) {
  if (typeof Headers !== "undefined" && headers instanceof Headers)
    return Object.fromEntries(headers.entries());
  return headers;
}
function combineCallbacks(combination, ...callbacks) {
  if (combination === "overwrite") {
    return async (ctx) => {
      let callback;
      for (let i = callbacks.length - 1; i >= 0; i--) {
        if (callbacks[i] != null) {
          callback = callbacks[i];
          break;
        }
      }
      if (callback)
        return { ...ctx, ...await callback(ctx) };
      return ctx;
    };
  } else {
    return async (ctx) => {
      for (const callback of callbacks) {
        if (callback)
          ctx = { ...ctx, ...await callback(ctx) };
      }
      return ctx;
    };
  }
}
function createFetch(config = {}) {
  const _combination = config.combination || "chain";
  const _options = config.options || {};
  const _fetchOptions = config.fetchOptions || {};
  function useFactoryFetch(url, ...args) {
    const computedUrl = computed(() => {
      const baseUrl = toValue$1(config.baseUrl);
      const targetUrl = toValue$1(url);
      return baseUrl && !isAbsoluteURL$1(targetUrl) ? joinPaths(baseUrl, targetUrl) : targetUrl;
    });
    let options = _options;
    let fetchOptions = _fetchOptions;
    if (args.length > 0) {
      if (isFetchOptions(args[0])) {
        options = {
          ...options,
          ...args[0],
          beforeFetch: combineCallbacks(_combination, _options.beforeFetch, args[0].beforeFetch),
          afterFetch: combineCallbacks(_combination, _options.afterFetch, args[0].afterFetch),
          onFetchError: combineCallbacks(_combination, _options.onFetchError, args[0].onFetchError)
        };
      } else {
        fetchOptions = {
          ...fetchOptions,
          ...args[0],
          headers: {
            ...headersToObject$1(fetchOptions.headers) || {},
            ...headersToObject$1(args[0].headers) || {}
          }
        };
      }
    }
    if (args.length > 1 && isFetchOptions(args[1])) {
      options = {
        ...options,
        ...args[1],
        beforeFetch: combineCallbacks(_combination, _options.beforeFetch, args[1].beforeFetch),
        afterFetch: combineCallbacks(_combination, _options.afterFetch, args[1].afterFetch),
        onFetchError: combineCallbacks(_combination, _options.onFetchError, args[1].onFetchError)
      };
    }
    return useFetch(computedUrl, fetchOptions, options);
  }
  return useFactoryFetch;
}
function useFetch(url, ...args) {
  var _a;
  const supportsAbort = typeof AbortController === "function";
  let fetchOptions = {};
  let options = {
    immediate: true,
    refetch: false,
    timeout: 0,
    updateDataOnError: false
  };
  const config = {
    method: "GET",
    type: "text",
    payload: void 0
  };
  if (args.length > 0) {
    if (isFetchOptions(args[0]))
      options = { ...options, ...args[0] };
    else
      fetchOptions = args[0];
  }
  if (args.length > 1) {
    if (isFetchOptions(args[1]))
      options = { ...options, ...args[1] };
  }
  const {
    fetch = (_a = defaultWindow) == null ? void 0 : _a.fetch,
    initialData,
    timeout
  } = options;
  const responseEvent = createEventHook();
  const errorEvent = createEventHook();
  const finallyEvent = createEventHook();
  const isFinished = shallowRef(false);
  const isFetching = shallowRef(false);
  const aborted = shallowRef(false);
  const statusCode = shallowRef(null);
  const response = shallowRef(null);
  const error = shallowRef(null);
  const data = shallowRef(initialData || null);
  const canAbort = computed(() => supportsAbort && isFetching.value);
  let controller;
  let timer;
  const abort = () => {
    if (supportsAbort) {
      controller == null ? void 0 : controller.abort();
      controller = new AbortController();
      controller.signal.onabort = () => aborted.value = true;
      fetchOptions = {
        ...fetchOptions,
        signal: controller.signal
      };
    }
  };
  const loading = (isLoading) => {
    isFetching.value = isLoading;
    isFinished.value = !isLoading;
  };
  if (timeout)
    timer = useTimeoutFn(abort, timeout, { immediate: false });
  let executeCounter = 0;
  const execute = async (throwOnFailed = false) => {
    var _a2, _b;
    abort();
    loading(true);
    error.value = null;
    statusCode.value = null;
    aborted.value = false;
    executeCounter += 1;
    const currentExecuteCounter = executeCounter;
    const defaultFetchOptions = {
      method: config.method,
      headers: {}
    };
    const payload = toValue$1(config.payload);
    if (payload) {
      const headers = headersToObject$1(defaultFetchOptions.headers);
      const proto = Object.getPrototypeOf(payload);
      if (!config.payloadType && payload && (proto === Object.prototype || Array.isArray(proto)) && !(payload instanceof FormData))
        config.payloadType = "json";
      if (config.payloadType)
        headers["Content-Type"] = (_a2 = payloadMapping[config.payloadType]) != null ? _a2 : config.payloadType;
      defaultFetchOptions.body = config.payloadType === "json" ? JSON.stringify(payload) : payload;
    }
    let isCanceled = false;
    const context = {
      url: toValue$1(url),
      options: {
        ...defaultFetchOptions,
        ...fetchOptions
      },
      cancel: () => {
        isCanceled = true;
      }
    };
    if (options.beforeFetch)
      Object.assign(context, await options.beforeFetch(context));
    if (isCanceled || !fetch) {
      loading(false);
      return Promise.resolve(null);
    }
    let responseData = null;
    if (timer)
      timer.start();
    return fetch(
      context.url,
      {
        ...defaultFetchOptions,
        ...context.options,
        headers: {
          ...headersToObject$1(defaultFetchOptions.headers),
          ...headersToObject$1((_b = context.options) == null ? void 0 : _b.headers)
        }
      }
    ).then(async (fetchResponse) => {
      response.value = fetchResponse;
      statusCode.value = fetchResponse.status;
      responseData = await fetchResponse.clone()[config.type]();
      if (!fetchResponse.ok) {
        data.value = initialData || null;
        throw new Error(fetchResponse.statusText);
      }
      if (options.afterFetch) {
        ({ data: responseData } = await options.afterFetch({
          data: responseData,
          response: fetchResponse,
          context,
          execute
        }));
      }
      data.value = responseData;
      responseEvent.trigger(fetchResponse);
      return fetchResponse;
    }).catch(async (fetchError) => {
      let errorData = fetchError.message || fetchError.name;
      if (options.onFetchError) {
        ({ error: errorData, data: responseData } = await options.onFetchError({
          data: responseData,
          error: fetchError,
          response: response.value,
          context,
          execute
        }));
      }
      error.value = errorData;
      if (options.updateDataOnError)
        data.value = responseData;
      errorEvent.trigger(fetchError);
      if (throwOnFailed)
        throw fetchError;
      return null;
    }).finally(() => {
      if (currentExecuteCounter === executeCounter)
        loading(false);
      if (timer)
        timer.stop();
      finallyEvent.trigger(null);
    });
  };
  const refetch = toRef(options.refetch);
  watch(
    [
      refetch,
      toRef(url)
    ],
    ([refetch2]) => refetch2 && execute(),
    { deep: true }
  );
  const shell = {
    isFinished: readonly(isFinished),
    isFetching: readonly(isFetching),
    statusCode,
    response,
    error,
    data,
    canAbort,
    aborted,
    abort,
    execute,
    onFetchResponse: responseEvent.on,
    onFetchError: errorEvent.on,
    onFetchFinally: finallyEvent.on,
    // method
    get: setMethod("GET"),
    put: setMethod("PUT"),
    post: setMethod("POST"),
    delete: setMethod("DELETE"),
    patch: setMethod("PATCH"),
    head: setMethod("HEAD"),
    options: setMethod("OPTIONS"),
    // type
    json: setType("json"),
    text: setType("text"),
    blob: setType("blob"),
    arrayBuffer: setType("arrayBuffer"),
    formData: setType("formData")
  };
  function setMethod(method) {
    return (payload, payloadType) => {
      if (!isFetching.value) {
        config.method = method;
        config.payload = payload;
        config.payloadType = payloadType;
        if (isRef(config.payload)) {
          watch(
            [
              refetch,
              toRef(config.payload)
            ],
            ([refetch2]) => refetch2 && execute(),
            { deep: true }
          );
        }
        return {
          ...shell,
          then(onFulfilled, onRejected) {
            return waitUntilFinished().then(onFulfilled, onRejected);
          }
        };
      }
      return void 0;
    };
  }
  function waitUntilFinished() {
    return new Promise((resolve, reject) => {
      until(isFinished).toBe(true).then(() => resolve(shell)).catch(reject);
    });
  }
  function setType(type) {
    return () => {
      if (!isFetching.value) {
        config.type = type;
        return {
          ...shell,
          then(onFulfilled, onRejected) {
            return waitUntilFinished().then(onFulfilled, onRejected);
          }
        };
      }
      return void 0;
    };
  }
  if (options.immediate)
    Promise.resolve().then(() => execute());
  return {
    ...shell,
    then(onFulfilled, onRejected) {
      return waitUntilFinished().then(onFulfilled, onRejected);
    }
  };
}
function joinPaths(start, end) {
  if (!start.endsWith("/") && !end.startsWith("/")) {
    return `${start}/${end}`;
  }
  if (start.endsWith("/") && end.startsWith("/")) {
    return `${start.slice(0, -1)}${end}`;
  }
  return `${start}${end}`;
}
const DEFAULT_OPTIONS$1 = {
  multiple: true,
  accept: "*",
  reset: false,
  directory: false
};
function prepareInitialFiles(files) {
  if (!files)
    return null;
  if (files instanceof FileList)
    return files;
  const dt = new DataTransfer();
  for (const file of files) {
    dt.items.add(file);
  }
  return dt.files;
}
function useFileDialog(options = {}) {
  const {
    document: document2 = defaultDocument
  } = options;
  const files = ref(prepareInitialFiles(options.initialFiles));
  const { on: onChange, trigger: changeTrigger } = createEventHook();
  const { on: onCancel, trigger: cancelTrigger } = createEventHook();
  let input;
  if (document2) {
    input = document2.createElement("input");
    input.type = "file";
    input.onchange = (event) => {
      const result = event.target;
      files.value = result.files;
      changeTrigger(files.value);
    };
    input.oncancel = () => {
      cancelTrigger();
    };
  }
  const reset = () => {
    files.value = null;
    if (input && input.value) {
      input.value = "";
      changeTrigger(null);
    }
  };
  const open = (localOptions) => {
    if (!input)
      return;
    const _options = {
      ...DEFAULT_OPTIONS$1,
      ...options,
      ...localOptions
    };
    input.multiple = _options.multiple;
    input.accept = _options.accept;
    input.webkitdirectory = _options.directory;
    if (hasOwn$2(_options, "capture"))
      input.capture = _options.capture;
    if (_options.reset)
      reset();
    input.click();
  };
  return {
    files: readonly(files),
    open,
    reset,
    onCancel,
    onChange
  };
}
function useFileSystemAccess(options = {}) {
  const {
    window: _window = defaultWindow,
    dataType = "Text"
  } = options;
  const window2 = _window;
  const isSupported = useSupported(() => window2 && "showSaveFilePicker" in window2 && "showOpenFilePicker" in window2);
  const fileHandle = shallowRef();
  const data = shallowRef();
  const file = shallowRef();
  const fileName = computed(() => {
    var _a, _b;
    return (_b = (_a = file.value) == null ? void 0 : _a.name) != null ? _b : "";
  });
  const fileMIME = computed(() => {
    var _a, _b;
    return (_b = (_a = file.value) == null ? void 0 : _a.type) != null ? _b : "";
  });
  const fileSize = computed(() => {
    var _a, _b;
    return (_b = (_a = file.value) == null ? void 0 : _a.size) != null ? _b : 0;
  });
  const fileLastModified = computed(() => {
    var _a, _b;
    return (_b = (_a = file.value) == null ? void 0 : _a.lastModified) != null ? _b : 0;
  });
  async function open(_options = {}) {
    if (!isSupported.value)
      return;
    const [handle] = await window2.showOpenFilePicker({ ...toValue$1(options), ..._options });
    fileHandle.value = handle;
    await updateData();
  }
  async function create(_options = {}) {
    if (!isSupported.value)
      return;
    fileHandle.value = await window2.showSaveFilePicker({ ...options, ..._options });
    data.value = void 0;
    await updateData();
  }
  async function save(_options = {}) {
    if (!isSupported.value)
      return;
    if (!fileHandle.value)
      return saveAs(_options);
    if (data.value) {
      const writableStream = await fileHandle.value.createWritable();
      await writableStream.write(data.value);
      await writableStream.close();
    }
    await updateFile();
  }
  async function saveAs(_options = {}) {
    if (!isSupported.value)
      return;
    fileHandle.value = await window2.showSaveFilePicker({ ...options, ..._options });
    if (data.value) {
      const writableStream = await fileHandle.value.createWritable();
      await writableStream.write(data.value);
      await writableStream.close();
    }
    await updateFile();
  }
  async function updateFile() {
    var _a;
    file.value = await ((_a = fileHandle.value) == null ? void 0 : _a.getFile());
  }
  async function updateData() {
    var _a, _b;
    await updateFile();
    const type = toValue$1(dataType);
    if (type === "Text")
      data.value = await ((_a = file.value) == null ? void 0 : _a.text());
    else if (type === "ArrayBuffer")
      data.value = await ((_b = file.value) == null ? void 0 : _b.arrayBuffer());
    else if (type === "Blob")
      data.value = file.value;
  }
  watch(() => toValue$1(dataType), updateData);
  return {
    isSupported,
    data,
    file,
    fileName,
    fileMIME,
    fileSize,
    fileLastModified,
    open,
    create,
    save,
    saveAs,
    updateData
  };
}
function useFocus(target, options = {}) {
  const { initialValue = false, focusVisible = false, preventScroll = false } = options;
  const innerFocused = shallowRef(false);
  const targetElement = computed(() => unrefElement(target));
  const listenerOptions = { passive: true };
  useEventListener(targetElement, "focus", (event) => {
    var _a, _b;
    if (!focusVisible || ((_b = (_a = event.target).matches) == null ? void 0 : _b.call(_a, ":focus-visible")))
      innerFocused.value = true;
  }, listenerOptions);
  useEventListener(targetElement, "blur", () => innerFocused.value = false, listenerOptions);
  const focused = computed({
    get: () => innerFocused.value,
    set(value) {
      var _a, _b;
      if (!value && innerFocused.value)
        (_a = targetElement.value) == null ? void 0 : _a.blur();
      else if (value && !innerFocused.value)
        (_b = targetElement.value) == null ? void 0 : _b.focus({ preventScroll });
    }
  });
  watch(
    targetElement,
    () => {
      focused.value = initialValue;
    },
    { immediate: true, flush: "post" }
  );
  return { focused };
}
const EVENT_FOCUS_IN = "focusin";
const EVENT_FOCUS_OUT = "focusout";
const PSEUDO_CLASS_FOCUS_WITHIN = ":focus-within";
function useFocusWithin(target, options = {}) {
  const { window: window2 = defaultWindow } = options;
  const targetElement = computed(() => unrefElement(target));
  const _focused = shallowRef(false);
  const focused = computed(() => _focused.value);
  const activeElement = useActiveElement(options);
  if (!window2 || !activeElement.value) {
    return { focused };
  }
  const listenerOptions = { passive: true };
  useEventListener(targetElement, EVENT_FOCUS_IN, () => _focused.value = true, listenerOptions);
  useEventListener(targetElement, EVENT_FOCUS_OUT, () => {
    var _a, _b, _c;
    return _focused.value = (_c = (_b = (_a = targetElement.value) == null ? void 0 : _a.matches) == null ? void 0 : _b.call(_a, PSEUDO_CLASS_FOCUS_WITHIN)) != null ? _c : false;
  }, listenerOptions);
  return { focused };
}
function useFps(options) {
  var _a;
  const fps = shallowRef(0);
  if (typeof performance === "undefined")
    return fps;
  const every = (_a = options == null ? void 0 : options.every) != null ? _a : 10;
  let last = performance.now();
  let ticks = 0;
  useRafFn(() => {
    ticks += 1;
    if (ticks >= every) {
      const now = performance.now();
      const diff = now - last;
      fps.value = Math.round(1e3 / (diff / ticks));
      last = now;
      ticks = 0;
    }
  });
  return fps;
}
const eventHandlers = [
  "fullscreenchange",
  "webkitfullscreenchange",
  "webkitendfullscreen",
  "mozfullscreenchange",
  "MSFullscreenChange"
];
function useFullscreen(target, options = {}) {
  const {
    document: document2 = defaultDocument,
    autoExit = false
  } = options;
  const targetRef = computed(() => {
    var _a;
    return (_a = unrefElement(target)) != null ? _a : document2 == null ? void 0 : document2.documentElement;
  });
  const isFullscreen = shallowRef(false);
  const requestMethod = computed(() => {
    return [
      "requestFullscreen",
      "webkitRequestFullscreen",
      "webkitEnterFullscreen",
      "webkitEnterFullScreen",
      "webkitRequestFullScreen",
      "mozRequestFullScreen",
      "msRequestFullscreen"
    ].find((m) => document2 && m in document2 || targetRef.value && m in targetRef.value);
  });
  const exitMethod = computed(() => {
    return [
      "exitFullscreen",
      "webkitExitFullscreen",
      "webkitExitFullScreen",
      "webkitCancelFullScreen",
      "mozCancelFullScreen",
      "msExitFullscreen"
    ].find((m) => document2 && m in document2 || targetRef.value && m in targetRef.value);
  });
  const fullscreenEnabled = computed(() => {
    return [
      "fullScreen",
      "webkitIsFullScreen",
      "webkitDisplayingFullscreen",
      "mozFullScreen",
      "msFullscreenElement"
    ].find((m) => document2 && m in document2 || targetRef.value && m in targetRef.value);
  });
  const fullscreenElementMethod = [
    "fullscreenElement",
    "webkitFullscreenElement",
    "mozFullScreenElement",
    "msFullscreenElement"
  ].find((m) => document2 && m in document2);
  const isSupported = useSupported(() => targetRef.value && document2 && requestMethod.value !== void 0 && exitMethod.value !== void 0 && fullscreenEnabled.value !== void 0);
  const isCurrentElementFullScreen = () => {
    if (fullscreenElementMethod)
      return (document2 == null ? void 0 : document2[fullscreenElementMethod]) === targetRef.value;
    return false;
  };
  const isElementFullScreen = () => {
    if (fullscreenEnabled.value) {
      if (document2 && document2[fullscreenEnabled.value] != null) {
        return document2[fullscreenEnabled.value];
      } else {
        const target2 = targetRef.value;
        if ((target2 == null ? void 0 : target2[fullscreenEnabled.value]) != null) {
          return Boolean(target2[fullscreenEnabled.value]);
        }
      }
    }
    return false;
  };
  async function exit() {
    if (!isSupported.value || !isFullscreen.value)
      return;
    if (exitMethod.value) {
      if ((document2 == null ? void 0 : document2[exitMethod.value]) != null) {
        await document2[exitMethod.value]();
      } else {
        const target2 = targetRef.value;
        if ((target2 == null ? void 0 : target2[exitMethod.value]) != null)
          await target2[exitMethod.value]();
      }
    }
    isFullscreen.value = false;
  }
  async function enter() {
    if (!isSupported.value || isFullscreen.value)
      return;
    if (isElementFullScreen())
      await exit();
    const target2 = targetRef.value;
    if (requestMethod.value && (target2 == null ? void 0 : target2[requestMethod.value]) != null) {
      await target2[requestMethod.value]();
      isFullscreen.value = true;
    }
  }
  async function toggle() {
    await (isFullscreen.value ? exit() : enter());
  }
  const handlerCallback = () => {
    const isElementFullScreenValue = isElementFullScreen();
    if (!isElementFullScreenValue || isElementFullScreenValue && isCurrentElementFullScreen())
      isFullscreen.value = isElementFullScreenValue;
  };
  const listenerOptions = { capture: false, passive: true };
  useEventListener(document2, eventHandlers, handlerCallback, listenerOptions);
  useEventListener(() => unrefElement(targetRef), eventHandlers, handlerCallback, listenerOptions);
  if (autoExit)
    tryOnScopeDispose(exit);
  return {
    isSupported,
    isFullscreen,
    enter,
    exit,
    toggle
  };
}
function mapGamepadToXbox360Controller(gamepad) {
  return computed(() => {
    if (gamepad.value) {
      return {
        buttons: {
          a: gamepad.value.buttons[0],
          b: gamepad.value.buttons[1],
          x: gamepad.value.buttons[2],
          y: gamepad.value.buttons[3]
        },
        bumper: {
          left: gamepad.value.buttons[4],
          right: gamepad.value.buttons[5]
        },
        triggers: {
          left: gamepad.value.buttons[6],
          right: gamepad.value.buttons[7]
        },
        stick: {
          left: {
            horizontal: gamepad.value.axes[0],
            vertical: gamepad.value.axes[1],
            button: gamepad.value.buttons[10]
          },
          right: {
            horizontal: gamepad.value.axes[2],
            vertical: gamepad.value.axes[3],
            button: gamepad.value.buttons[11]
          }
        },
        dpad: {
          up: gamepad.value.buttons[12],
          down: gamepad.value.buttons[13],
          left: gamepad.value.buttons[14],
          right: gamepad.value.buttons[15]
        },
        back: gamepad.value.buttons[8],
        start: gamepad.value.buttons[9]
      };
    }
    return null;
  });
}
function useGamepad(options = {}) {
  const {
    navigator: navigator2 = defaultNavigator
  } = options;
  const isSupported = useSupported(() => navigator2 && "getGamepads" in navigator2);
  const gamepads = ref([]);
  const onConnectedHook = createEventHook();
  const onDisconnectedHook = createEventHook();
  const stateFromGamepad = (gamepad) => {
    const hapticActuators = [];
    const vibrationActuator = "vibrationActuator" in gamepad ? gamepad.vibrationActuator : null;
    if (vibrationActuator)
      hapticActuators.push(vibrationActuator);
    if (gamepad.hapticActuators)
      hapticActuators.push(...gamepad.hapticActuators);
    return {
      id: gamepad.id,
      index: gamepad.index,
      connected: gamepad.connected,
      mapping: gamepad.mapping,
      timestamp: gamepad.timestamp,
      vibrationActuator: gamepad.vibrationActuator,
      hapticActuators,
      axes: gamepad.axes.map((axes) => axes),
      buttons: gamepad.buttons.map((button) => ({ pressed: button.pressed, touched: button.touched, value: button.value }))
    };
  };
  const updateGamepadState = () => {
    const _gamepads = (navigator2 == null ? void 0 : navigator2.getGamepads()) || [];
    for (const gamepad of _gamepads) {
      if (gamepad && gamepads.value[gamepad.index])
        gamepads.value[gamepad.index] = stateFromGamepad(gamepad);
    }
  };
  const { isActive, pause, resume } = useRafFn(updateGamepadState);
  const onGamepadConnected = (gamepad) => {
    if (!gamepads.value.some(({ index }) => index === gamepad.index)) {
      gamepads.value.push(stateFromGamepad(gamepad));
      onConnectedHook.trigger(gamepad.index);
    }
    resume();
  };
  const onGamepadDisconnected = (gamepad) => {
    gamepads.value = gamepads.value.filter((x) => x.index !== gamepad.index);
    onDisconnectedHook.trigger(gamepad.index);
  };
  const listenerOptions = { passive: true };
  useEventListener("gamepadconnected", (e) => onGamepadConnected(e.gamepad), listenerOptions);
  useEventListener("gamepaddisconnected", (e) => onGamepadDisconnected(e.gamepad), listenerOptions);
  tryOnMounted(() => {
    const _gamepads = (navigator2 == null ? void 0 : navigator2.getGamepads()) || [];
    for (const gamepad of _gamepads) {
      if (gamepad && gamepads.value[gamepad.index])
        onGamepadConnected(gamepad);
    }
  });
  pause();
  return {
    isSupported,
    onConnected: onConnectedHook.on,
    onDisconnected: onDisconnectedHook.on,
    gamepads,
    pause,
    resume,
    isActive
  };
}
function useGeolocation(options = {}) {
  const {
    enableHighAccuracy = true,
    maximumAge = 3e4,
    timeout = 27e3,
    navigator: navigator2 = defaultNavigator,
    immediate = true
  } = options;
  const isSupported = useSupported(() => navigator2 && "geolocation" in navigator2);
  const locatedAt = shallowRef(null);
  const error = shallowRef(null);
  const coords = ref({
    accuracy: 0,
    latitude: Number.POSITIVE_INFINITY,
    longitude: Number.POSITIVE_INFINITY,
    altitude: null,
    altitudeAccuracy: null,
    heading: null,
    speed: null
  });
  function updatePosition(position) {
    locatedAt.value = position.timestamp;
    coords.value = position.coords;
    error.value = null;
  }
  let watcher;
  function resume() {
    if (isSupported.value) {
      watcher = navigator2.geolocation.watchPosition(
        updatePosition,
        (err) => error.value = err,
        {
          enableHighAccuracy,
          maximumAge,
          timeout
        }
      );
    }
  }
  if (immediate)
    resume();
  function pause() {
    if (watcher && navigator2)
      navigator2.geolocation.clearWatch(watcher);
  }
  tryOnScopeDispose(() => {
    pause();
  });
  return {
    isSupported,
    coords,
    locatedAt,
    error,
    resume,
    pause
  };
}
const defaultEvents$1 = ["mousemove", "mousedown", "resize", "keydown", "touchstart", "wheel"];
const oneMinute = 6e4;
function useIdle(timeout = oneMinute, options = {}) {
  const {
    initialState = false,
    listenForVisibilityChange = true,
    events: events2 = defaultEvents$1,
    window: window2 = defaultWindow,
    eventFilter = throttleFilter(50)
  } = options;
  const idle = shallowRef(initialState);
  const lastActive = shallowRef(timestamp());
  let timer;
  const reset = () => {
    idle.value = false;
    clearTimeout(timer);
    timer = setTimeout(() => idle.value = true, timeout);
  };
  const onEvent = createFilterWrapper(
    eventFilter,
    () => {
      lastActive.value = timestamp();
      reset();
    }
  );
  if (window2) {
    const document2 = window2.document;
    const listenerOptions = { passive: true };
    for (const event of events2)
      useEventListener(window2, event, onEvent, listenerOptions);
    if (listenForVisibilityChange) {
      useEventListener(document2, "visibilitychange", () => {
        if (!document2.hidden)
          onEvent();
      }, listenerOptions);
    }
    reset();
  }
  return {
    idle,
    lastActive,
    reset
  };
}
async function loadImage(options) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    const { src, srcset, sizes, class: clazz, loading, crossorigin, referrerPolicy, width, height, decoding, fetchPriority, ismap, usemap } = options;
    img.src = src;
    if (srcset != null)
      img.srcset = srcset;
    if (sizes != null)
      img.sizes = sizes;
    if (clazz != null)
      img.className = clazz;
    if (loading != null)
      img.loading = loading;
    if (crossorigin != null)
      img.crossOrigin = crossorigin;
    if (referrerPolicy != null)
      img.referrerPolicy = referrerPolicy;
    if (width != null)
      img.width = width;
    if (height != null)
      img.height = height;
    if (decoding != null)
      img.decoding = decoding;
    if (fetchPriority != null)
      img.fetchPriority = fetchPriority;
    if (ismap != null)
      img.isMap = ismap;
    if (usemap != null)
      img.useMap = usemap;
    img.onload = () => resolve(img);
    img.onerror = reject;
  });
}
function useImage(options, asyncStateOptions = {}) {
  const state = useAsyncState(
    () => loadImage(toValue$1(options)),
    void 0,
    {
      resetOnExecute: true,
      ...asyncStateOptions
    }
  );
  watch(
    () => toValue$1(options),
    () => state.execute(asyncStateOptions.delay),
    { deep: true }
  );
  return state;
}
function resolveElement(el) {
  if (typeof Window !== "undefined" && el instanceof Window)
    return el.document.documentElement;
  if (typeof Document !== "undefined" && el instanceof Document)
    return el.documentElement;
  return el;
}
const ARRIVED_STATE_THRESHOLD_PIXELS = 1;
function useScroll(element, options = {}) {
  const {
    throttle = 0,
    idle = 200,
    onStop = noop$3,
    onScroll = noop$3,
    offset = {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    },
    eventListenerOptions = {
      capture: false,
      passive: true
    },
    behavior = "auto",
    window: window2 = defaultWindow,
    onError = (e) => {
      console.error(e);
    }
  } = options;
  const internalX = shallowRef(0);
  const internalY = shallowRef(0);
  const x = computed({
    get() {
      return internalX.value;
    },
    set(x2) {
      scrollTo(x2, void 0);
    }
  });
  const y = computed({
    get() {
      return internalY.value;
    },
    set(y2) {
      scrollTo(void 0, y2);
    }
  });
  function scrollTo(_x, _y) {
    var _a, _b, _c, _d;
    if (!window2)
      return;
    const _element = toValue$1(element);
    if (!_element)
      return;
    (_c = _element instanceof Document ? window2.document.body : _element) == null ? void 0 : _c.scrollTo({
      top: (_a = toValue$1(_y)) != null ? _a : y.value,
      left: (_b = toValue$1(_x)) != null ? _b : x.value,
      behavior: toValue$1(behavior)
    });
    const scrollContainer = ((_d = _element == null ? void 0 : _element.document) == null ? void 0 : _d.documentElement) || (_element == null ? void 0 : _element.documentElement) || _element;
    if (x != null)
      internalX.value = scrollContainer.scrollLeft;
    if (y != null)
      internalY.value = scrollContainer.scrollTop;
  }
  const isScrolling = shallowRef(false);
  const arrivedState = reactive({
    left: true,
    right: false,
    top: true,
    bottom: false
  });
  const directions = reactive({
    left: false,
    right: false,
    top: false,
    bottom: false
  });
  const onScrollEnd = (e) => {
    if (!isScrolling.value)
      return;
    isScrolling.value = false;
    directions.left = false;
    directions.right = false;
    directions.top = false;
    directions.bottom = false;
    onStop(e);
  };
  const onScrollEndDebounced = useDebounceFn(onScrollEnd, throttle + idle);
  const setArrivedState = (target) => {
    var _a;
    if (!window2)
      return;
    const el = ((_a = target == null ? void 0 : target.document) == null ? void 0 : _a.documentElement) || (target == null ? void 0 : target.documentElement) || unrefElement(target);
    const { display, flexDirection, direction } = getComputedStyle(el);
    const directionMultipler = direction === "rtl" ? -1 : 1;
    const scrollLeft = el.scrollLeft;
    directions.left = scrollLeft < internalX.value;
    directions.right = scrollLeft > internalX.value;
    const left = Math.abs(scrollLeft * directionMultipler) <= (offset.left || 0);
    const right = Math.abs(scrollLeft * directionMultipler) + el.clientWidth >= el.scrollWidth - (offset.right || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;
    if (display === "flex" && flexDirection === "row-reverse") {
      arrivedState.left = right;
      arrivedState.right = left;
    } else {
      arrivedState.left = left;
      arrivedState.right = right;
    }
    internalX.value = scrollLeft;
    let scrollTop = el.scrollTop;
    if (target === window2.document && !scrollTop)
      scrollTop = window2.document.body.scrollTop;
    directions.top = scrollTop < internalY.value;
    directions.bottom = scrollTop > internalY.value;
    const top = Math.abs(scrollTop) <= (offset.top || 0);
    const bottom = Math.abs(scrollTop) + el.clientHeight >= el.scrollHeight - (offset.bottom || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;
    if (display === "flex" && flexDirection === "column-reverse") {
      arrivedState.top = bottom;
      arrivedState.bottom = top;
    } else {
      arrivedState.top = top;
      arrivedState.bottom = bottom;
    }
    internalY.value = scrollTop;
  };
  const onScrollHandler = (e) => {
    var _a;
    if (!window2)
      return;
    const eventTarget = (_a = e.target.documentElement) != null ? _a : e.target;
    setArrivedState(eventTarget);
    isScrolling.value = true;
    onScrollEndDebounced(e);
    onScroll(e);
  };
  useEventListener(
    element,
    "scroll",
    throttle ? useThrottleFn(onScrollHandler, throttle, true, false) : onScrollHandler,
    eventListenerOptions
  );
  tryOnMounted(() => {
    try {
      const _element = toValue$1(element);
      if (!_element)
        return;
      setArrivedState(_element);
    } catch (e) {
      onError(e);
    }
  });
  useEventListener(
    element,
    "scrollend",
    onScrollEnd,
    eventListenerOptions
  );
  return {
    x,
    y,
    isScrolling,
    arrivedState,
    directions,
    measure() {
      const _element = toValue$1(element);
      if (window2 && _element)
        setArrivedState(_element);
    }
  };
}
function useInfiniteScroll(element, onLoadMore, options = {}) {
  var _a;
  const {
    direction = "bottom",
    interval = 100,
    canLoadMore = () => true
  } = options;
  const state = reactive(useScroll(
    element,
    {
      ...options,
      offset: {
        [direction]: (_a = options.distance) != null ? _a : 0,
        ...options.offset
      }
    }
  ));
  const promise = ref();
  const isLoading = computed(() => !!promise.value);
  const observedElement = computed(() => {
    return resolveElement(toValue$1(element));
  });
  const isElementVisible = useElementVisibility(observedElement);
  function checkAndLoad() {
    state.measure();
    if (!observedElement.value || !isElementVisible.value || !canLoadMore(observedElement.value))
      return;
    const { scrollHeight, clientHeight, scrollWidth, clientWidth } = observedElement.value;
    const isNarrower = direction === "bottom" || direction === "top" ? scrollHeight <= clientHeight : scrollWidth <= clientWidth;
    if (state.arrivedState[direction] || isNarrower) {
      if (!promise.value) {
        promise.value = Promise.all([
          onLoadMore(state),
          new Promise((resolve) => setTimeout(resolve, interval))
        ]).finally(() => {
          promise.value = null;
          nextTick(() => checkAndLoad());
        });
      }
    }
  }
  const stop = watch(
    () => [state.arrivedState[direction], isElementVisible.value],
    checkAndLoad,
    { immediate: true }
  );
  tryOnUnmounted(stop);
  return {
    isLoading,
    reset() {
      nextTick(() => checkAndLoad());
    }
  };
}
const defaultEvents = ["mousedown", "mouseup", "keydown", "keyup"];
function useKeyModifier(modifier, options = {}) {
  const {
    events: events2 = defaultEvents,
    document: document2 = defaultDocument,
    initial = null
  } = options;
  const state = shallowRef(initial);
  if (document2) {
    events2.forEach((listenerEvent) => {
      useEventListener(document2, listenerEvent, (evt) => {
        if (typeof evt.getModifierState === "function")
          state.value = evt.getModifierState(modifier);
      }, { passive: true });
    });
  }
  return state;
}
function useLocalStorage(key, initialValue, options = {}) {
  const { window: window2 = defaultWindow } = options;
  return useStorage(key, initialValue, window2 == null ? void 0 : window2.localStorage, options);
}
const DefaultMagicKeysAliasMap = {
  ctrl: "control",
  command: "meta",
  cmd: "meta",
  option: "alt",
  up: "arrowup",
  down: "arrowdown",
  left: "arrowleft",
  right: "arrowright"
};
function useMagicKeys(options = {}) {
  const {
    reactive: useReactive = false,
    target = defaultWindow,
    aliasMap = DefaultMagicKeysAliasMap,
    passive = true,
    onEventFired = noop$3
  } = options;
  const current = reactive(/* @__PURE__ */ new Set());
  const obj = {
    toJSON() {
      return {};
    },
    current
  };
  const refs = useReactive ? reactive(obj) : obj;
  const metaDeps = /* @__PURE__ */ new Set();
  const usedKeys = /* @__PURE__ */ new Set();
  function setRefs(key, value) {
    if (key in refs) {
      if (useReactive)
        refs[key] = value;
      else
        refs[key].value = value;
    }
  }
  function reset() {
    current.clear();
    for (const key of usedKeys)
      setRefs(key, false);
  }
  function updateRefs(e, value) {
    var _a, _b;
    const key = (_a = e.key) == null ? void 0 : _a.toLowerCase();
    const code = (_b = e.code) == null ? void 0 : _b.toLowerCase();
    const values = [code, key].filter(Boolean);
    if (key) {
      if (value)
        current.add(key);
      else
        current.delete(key);
    }
    for (const key2 of values) {
      usedKeys.add(key2);
      setRefs(key2, value);
    }
    if (key === "meta" && !value) {
      metaDeps.forEach((key2) => {
        current.delete(key2);
        setRefs(key2, false);
      });
      metaDeps.clear();
    } else if (typeof e.getModifierState === "function" && e.getModifierState("Meta") && value) {
      [...current, ...values].forEach((key2) => metaDeps.add(key2));
    }
  }
  useEventListener(target, "keydown", (e) => {
    updateRefs(e, true);
    return onEventFired(e);
  }, { passive });
  useEventListener(target, "keyup", (e) => {
    updateRefs(e, false);
    return onEventFired(e);
  }, { passive });
  useEventListener("blur", reset, { passive });
  useEventListener("focus", reset, { passive });
  const proxy = new Proxy(
    refs,
    {
      get(target2, prop, rec) {
        if (typeof prop !== "string")
          return Reflect.get(target2, prop, rec);
        prop = prop.toLowerCase();
        if (prop in aliasMap)
          prop = aliasMap[prop];
        if (!(prop in refs)) {
          if (/[+_-]/.test(prop)) {
            const keys2 = prop.split(/[+_-]/g).map((i) => i.trim());
            refs[prop] = computed(() => keys2.map((key) => toValue$1(proxy[key])).every(Boolean));
          } else {
            refs[prop] = shallowRef(false);
          }
        }
        const r = Reflect.get(target2, prop, rec);
        return useReactive ? toValue$1(r) : r;
      }
    }
  );
  return proxy;
}
function usingElRef(source, cb) {
  if (toValue$1(source))
    cb(toValue$1(source));
}
function timeRangeToArray(timeRanges) {
  let ranges = [];
  for (let i = 0; i < timeRanges.length; ++i)
    ranges = [...ranges, [timeRanges.start(i), timeRanges.end(i)]];
  return ranges;
}
function tracksToArray(tracks) {
  return Array.from(tracks).map(({ label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType }, id) => ({ id, label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType }));
}
const defaultOptions = {
  src: "",
  tracks: []
};
function useMediaControls(target, options = {}) {
  target = toRef(target);
  options = {
    ...defaultOptions,
    ...options
  };
  const {
    document: document2 = defaultDocument
  } = options;
  const listenerOptions = { passive: true };
  const currentTime = shallowRef(0);
  const duration = shallowRef(0);
  const seeking = shallowRef(false);
  const volume = shallowRef(1);
  const waiting = shallowRef(false);
  const ended = shallowRef(false);
  const playing = shallowRef(false);
  const rate = shallowRef(1);
  const stalled = shallowRef(false);
  const buffered = ref([]);
  const tracks = ref([]);
  const selectedTrack = shallowRef(-1);
  const isPictureInPicture = shallowRef(false);
  const muted = shallowRef(false);
  const supportsPictureInPicture = document2 && "pictureInPictureEnabled" in document2;
  const sourceErrorEvent = createEventHook();
  const playbackErrorEvent = createEventHook();
  const disableTrack = (track) => {
    usingElRef(target, (el) => {
      if (track) {
        const id = typeof track === "number" ? track : track.id;
        el.textTracks[id].mode = "disabled";
      } else {
        for (let i = 0; i < el.textTracks.length; ++i)
          el.textTracks[i].mode = "disabled";
      }
      selectedTrack.value = -1;
    });
  };
  const enableTrack = (track, disableTracks = true) => {
    usingElRef(target, (el) => {
      const id = typeof track === "number" ? track : track.id;
      if (disableTracks)
        disableTrack();
      el.textTracks[id].mode = "showing";
      selectedTrack.value = id;
    });
  };
  const togglePictureInPicture = () => {
    return new Promise((resolve, reject) => {
      usingElRef(target, async (el) => {
        if (supportsPictureInPicture) {
          if (!isPictureInPicture.value) {
            el.requestPictureInPicture().then(resolve).catch(reject);
          } else {
            document2.exitPictureInPicture().then(resolve).catch(reject);
          }
        }
      });
    });
  };
  watchEffect(() => {
    if (!document2)
      return;
    const el = toValue$1(target);
    if (!el)
      return;
    const src = toValue$1(options.src);
    let sources = [];
    if (!src)
      return;
    if (typeof src === "string")
      sources = [{ src }];
    else if (Array.isArray(src))
      sources = src;
    else if (isObject$2(src))
      sources = [src];
    el.querySelectorAll("source").forEach((e) => {
      e.remove();
    });
    sources.forEach(({ src: src2, type, media }) => {
      const source = document2.createElement("source");
      source.setAttribute("src", src2);
      source.setAttribute("type", type || "");
      source.setAttribute("media", media || "");
      useEventListener(source, "error", sourceErrorEvent.trigger, listenerOptions);
      el.appendChild(source);
    });
    el.load();
  });
  watch([target, volume], () => {
    const el = toValue$1(target);
    if (!el)
      return;
    el.volume = volume.value;
  });
  watch([target, muted], () => {
    const el = toValue$1(target);
    if (!el)
      return;
    el.muted = muted.value;
  });
  watch([target, rate], () => {
    const el = toValue$1(target);
    if (!el)
      return;
    el.playbackRate = rate.value;
  });
  watchEffect(() => {
    if (!document2)
      return;
    const textTracks = toValue$1(options.tracks);
    const el = toValue$1(target);
    if (!textTracks || !textTracks.length || !el)
      return;
    el.querySelectorAll("track").forEach((e) => e.remove());
    textTracks.forEach(({ default: isDefault, kind, label, src, srcLang }, i) => {
      const track = document2.createElement("track");
      track.default = isDefault || false;
      track.kind = kind;
      track.label = label;
      track.src = src;
      track.srclang = srcLang;
      if (track.default)
        selectedTrack.value = i;
      el.appendChild(track);
    });
  });
  const { ignoreUpdates: ignoreCurrentTimeUpdates } = watchIgnorable(currentTime, (time) => {
    const el = toValue$1(target);
    if (!el)
      return;
    el.currentTime = time;
  });
  const { ignoreUpdates: ignorePlayingUpdates } = watchIgnorable(playing, (isPlaying) => {
    const el = toValue$1(target);
    if (!el)
      return;
    if (isPlaying) {
      el.play().catch((e) => {
        playbackErrorEvent.trigger(e);
        throw e;
      });
    } else {
      el.pause();
    }
  });
  useEventListener(
    target,
    "timeupdate",
    () => ignoreCurrentTimeUpdates(() => currentTime.value = toValue$1(target).currentTime),
    listenerOptions
  );
  useEventListener(
    target,
    "durationchange",
    () => duration.value = toValue$1(target).duration,
    listenerOptions
  );
  useEventListener(
    target,
    "progress",
    () => buffered.value = timeRangeToArray(toValue$1(target).buffered),
    listenerOptions
  );
  useEventListener(
    target,
    "seeking",
    () => seeking.value = true,
    listenerOptions
  );
  useEventListener(
    target,
    "seeked",
    () => seeking.value = false,
    listenerOptions
  );
  useEventListener(
    target,
    ["waiting", "loadstart"],
    () => {
      waiting.value = true;
      ignorePlayingUpdates(() => playing.value = false);
    },
    listenerOptions
  );
  useEventListener(
    target,
    "loadeddata",
    () => waiting.value = false,
    listenerOptions
  );
  useEventListener(
    target,
    "playing",
    () => {
      waiting.value = false;
      ended.value = false;
      ignorePlayingUpdates(() => playing.value = true);
    },
    listenerOptions
  );
  useEventListener(
    target,
    "ratechange",
    () => rate.value = toValue$1(target).playbackRate,
    listenerOptions
  );
  useEventListener(
    target,
    "stalled",
    () => stalled.value = true,
    listenerOptions
  );
  useEventListener(
    target,
    "ended",
    () => ended.value = true,
    listenerOptions
  );
  useEventListener(
    target,
    "pause",
    () => ignorePlayingUpdates(() => playing.value = false),
    listenerOptions
  );
  useEventListener(
    target,
    "play",
    () => ignorePlayingUpdates(() => playing.value = true),
    listenerOptions
  );
  useEventListener(
    target,
    "enterpictureinpicture",
    () => isPictureInPicture.value = true,
    listenerOptions
  );
  useEventListener(
    target,
    "leavepictureinpicture",
    () => isPictureInPicture.value = false,
    listenerOptions
  );
  useEventListener(
    target,
    "volumechange",
    () => {
      const el = toValue$1(target);
      if (!el)
        return;
      volume.value = el.volume;
      muted.value = el.muted;
    },
    listenerOptions
  );
  const listeners = [];
  const stop = watch([target], () => {
    const el = toValue$1(target);
    if (!el)
      return;
    stop();
    listeners[0] = useEventListener(el.textTracks, "addtrack", () => tracks.value = tracksToArray(el.textTracks), listenerOptions);
    listeners[1] = useEventListener(el.textTracks, "removetrack", () => tracks.value = tracksToArray(el.textTracks), listenerOptions);
    listeners[2] = useEventListener(el.textTracks, "change", () => tracks.value = tracksToArray(el.textTracks), listenerOptions);
  });
  tryOnScopeDispose(() => listeners.forEach((listener) => listener()));
  return {
    currentTime,
    duration,
    waiting,
    seeking,
    ended,
    stalled,
    buffered,
    playing,
    rate,
    // Volume
    volume,
    muted,
    // Tracks
    tracks,
    selectedTrack,
    enableTrack,
    disableTrack,
    // Picture in Picture
    supportsPictureInPicture,
    togglePictureInPicture,
    isPictureInPicture,
    // Events
    onSourceError: sourceErrorEvent.on,
    onPlaybackError: playbackErrorEvent.on
  };
}
function useMemoize(resolver, options) {
  const initCache = () => {
    if (options == null ? void 0 : options.cache)
      return shallowReactive(options.cache);
    return shallowReactive(/* @__PURE__ */ new Map());
  };
  const cache = initCache();
  const generateKey = (...args) => (options == null ? void 0 : options.getKey) ? options.getKey(...args) : JSON.stringify(args);
  const _loadData = (key, ...args) => {
    cache.set(key, resolver(...args));
    return cache.get(key);
  };
  const loadData = (...args) => _loadData(generateKey(...args), ...args);
  const deleteData = (...args) => {
    cache.delete(generateKey(...args));
  };
  const clearData = () => {
    cache.clear();
  };
  const memoized = (...args) => {
    const key = generateKey(...args);
    if (cache.has(key))
      return cache.get(key);
    return _loadData(key, ...args);
  };
  memoized.load = loadData;
  memoized.delete = deleteData;
  memoized.clear = clearData;
  memoized.generateKey = generateKey;
  memoized.cache = cache;
  return memoized;
}
function useMemory(options = {}) {
  const memory = ref();
  const isSupported = useSupported(() => typeof performance !== "undefined" && "memory" in performance);
  if (isSupported.value) {
    const { interval = 1e3 } = options;
    useIntervalFn(() => {
      memory.value = performance.memory;
    }, interval, { immediate: options.immediate, immediateCallback: options.immediateCallback });
  }
  return { isSupported, memory };
}
const UseMouseBuiltinExtractors = {
  page: (event) => [event.pageX, event.pageY],
  client: (event) => [event.clientX, event.clientY],
  screen: (event) => [event.screenX, event.screenY],
  movement: (event) => event instanceof MouseEvent ? [event.movementX, event.movementY] : null
};
function useMouse(options = {}) {
  const {
    type = "page",
    touch = true,
    resetOnTouchEnds = false,
    initialValue = { x: 0, y: 0 },
    window: window2 = defaultWindow,
    target = window2,
    scroll = true,
    eventFilter
  } = options;
  let _prevMouseEvent = null;
  let _prevScrollX = 0;
  let _prevScrollY = 0;
  const x = shallowRef(initialValue.x);
  const y = shallowRef(initialValue.y);
  const sourceType = shallowRef(null);
  const extractor = typeof type === "function" ? type : UseMouseBuiltinExtractors[type];
  const mouseHandler = (event) => {
    const result = extractor(event);
    _prevMouseEvent = event;
    if (result) {
      [x.value, y.value] = result;
      sourceType.value = "mouse";
    }
    if (window2) {
      _prevScrollX = window2.scrollX;
      _prevScrollY = window2.scrollY;
    }
  };
  const touchHandler = (event) => {
    if (event.touches.length > 0) {
      const result = extractor(event.touches[0]);
      if (result) {
        [x.value, y.value] = result;
        sourceType.value = "touch";
      }
    }
  };
  const scrollHandler = () => {
    if (!_prevMouseEvent || !window2)
      return;
    const pos = extractor(_prevMouseEvent);
    if (_prevMouseEvent instanceof MouseEvent && pos) {
      x.value = pos[0] + window2.scrollX - _prevScrollX;
      y.value = pos[1] + window2.scrollY - _prevScrollY;
    }
  };
  const reset = () => {
    x.value = initialValue.x;
    y.value = initialValue.y;
  };
  const mouseHandlerWrapper = eventFilter ? (event) => eventFilter(() => mouseHandler(event), {}) : (event) => mouseHandler(event);
  const touchHandlerWrapper = eventFilter ? (event) => eventFilter(() => touchHandler(event), {}) : (event) => touchHandler(event);
  const scrollHandlerWrapper = eventFilter ? () => eventFilter(() => scrollHandler(), {}) : () => scrollHandler();
  if (target) {
    const listenerOptions = { passive: true };
    useEventListener(target, ["mousemove", "dragover"], mouseHandlerWrapper, listenerOptions);
    if (touch && type !== "movement") {
      useEventListener(target, ["touchstart", "touchmove"], touchHandlerWrapper, listenerOptions);
      if (resetOnTouchEnds)
        useEventListener(target, "touchend", reset, listenerOptions);
    }
    if (scroll && type === "page")
      useEventListener(window2, "scroll", scrollHandlerWrapper, listenerOptions);
  }
  return {
    x,
    y,
    sourceType
  };
}
function useMouseInElement(target, options = {}) {
  const {
    handleOutside = true,
    window: window2 = defaultWindow
  } = options;
  const type = options.type || "page";
  const { x, y, sourceType } = useMouse(options);
  const targetRef = shallowRef(target != null ? target : window2 == null ? void 0 : window2.document.body);
  const elementX = shallowRef(0);
  const elementY = shallowRef(0);
  const elementPositionX = shallowRef(0);
  const elementPositionY = shallowRef(0);
  const elementHeight = shallowRef(0);
  const elementWidth = shallowRef(0);
  const isOutside = shallowRef(true);
  let stop = () => {
  };
  if (window2) {
    stop = watch(
      [targetRef, x, y],
      () => {
        const el = unrefElement(targetRef);
        if (!el || !(el instanceof Element))
          return;
        const {
          left,
          top,
          width,
          height
        } = el.getBoundingClientRect();
        elementPositionX.value = left + (type === "page" ? window2.pageXOffset : 0);
        elementPositionY.value = top + (type === "page" ? window2.pageYOffset : 0);
        elementHeight.value = height;
        elementWidth.value = width;
        const elX = x.value - elementPositionX.value;
        const elY = y.value - elementPositionY.value;
        isOutside.value = width === 0 || height === 0 || elX < 0 || elY < 0 || elX > width || elY > height;
        if (handleOutside || !isOutside.value) {
          elementX.value = elX;
          elementY.value = elY;
        }
      },
      { immediate: true }
    );
    useEventListener(
      document,
      "mouseleave",
      () => isOutside.value = true,
      { passive: true }
    );
  }
  return {
    x,
    y,
    sourceType,
    elementX,
    elementY,
    elementPositionX,
    elementPositionY,
    elementHeight,
    elementWidth,
    isOutside,
    stop
  };
}
function useMousePressed(options = {}) {
  const {
    touch = true,
    drag = true,
    capture = false,
    initialValue = false,
    window: window2 = defaultWindow
  } = options;
  const pressed = shallowRef(initialValue);
  const sourceType = shallowRef(null);
  if (!window2) {
    return {
      pressed,
      sourceType
    };
  }
  const onPressed = (srcType) => (event) => {
    var _a;
    pressed.value = true;
    sourceType.value = srcType;
    (_a = options.onPressed) == null ? void 0 : _a.call(options, event);
  };
  const onReleased = (event) => {
    var _a;
    pressed.value = false;
    sourceType.value = null;
    (_a = options.onReleased) == null ? void 0 : _a.call(options, event);
  };
  const target = computed(() => unrefElement(options.target) || window2);
  const listenerOptions = { passive: true, capture };
  useEventListener(target, "mousedown", onPressed("mouse"), listenerOptions);
  useEventListener(window2, "mouseleave", onReleased, listenerOptions);
  useEventListener(window2, "mouseup", onReleased, listenerOptions);
  if (drag) {
    useEventListener(target, "dragstart", onPressed("mouse"), listenerOptions);
    useEventListener(window2, "drop", onReleased, listenerOptions);
    useEventListener(window2, "dragend", onReleased, listenerOptions);
  }
  if (touch) {
    useEventListener(target, "touchstart", onPressed("touch"), listenerOptions);
    useEventListener(window2, "touchend", onReleased, listenerOptions);
    useEventListener(window2, "touchcancel", onReleased, listenerOptions);
  }
  return {
    pressed,
    sourceType
  };
}
function useNavigatorLanguage(options = {}) {
  const { window: window2 = defaultWindow } = options;
  const navigator2 = window2 == null ? void 0 : window2.navigator;
  const isSupported = useSupported(() => navigator2 && "language" in navigator2);
  const language = shallowRef(navigator2 == null ? void 0 : navigator2.language);
  useEventListener(window2, "languagechange", () => {
    if (navigator2)
      language.value = navigator2.language;
  }, { passive: true });
  return {
    isSupported,
    language
  };
}
function useNetwork(options = {}) {
  const { window: window2 = defaultWindow } = options;
  const navigator2 = window2 == null ? void 0 : window2.navigator;
  const isSupported = useSupported(() => navigator2 && "connection" in navigator2);
  const isOnline = shallowRef(true);
  const saveData = shallowRef(false);
  const offlineAt = shallowRef(void 0);
  const onlineAt = shallowRef(void 0);
  const downlink = shallowRef(void 0);
  const downlinkMax = shallowRef(void 0);
  const rtt = shallowRef(void 0);
  const effectiveType = shallowRef(void 0);
  const type = shallowRef("unknown");
  const connection = isSupported.value && navigator2.connection;
  function updateNetworkInformation() {
    if (!navigator2)
      return;
    isOnline.value = navigator2.onLine;
    offlineAt.value = isOnline.value ? void 0 : Date.now();
    onlineAt.value = isOnline.value ? Date.now() : void 0;
    if (connection) {
      downlink.value = connection.downlink;
      downlinkMax.value = connection.downlinkMax;
      effectiveType.value = connection.effectiveType;
      rtt.value = connection.rtt;
      saveData.value = connection.saveData;
      type.value = connection.type;
    }
  }
  const listenerOptions = { passive: true };
  if (window2) {
    useEventListener(window2, "offline", () => {
      isOnline.value = false;
      offlineAt.value = Date.now();
    }, listenerOptions);
    useEventListener(window2, "online", () => {
      isOnline.value = true;
      onlineAt.value = Date.now();
    }, listenerOptions);
  }
  if (connection)
    useEventListener(connection, "change", updateNetworkInformation, listenerOptions);
  updateNetworkInformation();
  return {
    isSupported,
    isOnline: readonly(isOnline),
    saveData: readonly(saveData),
    offlineAt: readonly(offlineAt),
    onlineAt: readonly(onlineAt),
    downlink: readonly(downlink),
    downlinkMax: readonly(downlinkMax),
    effectiveType: readonly(effectiveType),
    rtt: readonly(rtt),
    type: readonly(type)
  };
}
function useNow(options = {}) {
  const {
    controls: exposeControls = false,
    interval = "requestAnimationFrame"
  } = options;
  const now = ref(/* @__PURE__ */ new Date());
  const update = () => now.value = /* @__PURE__ */ new Date();
  const controls = interval === "requestAnimationFrame" ? useRafFn(update, { immediate: true }) : useIntervalFn(update, interval, { immediate: true });
  if (exposeControls) {
    return {
      now,
      ...controls
    };
  } else {
    return now;
  }
}
function useObjectUrl(object) {
  const url = shallowRef();
  const release = () => {
    if (url.value)
      URL.revokeObjectURL(url.value);
    url.value = void 0;
  };
  watch(
    () => toValue$1(object),
    (newObject) => {
      release();
      if (newObject)
        url.value = URL.createObjectURL(newObject);
    },
    { immediate: true }
  );
  tryOnScopeDispose(release);
  return readonly(url);
}
function useClamp(value, min, max) {
  if (typeof value === "function" || isReadonly(value))
    return computed(() => clamp(toValue$1(value), toValue$1(min), toValue$1(max)));
  const _value = ref(value);
  return computed({
    get() {
      return _value.value = clamp(_value.value, toValue$1(min), toValue$1(max));
    },
    set(value2) {
      _value.value = clamp(value2, toValue$1(min), toValue$1(max));
    }
  });
}
function useOffsetPagination(options) {
  const {
    total = Number.POSITIVE_INFINITY,
    pageSize = 10,
    page = 1,
    onPageChange = noop$3,
    onPageSizeChange = noop$3,
    onPageCountChange = noop$3
  } = options;
  const currentPageSize = useClamp(pageSize, 1, Number.POSITIVE_INFINITY);
  const pageCount = computed(() => Math.max(
    1,
    Math.ceil(toValue$1(total) / toValue$1(currentPageSize))
  ));
  const currentPage = useClamp(page, 1, pageCount);
  const isFirstPage = computed(() => currentPage.value === 1);
  const isLastPage = computed(() => currentPage.value === pageCount.value);
  if (isRef(page)) {
    syncRef(page, currentPage, {
      direction: isReadonly(page) ? "ltr" : "both"
    });
  }
  if (isRef(pageSize)) {
    syncRef(pageSize, currentPageSize, {
      direction: isReadonly(pageSize) ? "ltr" : "both"
    });
  }
  function prev() {
    currentPage.value--;
  }
  function next() {
    currentPage.value++;
  }
  const returnValue = {
    currentPage,
    currentPageSize,
    pageCount,
    isFirstPage,
    isLastPage,
    prev,
    next
  };
  watch(currentPage, () => {
    onPageChange(reactive(returnValue));
  });
  watch(currentPageSize, () => {
    onPageSizeChange(reactive(returnValue));
  });
  watch(pageCount, () => {
    onPageCountChange(reactive(returnValue));
  });
  return returnValue;
}
function useOnline(options = {}) {
  const { isOnline } = useNetwork(options);
  return isOnline;
}
function usePageLeave(options = {}) {
  const { window: window2 = defaultWindow } = options;
  const isLeft = shallowRef(false);
  const handler = (event) => {
    if (!window2)
      return;
    event = event || window2.event;
    const from = event.relatedTarget || event.toElement;
    isLeft.value = !from;
  };
  if (window2) {
    const listenerOptions = { passive: true };
    useEventListener(window2, "mouseout", handler, listenerOptions);
    useEventListener(window2.document, "mouseleave", handler, listenerOptions);
    useEventListener(window2.document, "mouseenter", handler, listenerOptions);
  }
  return isLeft;
}
function useScreenOrientation(options = {}) {
  const {
    window: window2 = defaultWindow
  } = options;
  const isSupported = useSupported(() => window2 && "screen" in window2 && "orientation" in window2.screen);
  const screenOrientation = isSupported.value ? window2.screen.orientation : {};
  const orientation = ref(screenOrientation.type);
  const angle = shallowRef(screenOrientation.angle || 0);
  if (isSupported.value) {
    useEventListener(window2, "orientationchange", () => {
      orientation.value = screenOrientation.type;
      angle.value = screenOrientation.angle;
    }, { passive: true });
  }
  const lockOrientation = (type) => {
    if (isSupported.value && typeof screenOrientation.lock === "function")
      return screenOrientation.lock(type);
    return Promise.reject(new Error("Not supported"));
  };
  const unlockOrientation = () => {
    if (isSupported.value && typeof screenOrientation.unlock === "function")
      screenOrientation.unlock();
  };
  return {
    isSupported,
    orientation,
    angle,
    lockOrientation,
    unlockOrientation
  };
}
function useParallax(target, options = {}) {
  const {
    deviceOrientationTiltAdjust = (i) => i,
    deviceOrientationRollAdjust = (i) => i,
    mouseTiltAdjust = (i) => i,
    mouseRollAdjust = (i) => i,
    window: window2 = defaultWindow
  } = options;
  const orientation = reactive(useDeviceOrientation({ window: window2 }));
  const screenOrientation = reactive(useScreenOrientation({ window: window2 }));
  const {
    elementX: x,
    elementY: y,
    elementWidth: width,
    elementHeight: height
  } = useMouseInElement(target, { handleOutside: false, window: window2 });
  const source = computed(() => {
    if (orientation.isSupported && (orientation.alpha != null && orientation.alpha !== 0 || orientation.gamma != null && orientation.gamma !== 0)) {
      return "deviceOrientation";
    }
    return "mouse";
  });
  const roll = computed(() => {
    if (source.value === "deviceOrientation") {
      let value;
      switch (screenOrientation.orientation) {
        case "landscape-primary":
          value = orientation.gamma / 90;
          break;
        case "landscape-secondary":
          value = -orientation.gamma / 90;
          break;
        case "portrait-primary":
          value = -orientation.beta / 90;
          break;
        case "portrait-secondary":
          value = orientation.beta / 90;
          break;
        default:
          value = -orientation.beta / 90;
      }
      return deviceOrientationRollAdjust(value);
    } else {
      const value = -(y.value - height.value / 2) / height.value;
      return mouseRollAdjust(value);
    }
  });
  const tilt = computed(() => {
    if (source.value === "deviceOrientation") {
      let value;
      switch (screenOrientation.orientation) {
        case "landscape-primary":
          value = orientation.beta / 90;
          break;
        case "landscape-secondary":
          value = -orientation.beta / 90;
          break;
        case "portrait-primary":
          value = orientation.gamma / 90;
          break;
        case "portrait-secondary":
          value = -orientation.gamma / 90;
          break;
        default:
          value = orientation.gamma / 90;
      }
      return deviceOrientationTiltAdjust(value);
    } else {
      const value = (x.value - width.value / 2) / width.value;
      return mouseTiltAdjust(value);
    }
  });
  return { roll, tilt, source };
}
function useParentElement(element = useCurrentElement()) {
  const parentElement = shallowRef();
  const update = () => {
    const el = unrefElement(element);
    if (el)
      parentElement.value = el.parentElement;
  };
  tryOnMounted(update);
  watch(() => toValue$1(element), update);
  return parentElement;
}
function usePerformanceObserver(options, callback) {
  const {
    window: window2 = defaultWindow,
    immediate = true,
    ...performanceOptions
  } = options;
  const isSupported = useSupported(() => window2 && "PerformanceObserver" in window2);
  let observer;
  const stop = () => {
    observer == null ? void 0 : observer.disconnect();
  };
  const start = () => {
    if (isSupported.value) {
      stop();
      observer = new PerformanceObserver(callback);
      observer.observe(performanceOptions);
    }
  };
  tryOnScopeDispose(stop);
  if (immediate)
    start();
  return {
    isSupported,
    start,
    stop
  };
}
const defaultState = {
  x: 0,
  y: 0,
  pointerId: 0,
  pressure: 0,
  tiltX: 0,
  tiltY: 0,
  width: 0,
  height: 0,
  twist: 0,
  pointerType: null
};
const keys$1 = /* @__PURE__ */ Object.keys(defaultState);
function usePointer(options = {}) {
  const {
    target = defaultWindow
  } = options;
  const isInside = shallowRef(false);
  const state = ref(options.initialValue || {});
  Object.assign(state.value, defaultState, state.value);
  const handler = (event) => {
    isInside.value = true;
    if (options.pointerTypes && !options.pointerTypes.includes(event.pointerType))
      return;
    state.value = objectPick(event, keys$1, false);
  };
  if (target) {
    const listenerOptions = { passive: true };
    useEventListener(target, ["pointerdown", "pointermove", "pointerup"], handler, listenerOptions);
    useEventListener(target, "pointerleave", () => isInside.value = false, listenerOptions);
  }
  return {
    ...toRefs(state),
    isInside
  };
}
function usePointerLock(target, options = {}) {
  const { document: document2 = defaultDocument } = options;
  const isSupported = useSupported(() => document2 && "pointerLockElement" in document2);
  const element = shallowRef();
  const triggerElement = shallowRef();
  let targetElement;
  if (isSupported.value) {
    const listenerOptions = { passive: true };
    useEventListener(document2, "pointerlockchange", () => {
      var _a;
      const currentElement = (_a = document2.pointerLockElement) != null ? _a : element.value;
      if (targetElement && currentElement === targetElement) {
        element.value = document2.pointerLockElement;
        if (!element.value)
          targetElement = triggerElement.value = null;
      }
    }, listenerOptions);
    useEventListener(document2, "pointerlockerror", () => {
      var _a;
      const currentElement = (_a = document2.pointerLockElement) != null ? _a : element.value;
      if (targetElement && currentElement === targetElement) {
        const action = document2.pointerLockElement ? "release" : "acquire";
        throw new Error(`Failed to ${action} pointer lock.`);
      }
    }, listenerOptions);
  }
  async function lock(e) {
    var _a;
    if (!isSupported.value)
      throw new Error("Pointer Lock API is not supported by your browser.");
    triggerElement.value = e instanceof Event ? e.currentTarget : null;
    targetElement = e instanceof Event ? (_a = unrefElement(target)) != null ? _a : triggerElement.value : unrefElement(e);
    if (!targetElement)
      throw new Error("Target element undefined.");
    targetElement.requestPointerLock();
    return await until(element).toBe(targetElement);
  }
  async function unlock() {
    if (!element.value)
      return false;
    document2.exitPointerLock();
    await until(element).toBeNull();
    return true;
  }
  return {
    isSupported,
    element,
    triggerElement,
    lock,
    unlock
  };
}
function usePointerSwipe(target, options = {}) {
  const targetRef = toRef(target);
  const {
    threshold = 50,
    onSwipe,
    onSwipeEnd,
    onSwipeStart,
    disableTextSelect = false
  } = options;
  const posStart = reactive({ x: 0, y: 0 });
  const updatePosStart = (x, y) => {
    posStart.x = x;
    posStart.y = y;
  };
  const posEnd = reactive({ x: 0, y: 0 });
  const updatePosEnd = (x, y) => {
    posEnd.x = x;
    posEnd.y = y;
  };
  const distanceX = computed(() => posStart.x - posEnd.x);
  const distanceY = computed(() => posStart.y - posEnd.y);
  const { max, abs } = Math;
  const isThresholdExceeded = computed(() => max(abs(distanceX.value), abs(distanceY.value)) >= threshold);
  const isSwiping = shallowRef(false);
  const isPointerDown = shallowRef(false);
  const direction = computed(() => {
    if (!isThresholdExceeded.value)
      return "none";
    if (abs(distanceX.value) > abs(distanceY.value)) {
      return distanceX.value > 0 ? "left" : "right";
    } else {
      return distanceY.value > 0 ? "up" : "down";
    }
  });
  const eventIsAllowed = (e) => {
    var _a, _b, _c;
    const isReleasingButton = e.buttons === 0;
    const isPrimaryButton = e.buttons === 1;
    return (_c = (_b = (_a = options.pointerTypes) == null ? void 0 : _a.includes(e.pointerType)) != null ? _b : isReleasingButton || isPrimaryButton) != null ? _c : true;
  };
  const listenerOptions = { passive: true };
  const stops = [
    useEventListener(target, "pointerdown", (e) => {
      if (!eventIsAllowed(e))
        return;
      isPointerDown.value = true;
      const eventTarget = e.target;
      eventTarget == null ? void 0 : eventTarget.setPointerCapture(e.pointerId);
      const { clientX: x, clientY: y } = e;
      updatePosStart(x, y);
      updatePosEnd(x, y);
      onSwipeStart == null ? void 0 : onSwipeStart(e);
    }, listenerOptions),
    useEventListener(target, "pointermove", (e) => {
      if (!eventIsAllowed(e))
        return;
      if (!isPointerDown.value)
        return;
      const { clientX: x, clientY: y } = e;
      updatePosEnd(x, y);
      if (!isSwiping.value && isThresholdExceeded.value)
        isSwiping.value = true;
      if (isSwiping.value)
        onSwipe == null ? void 0 : onSwipe(e);
    }, listenerOptions),
    useEventListener(target, "pointerup", (e) => {
      if (!eventIsAllowed(e))
        return;
      if (isSwiping.value)
        onSwipeEnd == null ? void 0 : onSwipeEnd(e, direction.value);
      isPointerDown.value = false;
      isSwiping.value = false;
    }, listenerOptions)
  ];
  tryOnMounted(() => {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    (_b = (_a = targetRef.value) == null ? void 0 : _a.style) == null ? void 0 : _b.setProperty("touch-action", "none");
    if (disableTextSelect) {
      (_d = (_c = targetRef.value) == null ? void 0 : _c.style) == null ? void 0 : _d.setProperty("-webkit-user-select", "none");
      (_f = (_e = targetRef.value) == null ? void 0 : _e.style) == null ? void 0 : _f.setProperty("-ms-user-select", "none");
      (_h = (_g = targetRef.value) == null ? void 0 : _g.style) == null ? void 0 : _h.setProperty("user-select", "none");
    }
  });
  const stop = () => stops.forEach((s) => s());
  return {
    isSwiping: readonly(isSwiping),
    direction: readonly(direction),
    posStart: readonly(posStart),
    posEnd: readonly(posEnd),
    distanceX,
    distanceY,
    stop
  };
}
function usePreferredColorScheme(options) {
  const isLight = useMediaQuery("(prefers-color-scheme: light)", options);
  const isDark = useMediaQuery("(prefers-color-scheme: dark)", options);
  return computed(() => {
    if (isDark.value)
      return "dark";
    if (isLight.value)
      return "light";
    return "no-preference";
  });
}
function usePreferredContrast(options) {
  const isMore = useMediaQuery("(prefers-contrast: more)", options);
  const isLess = useMediaQuery("(prefers-contrast: less)", options);
  const isCustom = useMediaQuery("(prefers-contrast: custom)", options);
  return computed(() => {
    if (isMore.value)
      return "more";
    if (isLess.value)
      return "less";
    if (isCustom.value)
      return "custom";
    return "no-preference";
  });
}
function usePreferredLanguages(options = {}) {
  const { window: window2 = defaultWindow } = options;
  if (!window2)
    return ref(["en"]);
  const navigator2 = window2.navigator;
  const value = ref(navigator2.languages);
  useEventListener(window2, "languagechange", () => {
    value.value = navigator2.languages;
  }, { passive: true });
  return value;
}
function usePreferredReducedMotion(options) {
  const isReduced = useMediaQuery("(prefers-reduced-motion: reduce)", options);
  return computed(() => {
    if (isReduced.value)
      return "reduce";
    return "no-preference";
  });
}
function usePreferredReducedTransparency(options) {
  const isReduced = useMediaQuery("(prefers-reduced-transparency: reduce)", options);
  return computed(() => {
    if (isReduced.value)
      return "reduce";
    return "no-preference";
  });
}
function usePrevious(value, initialValue) {
  const previous = shallowRef(initialValue);
  watch(
    toRef(value),
    (_, oldValue) => {
      previous.value = oldValue;
    },
    { flush: "sync" }
  );
  return readonly(previous);
}
const topVarName = "--vueuse-safe-area-top";
const rightVarName = "--vueuse-safe-area-right";
const bottomVarName = "--vueuse-safe-area-bottom";
const leftVarName = "--vueuse-safe-area-left";
function useScreenSafeArea() {
  const top = shallowRef("");
  const right = shallowRef("");
  const bottom = shallowRef("");
  const left = shallowRef("");
  if (isClient) {
    const topCssVar = useCssVar(topVarName);
    const rightCssVar = useCssVar(rightVarName);
    const bottomCssVar = useCssVar(bottomVarName);
    const leftCssVar = useCssVar(leftVarName);
    topCssVar.value = "env(safe-area-inset-top, 0px)";
    rightCssVar.value = "env(safe-area-inset-right, 0px)";
    bottomCssVar.value = "env(safe-area-inset-bottom, 0px)";
    leftCssVar.value = "env(safe-area-inset-left, 0px)";
    update();
    useEventListener("resize", useDebounceFn(update), { passive: true });
  }
  function update() {
    top.value = getValue(topVarName);
    right.value = getValue(rightVarName);
    bottom.value = getValue(bottomVarName);
    left.value = getValue(leftVarName);
  }
  return {
    top,
    right,
    bottom,
    left,
    update
  };
}
function getValue(position) {
  return getComputedStyle(document.documentElement).getPropertyValue(position);
}
function useScriptTag(src, onLoaded = noop$3, options = {}) {
  const {
    immediate = true,
    manual = false,
    type = "text/javascript",
    async = true,
    crossOrigin,
    referrerPolicy,
    noModule,
    defer,
    document: document2 = defaultDocument,
    attrs = {}
  } = options;
  const scriptTag = shallowRef(null);
  let _promise = null;
  const loadScript = (waitForScriptLoad) => new Promise((resolve, reject) => {
    const resolveWithElement = (el2) => {
      scriptTag.value = el2;
      resolve(el2);
      return el2;
    };
    if (!document2) {
      resolve(false);
      return;
    }
    let shouldAppend = false;
    let el = document2.querySelector(`script[src="${toValue$1(src)}"]`);
    if (!el) {
      el = document2.createElement("script");
      el.type = type;
      el.async = async;
      el.src = toValue$1(src);
      if (defer)
        el.defer = defer;
      if (crossOrigin)
        el.crossOrigin = crossOrigin;
      if (noModule)
        el.noModule = noModule;
      if (referrerPolicy)
        el.referrerPolicy = referrerPolicy;
      Object.entries(attrs).forEach(([name, value]) => el == null ? void 0 : el.setAttribute(name, value));
      shouldAppend = true;
    } else if (el.hasAttribute("data-loaded")) {
      resolveWithElement(el);
    }
    const listenerOptions = {
      passive: true
    };
    useEventListener(el, "error", (event) => reject(event), listenerOptions);
    useEventListener(el, "abort", (event) => reject(event), listenerOptions);
    useEventListener(el, "load", () => {
      el.setAttribute("data-loaded", "true");
      onLoaded(el);
      resolveWithElement(el);
    }, listenerOptions);
    if (shouldAppend)
      el = document2.head.appendChild(el);
    if (!waitForScriptLoad)
      resolveWithElement(el);
  });
  const load = (waitForScriptLoad = true) => {
    if (!_promise)
      _promise = loadScript(waitForScriptLoad);
    return _promise;
  };
  const unload = () => {
    if (!document2)
      return;
    _promise = null;
    if (scriptTag.value)
      scriptTag.value = null;
    const el = document2.querySelector(`script[src="${toValue$1(src)}"]`);
    if (el)
      document2.head.removeChild(el);
  };
  if (immediate && !manual)
    tryOnMounted(load);
  if (!manual)
    tryOnUnmounted(unload);
  return { scriptTag, load, unload };
}
function checkOverflowScroll(ele) {
  const style = window.getComputedStyle(ele);
  if (style.overflowX === "scroll" || style.overflowY === "scroll" || style.overflowX === "auto" && ele.clientWidth < ele.scrollWidth || style.overflowY === "auto" && ele.clientHeight < ele.scrollHeight) {
    return true;
  } else {
    const parent = ele.parentNode;
    if (!parent || parent.tagName === "BODY")
      return false;
    return checkOverflowScroll(parent);
  }
}
function preventDefault(rawEvent) {
  const e = rawEvent || window.event;
  const _target = e.target;
  if (checkOverflowScroll(_target))
    return false;
  if (e.touches.length > 1)
    return true;
  if (e.preventDefault)
    e.preventDefault();
  return false;
}
const elInitialOverflow = /* @__PURE__ */ new WeakMap();
function useScrollLock(element, initialState = false) {
  const isLocked = shallowRef(initialState);
  let stopTouchMoveListener = null;
  let initialOverflow = "";
  watch(toRef(element), (el) => {
    const target = resolveElement(toValue$1(el));
    if (target) {
      const ele = target;
      if (!elInitialOverflow.get(ele))
        elInitialOverflow.set(ele, ele.style.overflow);
      if (ele.style.overflow !== "hidden")
        initialOverflow = ele.style.overflow;
      if (ele.style.overflow === "hidden")
        return isLocked.value = true;
      if (isLocked.value)
        return ele.style.overflow = "hidden";
    }
  }, {
    immediate: true
  });
  const lock = () => {
    const el = resolveElement(toValue$1(element));
    if (!el || isLocked.value)
      return;
    if (isIOS) {
      stopTouchMoveListener = useEventListener(
        el,
        "touchmove",
        (e) => {
          preventDefault(e);
        },
        { passive: false }
      );
    }
    el.style.overflow = "hidden";
    isLocked.value = true;
  };
  const unlock = () => {
    const el = resolveElement(toValue$1(element));
    if (!el || !isLocked.value)
      return;
    if (isIOS)
      stopTouchMoveListener == null ? void 0 : stopTouchMoveListener();
    el.style.overflow = initialOverflow;
    elInitialOverflow.delete(el);
    isLocked.value = false;
  };
  tryOnScopeDispose(unlock);
  return computed({
    get() {
      return isLocked.value;
    },
    set(v) {
      if (v)
        lock();
      else unlock();
    }
  });
}
function useSessionStorage(key, initialValue, options = {}) {
  const { window: window2 = defaultWindow } = options;
  return useStorage(key, initialValue, window2 == null ? void 0 : window2.sessionStorage, options);
}
function useShare(shareOptions = {}, options = {}) {
  const { navigator: navigator2 = defaultNavigator } = options;
  const _navigator = navigator2;
  const isSupported = useSupported(() => _navigator && "canShare" in _navigator);
  const share = async (overrideOptions = {}) => {
    if (isSupported.value) {
      const data = {
        ...toValue$1(shareOptions),
        ...toValue$1(overrideOptions)
      };
      let granted = true;
      if (data.files && _navigator.canShare)
        granted = _navigator.canShare({ files: data.files });
      if (granted)
        return _navigator.share(data);
    }
  };
  return {
    isSupported,
    share
  };
}
const defaultSortFn = (source, compareFn) => source.sort(compareFn);
const defaultCompare = (a, b) => a - b;
function useSorted(...args) {
  var _a, _b, _c, _d;
  const [source] = args;
  let compareFn = defaultCompare;
  let options = {};
  if (args.length === 2) {
    if (typeof args[1] === "object") {
      options = args[1];
      compareFn = (_a = options.compareFn) != null ? _a : defaultCompare;
    } else {
      compareFn = (_b = args[1]) != null ? _b : defaultCompare;
    }
  } else if (args.length > 2) {
    compareFn = (_c = args[1]) != null ? _c : defaultCompare;
    options = (_d = args[2]) != null ? _d : {};
  }
  const {
    dirty = false,
    sortFn = defaultSortFn
  } = options;
  if (!dirty)
    return computed(() => sortFn([...toValue$1(source)], compareFn));
  watchEffect(() => {
    const result = sortFn(toValue$1(source), compareFn);
    if (isRef(source))
      source.value = result;
    else
      source.splice(0, source.length, ...result);
  });
  return source;
}
function useSpeechRecognition(options = {}) {
  const {
    interimResults = true,
    continuous = true,
    maxAlternatives = 1,
    window: window2 = defaultWindow
  } = options;
  const lang = toRef(options.lang || "en-US");
  const isListening = shallowRef(false);
  const isFinal = shallowRef(false);
  const result = shallowRef("");
  const error = shallowRef(void 0);
  let recognition;
  const start = () => {
    isListening.value = true;
  };
  const stop = () => {
    isListening.value = false;
  };
  const toggle = (value = !isListening.value) => {
    if (value) {
      start();
    } else {
      stop();
    }
  };
  const SpeechRecognition = window2 && (window2.SpeechRecognition || window2.webkitSpeechRecognition);
  const isSupported = useSupported(() => SpeechRecognition);
  if (isSupported.value) {
    recognition = new SpeechRecognition();
    recognition.continuous = continuous;
    recognition.interimResults = interimResults;
    recognition.lang = toValue$1(lang);
    recognition.maxAlternatives = maxAlternatives;
    recognition.onstart = () => {
      isListening.value = true;
      isFinal.value = false;
    };
    watch(lang, (lang2) => {
      if (recognition && !isListening.value)
        recognition.lang = lang2;
    });
    recognition.onresult = (event) => {
      const currentResult = event.results[event.resultIndex];
      const { transcript } = currentResult[0];
      isFinal.value = currentResult.isFinal;
      result.value = transcript;
      error.value = void 0;
    };
    recognition.onerror = (event) => {
      error.value = event;
    };
    recognition.onend = () => {
      isListening.value = false;
      recognition.lang = toValue$1(lang);
    };
    watch(isListening, (newValue, oldValue) => {
      if (newValue === oldValue)
        return;
      if (newValue)
        recognition.start();
      else
        recognition.stop();
    });
  }
  tryOnScopeDispose(() => {
    stop();
  });
  return {
    isSupported,
    isListening,
    isFinal,
    recognition,
    result,
    error,
    toggle,
    start,
    stop
  };
}
function useSpeechSynthesis(text, options = {}) {
  const {
    pitch = 1,
    rate = 1,
    volume = 1,
    window: window2 = defaultWindow
  } = options;
  const synth = window2 && window2.speechSynthesis;
  const isSupported = useSupported(() => synth);
  const isPlaying = shallowRef(false);
  const status = shallowRef("init");
  const spokenText = toRef(text || "");
  const lang = toRef(options.lang || "en-US");
  const error = shallowRef(void 0);
  const toggle = (value = !isPlaying.value) => {
    isPlaying.value = value;
  };
  const bindEventsForUtterance = (utterance2) => {
    utterance2.lang = toValue$1(lang);
    utterance2.voice = toValue$1(options.voice) || null;
    utterance2.pitch = toValue$1(pitch);
    utterance2.rate = toValue$1(rate);
    utterance2.volume = volume;
    utterance2.onstart = () => {
      isPlaying.value = true;
      status.value = "play";
    };
    utterance2.onpause = () => {
      isPlaying.value = false;
      status.value = "pause";
    };
    utterance2.onresume = () => {
      isPlaying.value = true;
      status.value = "play";
    };
    utterance2.onend = () => {
      isPlaying.value = false;
      status.value = "end";
    };
    utterance2.onerror = (event) => {
      error.value = event;
    };
  };
  const utterance = computed(() => {
    isPlaying.value = false;
    status.value = "init";
    const newUtterance = new SpeechSynthesisUtterance(spokenText.value);
    bindEventsForUtterance(newUtterance);
    return newUtterance;
  });
  const speak = () => {
    synth.cancel();
    if (utterance)
      synth.speak(utterance.value);
  };
  const stop = () => {
    synth.cancel();
    isPlaying.value = false;
  };
  if (isSupported.value) {
    bindEventsForUtterance(utterance.value);
    watch(lang, (lang2) => {
      if (utterance.value && !isPlaying.value)
        utterance.value.lang = lang2;
    });
    if (options.voice) {
      watch(options.voice, () => {
        synth.cancel();
      });
    }
    watch(isPlaying, () => {
      if (isPlaying.value)
        synth.resume();
      else
        synth.pause();
    });
  }
  tryOnScopeDispose(() => {
    isPlaying.value = false;
  });
  return {
    isSupported,
    isPlaying,
    status,
    utterance,
    error,
    stop,
    toggle,
    speak
  };
}
function useStepper(steps, initialStep) {
  const stepsRef = ref(steps);
  const stepNames = computed(() => Array.isArray(stepsRef.value) ? stepsRef.value : Object.keys(stepsRef.value));
  const index = ref(stepNames.value.indexOf(initialStep != null ? initialStep : stepNames.value[0]));
  const current = computed(() => at(index.value));
  const isFirst = computed(() => index.value === 0);
  const isLast = computed(() => index.value === stepNames.value.length - 1);
  const next = computed(() => stepNames.value[index.value + 1]);
  const previous = computed(() => stepNames.value[index.value - 1]);
  function at(index2) {
    if (Array.isArray(stepsRef.value))
      return stepsRef.value[index2];
    return stepsRef.value[stepNames.value[index2]];
  }
  function get(step) {
    if (!stepNames.value.includes(step))
      return;
    return at(stepNames.value.indexOf(step));
  }
  function goTo(step) {
    if (stepNames.value.includes(step))
      index.value = stepNames.value.indexOf(step);
  }
  function goToNext() {
    if (isLast.value)
      return;
    index.value++;
  }
  function goToPrevious() {
    if (isFirst.value)
      return;
    index.value--;
  }
  function goBackTo(step) {
    if (isAfter(step))
      goTo(step);
  }
  function isNext(step) {
    return stepNames.value.indexOf(step) === index.value + 1;
  }
  function isPrevious(step) {
    return stepNames.value.indexOf(step) === index.value - 1;
  }
  function isCurrent(step) {
    return stepNames.value.indexOf(step) === index.value;
  }
  function isBefore(step) {
    return index.value < stepNames.value.indexOf(step);
  }
  function isAfter(step) {
    return index.value > stepNames.value.indexOf(step);
  }
  return {
    steps: stepsRef,
    stepNames,
    index,
    current,
    next,
    previous,
    isFirst,
    isLast,
    at,
    get,
    goTo,
    goToNext,
    goToPrevious,
    goBackTo,
    isNext,
    isPrevious,
    isCurrent,
    isBefore,
    isAfter
  };
}
function useStorageAsync(key, initialValue, storage, options = {}) {
  var _a;
  const {
    flush = "pre",
    deep = true,
    listenToStorageChanges = true,
    writeDefaults = true,
    mergeDefaults = false,
    shallow,
    window: window2 = defaultWindow,
    eventFilter,
    onError = (e) => {
      console.error(e);
    }
  } = options;
  const rawInit = toValue$1(initialValue);
  const type = guessSerializerType(rawInit);
  const data = (shallow ? shallowRef : ref)(toValue$1(initialValue));
  const serializer = (_a = options.serializer) != null ? _a : StorageSerializers[type];
  if (!storage) {
    try {
      storage = getSSRHandler("getDefaultStorageAsync", () => {
        var _a2;
        return (_a2 = defaultWindow) == null ? void 0 : _a2.localStorage;
      })();
    } catch (e) {
      onError(e);
    }
  }
  async function read(event) {
    if (!storage || event && event.key !== key)
      return;
    try {
      const rawValue = event ? event.newValue : await storage.getItem(key);
      if (rawValue == null) {
        data.value = rawInit;
        if (writeDefaults && rawInit !== null)
          await storage.setItem(key, await serializer.write(rawInit));
      } else if (mergeDefaults) {
        const value = await serializer.read(rawValue);
        if (typeof mergeDefaults === "function")
          data.value = mergeDefaults(value, rawInit);
        else if (type === "object" && !Array.isArray(value))
          data.value = { ...rawInit, ...value };
        else data.value = value;
      } else {
        data.value = await serializer.read(rawValue);
      }
    } catch (e) {
      onError(e);
    }
  }
  read();
  if (window2 && listenToStorageChanges)
    useEventListener(window2, "storage", (e) => Promise.resolve().then(() => read(e)), { passive: true });
  if (storage) {
    watchWithFilter(
      data,
      async () => {
        try {
          if (data.value == null)
            await storage.removeItem(key);
          else
            await storage.setItem(key, await serializer.write(data.value));
        } catch (e) {
          onError(e);
        }
      },
      {
        flush,
        deep,
        eventFilter
      }
    );
  }
  return data;
}
let _id = 0;
function useStyleTag(css, options = {}) {
  const isLoaded = shallowRef(false);
  const {
    document: document2 = defaultDocument,
    immediate = true,
    manual = false,
    id = `vueuse_styletag_${++_id}`
  } = options;
  const cssRef = shallowRef(css);
  let stop = () => {
  };
  const load = () => {
    if (!document2)
      return;
    const el = document2.getElementById(id) || document2.createElement("style");
    if (!el.isConnected) {
      el.id = id;
      if (options.media)
        el.media = options.media;
      document2.head.appendChild(el);
    }
    if (isLoaded.value)
      return;
    stop = watch(
      cssRef,
      (value) => {
        el.textContent = value;
      },
      { immediate: true }
    );
    isLoaded.value = true;
  };
  const unload = () => {
    if (!document2 || !isLoaded.value)
      return;
    stop();
    document2.head.removeChild(document2.getElementById(id));
    isLoaded.value = false;
  };
  if (immediate && !manual)
    tryOnMounted(load);
  if (!manual)
    tryOnScopeDispose(unload);
  return {
    id,
    css: cssRef,
    unload,
    load,
    isLoaded: readonly(isLoaded)
  };
}
function useSwipe(target, options = {}) {
  const {
    threshold = 50,
    onSwipe,
    onSwipeEnd,
    onSwipeStart,
    passive = true
  } = options;
  const coordsStart = reactive({ x: 0, y: 0 });
  const coordsEnd = reactive({ x: 0, y: 0 });
  const diffX = computed(() => coordsStart.x - coordsEnd.x);
  const diffY = computed(() => coordsStart.y - coordsEnd.y);
  const { max, abs } = Math;
  const isThresholdExceeded = computed(() => max(abs(diffX.value), abs(diffY.value)) >= threshold);
  const isSwiping = shallowRef(false);
  const direction = computed(() => {
    if (!isThresholdExceeded.value)
      return "none";
    if (abs(diffX.value) > abs(diffY.value)) {
      return diffX.value > 0 ? "left" : "right";
    } else {
      return diffY.value > 0 ? "up" : "down";
    }
  });
  const getTouchEventCoords = (e) => [e.touches[0].clientX, e.touches[0].clientY];
  const updateCoordsStart = (x, y) => {
    coordsStart.x = x;
    coordsStart.y = y;
  };
  const updateCoordsEnd = (x, y) => {
    coordsEnd.x = x;
    coordsEnd.y = y;
  };
  const listenerOptions = { passive, capture: !passive };
  const onTouchEnd = (e) => {
    if (isSwiping.value)
      onSwipeEnd == null ? void 0 : onSwipeEnd(e, direction.value);
    isSwiping.value = false;
  };
  const stops = [
    useEventListener(target, "touchstart", (e) => {
      if (e.touches.length !== 1)
        return;
      const [x, y] = getTouchEventCoords(e);
      updateCoordsStart(x, y);
      updateCoordsEnd(x, y);
      onSwipeStart == null ? void 0 : onSwipeStart(e);
    }, listenerOptions),
    useEventListener(target, "touchmove", (e) => {
      if (e.touches.length !== 1)
        return;
      const [x, y] = getTouchEventCoords(e);
      updateCoordsEnd(x, y);
      if (listenerOptions.capture && !listenerOptions.passive && Math.abs(diffX.value) > Math.abs(diffY.value))
        e.preventDefault();
      if (!isSwiping.value && isThresholdExceeded.value)
        isSwiping.value = true;
      if (isSwiping.value)
        onSwipe == null ? void 0 : onSwipe(e);
    }, listenerOptions),
    useEventListener(target, ["touchend", "touchcancel"], onTouchEnd, listenerOptions)
  ];
  const stop = () => stops.forEach((s) => s());
  return {
    isSwiping,
    direction,
    coordsStart,
    coordsEnd,
    lengthX: diffX,
    lengthY: diffY,
    stop,
    // TODO: Remove in the next major version
    isPassiveEventSupported: true
  };
}
function useTemplateRefsList() {
  const refs = ref([]);
  refs.value.set = (el) => {
    if (el)
      refs.value.push(el);
  };
  onBeforeUpdate(() => {
    refs.value.length = 0;
  });
  return refs;
}
function useTextDirection(options = {}) {
  const {
    document: document2 = defaultDocument,
    selector = "html",
    observe = false,
    initialValue = "ltr"
  } = options;
  function getValue2() {
    var _a, _b;
    return (_b = (_a = document2 == null ? void 0 : document2.querySelector(selector)) == null ? void 0 : _a.getAttribute("dir")) != null ? _b : initialValue;
  }
  const dir = ref(getValue2());
  tryOnMounted(() => dir.value = getValue2());
  if (observe && document2) {
    useMutationObserver(
      document2.querySelector(selector),
      () => dir.value = getValue2(),
      { attributes: true }
    );
  }
  return computed({
    get() {
      return dir.value;
    },
    set(v) {
      var _a, _b;
      dir.value = v;
      if (!document2)
        return;
      if (dir.value)
        (_a = document2.querySelector(selector)) == null ? void 0 : _a.setAttribute("dir", dir.value);
      else
        (_b = document2.querySelector(selector)) == null ? void 0 : _b.removeAttribute("dir");
    }
  });
}
function getRangesFromSelection(selection) {
  var _a;
  const rangeCount = (_a = selection.rangeCount) != null ? _a : 0;
  return Array.from({ length: rangeCount }, (_, i) => selection.getRangeAt(i));
}
function useTextSelection(options = {}) {
  const {
    window: window2 = defaultWindow
  } = options;
  const selection = ref(null);
  const text = computed(() => {
    var _a, _b;
    return (_b = (_a = selection.value) == null ? void 0 : _a.toString()) != null ? _b : "";
  });
  const ranges = computed(() => selection.value ? getRangesFromSelection(selection.value) : []);
  const rects = computed(() => ranges.value.map((range) => range.getBoundingClientRect()));
  function onSelectionChange() {
    selection.value = null;
    if (window2)
      selection.value = window2.getSelection();
  }
  if (window2)
    useEventListener(window2.document, "selectionchange", onSelectionChange, { passive: true });
  return {
    text,
    rects,
    ranges,
    selection
  };
}
function tryRequestAnimationFrame(window2 = defaultWindow, fn) {
  if (window2 && typeof window2.requestAnimationFrame === "function") {
    window2.requestAnimationFrame(fn);
  } else {
    fn();
  }
}
function useTextareaAutosize(options = {}) {
  var _a, _b;
  const { window: window2 = defaultWindow } = options;
  const textarea = toRef(options == null ? void 0 : options.element);
  const input = toRef((_a = options == null ? void 0 : options.input) != null ? _a : "");
  const styleProp = (_b = options == null ? void 0 : options.styleProp) != null ? _b : "height";
  const textareaScrollHeight = shallowRef(1);
  const textareaOldWidth = shallowRef(0);
  function triggerResize() {
    var _a2;
    if (!textarea.value)
      return;
    let height = "";
    textarea.value.style[styleProp] = "1px";
    textareaScrollHeight.value = (_a2 = textarea.value) == null ? void 0 : _a2.scrollHeight;
    const _styleTarget = toValue$1(options == null ? void 0 : options.styleTarget);
    if (_styleTarget)
      _styleTarget.style[styleProp] = `${textareaScrollHeight.value}px`;
    else
      height = `${textareaScrollHeight.value}px`;
    textarea.value.style[styleProp] = height;
  }
  watch([input, textarea], () => nextTick(triggerResize), { immediate: true });
  watch(textareaScrollHeight, () => {
    var _a2;
    return (_a2 = options == null ? void 0 : options.onResize) == null ? void 0 : _a2.call(options);
  });
  useResizeObserver(textarea, ([{ contentRect }]) => {
    if (textareaOldWidth.value === contentRect.width)
      return;
    tryRequestAnimationFrame(window2, () => {
      textareaOldWidth.value = contentRect.width;
      triggerResize();
    });
  });
  if (options == null ? void 0 : options.watch)
    watch(options.watch, triggerResize, { immediate: true, deep: true });
  return {
    textarea,
    input,
    triggerResize
  };
}
function useThrottledRefHistory(source, options = {}) {
  const { throttle = 200, trailing = true } = options;
  const filter = throttleFilter(throttle, trailing);
  const history = useRefHistory(source, { ...options, eventFilter: filter });
  return {
    ...history
  };
}
const DEFAULT_UNITS = [
  { max: 6e4, value: 1e3, name: "second" },
  { max: 276e4, value: 6e4, name: "minute" },
  { max: 72e6, value: 36e5, name: "hour" },
  { max: 5184e5, value: 864e5, name: "day" },
  { max: 24192e5, value: 6048e5, name: "week" },
  { max: 28512e6, value: 2592e6, name: "month" },
  { max: Number.POSITIVE_INFINITY, value: 31536e6, name: "year" }
];
const DEFAULT_MESSAGES = {
  justNow: "just now",
  past: (n) => n.match(/\d/) ? `${n} ago` : n,
  future: (n) => n.match(/\d/) ? `in ${n}` : n,
  month: (n, past) => n === 1 ? past ? "last month" : "next month" : `${n} month${n > 1 ? "s" : ""}`,
  year: (n, past) => n === 1 ? past ? "last year" : "next year" : `${n} year${n > 1 ? "s" : ""}`,
  day: (n, past) => n === 1 ? past ? "yesterday" : "tomorrow" : `${n} day${n > 1 ? "s" : ""}`,
  week: (n, past) => n === 1 ? past ? "last week" : "next week" : `${n} week${n > 1 ? "s" : ""}`,
  hour: (n) => `${n} hour${n > 1 ? "s" : ""}`,
  minute: (n) => `${n} minute${n > 1 ? "s" : ""}`,
  second: (n) => `${n} second${n > 1 ? "s" : ""}`,
  invalid: ""
};
function DEFAULT_FORMATTER(date) {
  return date.toISOString().slice(0, 10);
}
function useTimeAgo(time, options = {}) {
  const {
    controls: exposeControls = false,
    updateInterval = 3e4
  } = options;
  const { now, ...controls } = useNow({ interval: updateInterval, controls: true });
  const timeAgo = computed(() => formatTimeAgo(new Date(toValue$1(time)), options, toValue$1(now)));
  if (exposeControls) {
    return {
      timeAgo,
      ...controls
    };
  } else {
    return timeAgo;
  }
}
function formatTimeAgo(from, options = {}, now = Date.now()) {
  var _a;
  const {
    max,
    messages = DEFAULT_MESSAGES,
    fullDateFormatter = DEFAULT_FORMATTER,
    units = DEFAULT_UNITS,
    showSecond = false,
    rounding = "round"
  } = options;
  const roundFn = typeof rounding === "number" ? (n) => +n.toFixed(rounding) : Math[rounding];
  const diff = +now - +from;
  const absDiff = Math.abs(diff);
  function getValue2(diff2, unit) {
    return roundFn(Math.abs(diff2) / unit.value);
  }
  function format(diff2, unit) {
    const val = getValue2(diff2, unit);
    const past = diff2 > 0;
    const str = applyFormat(unit.name, val, past);
    return applyFormat(past ? "past" : "future", str, past);
  }
  function applyFormat(name, val, isPast) {
    const formatter = messages[name];
    if (typeof formatter === "function")
      return formatter(val, isPast);
    return formatter.replace("{0}", val.toString());
  }
  if (absDiff < 6e4 && !showSecond)
    return messages.justNow;
  if (typeof max === "number" && absDiff > max)
    return fullDateFormatter(new Date(from));
  if (typeof max === "string") {
    const unitMax = (_a = units.find((i) => i.name === max)) == null ? void 0 : _a.max;
    if (unitMax && absDiff > unitMax)
      return fullDateFormatter(new Date(from));
  }
  for (const [idx, unit] of units.entries()) {
    const val = getValue2(diff, unit);
    if (val <= 0 && units[idx - 1])
      return format(diff, units[idx - 1]);
    if (absDiff < unit.max)
      return format(diff, unit);
  }
  return messages.invalid;
}
function useTimeoutPoll(fn, interval, options = {}) {
  const {
    immediate = true,
    immediateCallback = false
  } = options;
  const { start } = useTimeoutFn(loop, interval, { immediate });
  const isActive = shallowRef(false);
  async function loop() {
    if (!isActive.value)
      return;
    await fn();
    start();
  }
  function resume() {
    if (!isActive.value) {
      isActive.value = true;
      if (immediateCallback)
        fn();
      start();
    }
  }
  function pause() {
    isActive.value = false;
  }
  if (immediate && isClient)
    resume();
  tryOnScopeDispose(pause);
  return {
    isActive,
    pause,
    resume
  };
}
function useTimestamp(options = {}) {
  const {
    controls: exposeControls = false,
    offset = 0,
    immediate = true,
    interval = "requestAnimationFrame",
    callback
  } = options;
  const ts = shallowRef(timestamp() + offset);
  const update = () => ts.value = timestamp() + offset;
  const cb = callback ? () => {
    update();
    callback(ts.value);
  } : update;
  const controls = interval === "requestAnimationFrame" ? useRafFn(cb, { immediate }) : useIntervalFn(cb, interval, { immediate });
  if (exposeControls) {
    return {
      timestamp: ts,
      ...controls
    };
  } else {
    return ts;
  }
}
function useTitle(newTitle = null, options = {}) {
  var _a, _b, _c;
  const {
    document: document2 = defaultDocument,
    restoreOnUnmount = (t) => t
  } = options;
  const originalTitle = (_a = document2 == null ? void 0 : document2.title) != null ? _a : "";
  const title = toRef((_b = newTitle != null ? newTitle : document2 == null ? void 0 : document2.title) != null ? _b : null);
  const isReadonly2 = !!(newTitle && typeof newTitle === "function");
  function format(t) {
    if (!("titleTemplate" in options))
      return t;
    const template = options.titleTemplate || "%s";
    return typeof template === "function" ? template(t) : toValue$1(template).replace(/%s/g, t);
  }
  watch(
    title,
    (newValue, oldValue) => {
      if (newValue !== oldValue && document2)
        document2.title = format(newValue != null ? newValue : "");
    },
    { immediate: true }
  );
  if (options.observe && !options.titleTemplate && document2 && !isReadonly2) {
    useMutationObserver(
      (_c = document2.head) == null ? void 0 : _c.querySelector("title"),
      () => {
        if (document2 && document2.title !== title.value)
          title.value = format(document2.title);
      },
      { childList: true }
    );
  }
  tryOnScopeDispose(() => {
    if (restoreOnUnmount) {
      const restoredTitle = restoreOnUnmount(originalTitle, title.value || "");
      if (restoredTitle != null && document2)
        document2.title = restoredTitle;
    }
  });
  return title;
}
const _TransitionPresets = {
  easeInSine: [0.12, 0, 0.39, 0],
  easeOutSine: [0.61, 1, 0.88, 1],
  easeInOutSine: [0.37, 0, 0.63, 1],
  easeInQuad: [0.11, 0, 0.5, 0],
  easeOutQuad: [0.5, 1, 0.89, 1],
  easeInOutQuad: [0.45, 0, 0.55, 1],
  easeInCubic: [0.32, 0, 0.67, 0],
  easeOutCubic: [0.33, 1, 0.68, 1],
  easeInOutCubic: [0.65, 0, 0.35, 1],
  easeInQuart: [0.5, 0, 0.75, 0],
  easeOutQuart: [0.25, 1, 0.5, 1],
  easeInOutQuart: [0.76, 0, 0.24, 1],
  easeInQuint: [0.64, 0, 0.78, 0],
  easeOutQuint: [0.22, 1, 0.36, 1],
  easeInOutQuint: [0.83, 0, 0.17, 1],
  easeInExpo: [0.7, 0, 0.84, 0],
  easeOutExpo: [0.16, 1, 0.3, 1],
  easeInOutExpo: [0.87, 0, 0.13, 1],
  easeInCirc: [0.55, 0, 1, 0.45],
  easeOutCirc: [0, 0.55, 0.45, 1],
  easeInOutCirc: [0.85, 0, 0.15, 1],
  easeInBack: [0.36, 0, 0.66, -0.56],
  easeOutBack: [0.34, 1.56, 0.64, 1],
  easeInOutBack: [0.68, -0.6, 0.32, 1.6]
};
const TransitionPresets = /* @__PURE__ */ Object.assign({}, { linear: identity }, _TransitionPresets);
function createEasingFunction([p0, p1, p2, p3]) {
  const a = (a1, a2) => 1 - 3 * a2 + 3 * a1;
  const b = (a1, a2) => 3 * a2 - 6 * a1;
  const c = (a1) => 3 * a1;
  const calcBezier = (t, a1, a2) => ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t;
  const getSlope = (t, a1, a2) => 3 * a(a1, a2) * t * t + 2 * b(a1, a2) * t + c(a1);
  const getTforX = (x) => {
    let aGuessT = x;
    for (let i = 0; i < 4; ++i) {
      const currentSlope = getSlope(aGuessT, p0, p2);
      if (currentSlope === 0)
        return aGuessT;
      const currentX = calcBezier(aGuessT, p0, p2) - x;
      aGuessT -= currentX / currentSlope;
    }
    return aGuessT;
  };
  return (x) => p0 === p1 && p2 === p3 ? x : calcBezier(getTforX(x), p1, p3);
}
function lerp(a, b, alpha) {
  return a + alpha * (b - a);
}
function toVec(t) {
  return (typeof t === "number" ? [t] : t) || [];
}
function executeTransition(source, from, to, options = {}) {
  var _a, _b;
  const fromVal = toValue$1(from);
  const toVal = toValue$1(to);
  const v1 = toVec(fromVal);
  const v2 = toVec(toVal);
  const duration = (_a = toValue$1(options.duration)) != null ? _a : 1e3;
  const startedAt = Date.now();
  const endAt = Date.now() + duration;
  const trans = typeof options.transition === "function" ? options.transition : (_b = toValue$1(options.transition)) != null ? _b : identity;
  const ease = typeof trans === "function" ? trans : createEasingFunction(trans);
  return new Promise((resolve) => {
    source.value = fromVal;
    const tick = () => {
      var _a2;
      if ((_a2 = options.abort) == null ? void 0 : _a2.call(options)) {
        resolve();
        return;
      }
      const now = Date.now();
      const alpha = ease((now - startedAt) / duration);
      const arr = toVec(source.value).map((n, i) => lerp(v1[i], v2[i], alpha));
      if (Array.isArray(source.value))
        source.value = arr.map((n, i) => {
          var _a3, _b2;
          return lerp((_a3 = v1[i]) != null ? _a3 : 0, (_b2 = v2[i]) != null ? _b2 : 0, alpha);
        });
      else if (typeof source.value === "number")
        source.value = arr[0];
      if (now < endAt) {
        requestAnimationFrame(tick);
      } else {
        source.value = toVal;
        resolve();
      }
    };
    tick();
  });
}
function useTransition(source, options = {}) {
  let currentId = 0;
  const sourceVal = () => {
    const v = toValue$1(source);
    return typeof v === "number" ? v : v.map(toValue$1);
  };
  const outputRef = ref(sourceVal());
  watch(sourceVal, async (to) => {
    var _a, _b;
    if (toValue$1(options.disabled))
      return;
    const id = ++currentId;
    if (options.delay)
      await promiseTimeout(toValue$1(options.delay));
    if (id !== currentId)
      return;
    const toVal = Array.isArray(to) ? to.map(toValue$1) : toValue$1(to);
    (_a = options.onStarted) == null ? void 0 : _a.call(options);
    await executeTransition(outputRef, outputRef.value, toVal, {
      ...options,
      abort: () => {
        var _a2;
        return id !== currentId || ((_a2 = options.abort) == null ? void 0 : _a2.call(options));
      }
    });
    (_b = options.onFinished) == null ? void 0 : _b.call(options);
  }, { deep: true });
  watch(() => toValue$1(options.disabled), (disabled) => {
    if (disabled) {
      currentId++;
      outputRef.value = sourceVal();
    }
  });
  tryOnScopeDispose(() => {
    currentId++;
  });
  return computed(() => toValue$1(options.disabled) ? sourceVal() : outputRef.value);
}
function useUrlSearchParams(mode = "history", options = {}) {
  const {
    initialValue = {},
    removeNullishValues = true,
    removeFalsyValues = false,
    write: enableWrite = true,
    writeMode = "replace",
    window: window2 = defaultWindow
  } = options;
  if (!window2)
    return reactive(initialValue);
  const state = reactive({});
  function getRawParams() {
    if (mode === "history") {
      return window2.location.search || "";
    } else if (mode === "hash") {
      const hash = window2.location.hash || "";
      const index = hash.indexOf("?");
      return index > 0 ? hash.slice(index) : "";
    } else {
      return (window2.location.hash || "").replace(/^#/, "");
    }
  }
  function constructQuery(params) {
    const stringified = params.toString();
    if (mode === "history")
      return `${stringified ? `?${stringified}` : ""}${window2.location.hash || ""}`;
    if (mode === "hash-params")
      return `${window2.location.search || ""}${stringified ? `#${stringified}` : ""}`;
    const hash = window2.location.hash || "#";
    const index = hash.indexOf("?");
    if (index > 0)
      return `${window2.location.search || ""}${hash.slice(0, index)}${stringified ? `?${stringified}` : ""}`;
    return `${window2.location.search || ""}${hash}${stringified ? `?${stringified}` : ""}`;
  }
  function read() {
    return new URLSearchParams(getRawParams());
  }
  function updateState(params) {
    const unusedKeys = new Set(Object.keys(state));
    for (const key of params.keys()) {
      const paramsForKey = params.getAll(key);
      state[key] = paramsForKey.length > 1 ? paramsForKey : params.get(key) || "";
      unusedKeys.delete(key);
    }
    Array.from(unusedKeys).forEach((key) => delete state[key]);
  }
  const { pause, resume } = watchPausable(
    state,
    () => {
      const params = new URLSearchParams("");
      Object.keys(state).forEach((key) => {
        const mapEntry = state[key];
        if (Array.isArray(mapEntry))
          mapEntry.forEach((value) => params.append(key, value));
        else if (removeNullishValues && mapEntry == null)
          params.delete(key);
        else if (removeFalsyValues && !mapEntry)
          params.delete(key);
        else
          params.set(key, mapEntry);
      });
      write(params, false);
    },
    { deep: true }
  );
  function write(params, shouldUpdate) {
    pause();
    if (shouldUpdate)
      updateState(params);
    if (writeMode === "replace") {
      window2.history.replaceState(
        window2.history.state,
        window2.document.title,
        window2.location.pathname + constructQuery(params)
      );
    } else {
      window2.history.pushState(
        window2.history.state,
        window2.document.title,
        window2.location.pathname + constructQuery(params)
      );
    }
    resume();
  }
  function onChanged() {
    if (!enableWrite)
      return;
    write(read(), true);
  }
  const listenerOptions = { passive: true };
  useEventListener(window2, "popstate", onChanged, listenerOptions);
  if (mode !== "history")
    useEventListener(window2, "hashchange", onChanged, listenerOptions);
  const initial = read();
  if (initial.keys().next().value)
    updateState(initial);
  else
    Object.assign(state, initialValue);
  return state;
}
function useUserMedia(options = {}) {
  var _a, _b;
  const enabled = shallowRef((_a = options.enabled) != null ? _a : false);
  const autoSwitch = shallowRef((_b = options.autoSwitch) != null ? _b : true);
  const constraints = ref(options.constraints);
  const { navigator: navigator2 = defaultNavigator } = options;
  const isSupported = useSupported(() => {
    var _a2;
    return (_a2 = navigator2 == null ? void 0 : navigator2.mediaDevices) == null ? void 0 : _a2.getUserMedia;
  });
  const stream = shallowRef();
  function getDeviceOptions(type) {
    switch (type) {
      case "video": {
        if (constraints.value)
          return constraints.value.video || false;
        break;
      }
      case "audio": {
        if (constraints.value)
          return constraints.value.audio || false;
        break;
      }
    }
  }
  async function _start() {
    if (!isSupported.value || stream.value)
      return;
    stream.value = await navigator2.mediaDevices.getUserMedia({
      video: getDeviceOptions("video"),
      audio: getDeviceOptions("audio")
    });
    return stream.value;
  }
  function _stop() {
    var _a2;
    (_a2 = stream.value) == null ? void 0 : _a2.getTracks().forEach((t) => t.stop());
    stream.value = void 0;
  }
  function stop() {
    _stop();
    enabled.value = false;
  }
  async function start() {
    await _start();
    if (stream.value)
      enabled.value = true;
    return stream.value;
  }
  async function restart() {
    _stop();
    return await start();
  }
  watch(
    enabled,
    (v) => {
      if (v)
        _start();
      else _stop();
    },
    { immediate: true }
  );
  watch(
    constraints,
    () => {
      if (autoSwitch.value && stream.value)
        restart();
    },
    { immediate: true }
  );
  tryOnScopeDispose(() => {
    stop();
  });
  return {
    isSupported,
    stream,
    start,
    stop,
    restart,
    constraints,
    enabled,
    autoSwitch
  };
}
function useVModel(props, key, emit, options = {}) {
  var _a, _b, _c;
  const {
    clone = false,
    passive = false,
    eventName,
    deep = false,
    defaultValue,
    shouldEmit
  } = options;
  const vm = getCurrentInstance();
  const _emit = emit || (vm == null ? void 0 : vm.emit) || ((_a = vm == null ? void 0 : vm.$emit) == null ? void 0 : _a.bind(vm)) || ((_c = (_b = vm == null ? void 0 : vm.proxy) == null ? void 0 : _b.$emit) == null ? void 0 : _c.bind(vm == null ? void 0 : vm.proxy));
  let event = eventName;
  if (!key) {
    key = "modelValue";
  }
  event = event || `update:${key.toString()}`;
  const cloneFn = (val) => !clone ? val : typeof clone === "function" ? clone(val) : cloneFnJSON(val);
  const getValue2 = () => isDef(props[key]) ? cloneFn(props[key]) : defaultValue;
  const triggerEmit = (value) => {
    if (shouldEmit) {
      if (shouldEmit(value))
        _emit(event, value);
    } else {
      _emit(event, value);
    }
  };
  if (passive) {
    const initialValue = getValue2();
    const proxy = ref(initialValue);
    let isUpdating = false;
    watch(
      () => props[key],
      (v) => {
        if (!isUpdating) {
          isUpdating = true;
          proxy.value = cloneFn(v);
          nextTick(() => isUpdating = false);
        }
      }
    );
    watch(
      proxy,
      (v) => {
        if (!isUpdating && (v !== props[key] || deep))
          triggerEmit(v);
      },
      { deep }
    );
    return proxy;
  } else {
    return computed({
      get() {
        return getValue2();
      },
      set(value) {
        triggerEmit(value);
      }
    });
  }
}
function useVModels(props, emit, options = {}) {
  const ret = {};
  for (const key in props) {
    ret[key] = useVModel(
      props,
      key,
      emit,
      options
    );
  }
  return ret;
}
function useVibrate(options) {
  const {
    pattern = [],
    interval = 0,
    navigator: navigator2 = defaultNavigator
  } = options || {};
  const isSupported = useSupported(() => typeof navigator2 !== "undefined" && "vibrate" in navigator2);
  const patternRef = toRef(pattern);
  let intervalControls;
  const vibrate = (pattern2 = patternRef.value) => {
    if (isSupported.value)
      navigator2.vibrate(pattern2);
  };
  const stop = () => {
    if (isSupported.value)
      navigator2.vibrate(0);
    intervalControls == null ? void 0 : intervalControls.pause();
  };
  if (interval > 0) {
    intervalControls = useIntervalFn(
      vibrate,
      interval,
      {
        immediate: false,
        immediateCallback: false
      }
    );
  }
  return {
    isSupported,
    pattern,
    intervalControls,
    vibrate,
    stop
  };
}
function useVirtualList(list, options) {
  const { containerStyle, wrapperProps, scrollTo, calculateRange, currentList, containerRef } = "itemHeight" in options ? useVerticalVirtualList(options, list) : useHorizontalVirtualList(options, list);
  return {
    list: currentList,
    scrollTo,
    containerProps: {
      ref: containerRef,
      onScroll: () => {
        calculateRange();
      },
      style: containerStyle
    },
    wrapperProps
  };
}
function useVirtualListResources(list) {
  const containerRef = shallowRef(null);
  const size = useElementSize(containerRef);
  const currentList = ref([]);
  const source = shallowRef(list);
  const state = ref({ start: 0, end: 10 });
  return { state, source, currentList, size, containerRef };
}
function createGetViewCapacity(state, source, itemSize) {
  return (containerSize) => {
    if (typeof itemSize === "number")
      return Math.ceil(containerSize / itemSize);
    const { start = 0 } = state.value;
    let sum = 0;
    let capacity = 0;
    for (let i = start; i < source.value.length; i++) {
      const size = itemSize(i);
      sum += size;
      capacity = i;
      if (sum > containerSize)
        break;
    }
    return capacity - start;
  };
}
function createGetOffset(source, itemSize) {
  return (scrollDirection) => {
    if (typeof itemSize === "number")
      return Math.floor(scrollDirection / itemSize) + 1;
    let sum = 0;
    let offset = 0;
    for (let i = 0; i < source.value.length; i++) {
      const size = itemSize(i);
      sum += size;
      if (sum >= scrollDirection) {
        offset = i;
        break;
      }
    }
    return offset + 1;
  };
}
function createCalculateRange(type, overscan, getOffset, getViewCapacity, { containerRef, state, currentList, source }) {
  return () => {
    const element = containerRef.value;
    if (element) {
      const offset = getOffset(type === "vertical" ? element.scrollTop : element.scrollLeft);
      const viewCapacity = getViewCapacity(type === "vertical" ? element.clientHeight : element.clientWidth);
      const from = offset - overscan;
      const to = offset + viewCapacity + overscan;
      state.value = {
        start: from < 0 ? 0 : from,
        end: to > source.value.length ? source.value.length : to
      };
      currentList.value = source.value.slice(state.value.start, state.value.end).map((ele, index) => ({
        data: ele,
        index: index + state.value.start
      }));
    }
  };
}
function createGetDistance(itemSize, source) {
  return (index) => {
    if (typeof itemSize === "number") {
      const size2 = index * itemSize;
      return size2;
    }
    const size = source.value.slice(0, index).reduce((sum, _, i) => sum + itemSize(i), 0);
    return size;
  };
}
function useWatchForSizes(size, list, containerRef, calculateRange) {
  watch([size.width, size.height, list, containerRef], () => {
    calculateRange();
  });
}
function createComputedTotalSize(itemSize, source) {
  return computed(() => {
    if (typeof itemSize === "number")
      return source.value.length * itemSize;
    return source.value.reduce((sum, _, index) => sum + itemSize(index), 0);
  });
}
const scrollToDictionaryForElementScrollKey = {
  horizontal: "scrollLeft",
  vertical: "scrollTop"
};
function createScrollTo(type, calculateRange, getDistance, containerRef) {
  return (index) => {
    if (containerRef.value) {
      containerRef.value[scrollToDictionaryForElementScrollKey[type]] = getDistance(index);
      calculateRange();
    }
  };
}
function useHorizontalVirtualList(options, list) {
  const resources = useVirtualListResources(list);
  const { state, source, currentList, size, containerRef } = resources;
  const containerStyle = { overflowX: "auto" };
  const { itemWidth, overscan = 5 } = options;
  const getViewCapacity = createGetViewCapacity(state, source, itemWidth);
  const getOffset = createGetOffset(source, itemWidth);
  const calculateRange = createCalculateRange("horizontal", overscan, getOffset, getViewCapacity, resources);
  const getDistanceLeft = createGetDistance(itemWidth, source);
  const offsetLeft = computed(() => getDistanceLeft(state.value.start));
  const totalWidth = createComputedTotalSize(itemWidth, source);
  useWatchForSizes(size, list, containerRef, calculateRange);
  const scrollTo = createScrollTo("horizontal", calculateRange, getDistanceLeft, containerRef);
  const wrapperProps = computed(() => {
    return {
      style: {
        height: "100%",
        width: `${totalWidth.value - offsetLeft.value}px`,
        marginLeft: `${offsetLeft.value}px`,
        display: "flex"
      }
    };
  });
  return {
    scrollTo,
    calculateRange,
    wrapperProps,
    containerStyle,
    currentList,
    containerRef
  };
}
function useVerticalVirtualList(options, list) {
  const resources = useVirtualListResources(list);
  const { state, source, currentList, size, containerRef } = resources;
  const containerStyle = { overflowY: "auto" };
  const { itemHeight, overscan = 5 } = options;
  const getViewCapacity = createGetViewCapacity(state, source, itemHeight);
  const getOffset = createGetOffset(source, itemHeight);
  const calculateRange = createCalculateRange("vertical", overscan, getOffset, getViewCapacity, resources);
  const getDistanceTop = createGetDistance(itemHeight, source);
  const offsetTop = computed(() => getDistanceTop(state.value.start));
  const totalHeight = createComputedTotalSize(itemHeight, source);
  useWatchForSizes(size, list, containerRef, calculateRange);
  const scrollTo = createScrollTo("vertical", calculateRange, getDistanceTop, containerRef);
  const wrapperProps = computed(() => {
    return {
      style: {
        width: "100%",
        height: `${totalHeight.value - offsetTop.value}px`,
        marginTop: `${offsetTop.value}px`
      }
    };
  });
  return {
    calculateRange,
    scrollTo,
    containerStyle,
    wrapperProps,
    currentList,
    containerRef
  };
}
function useWakeLock(options = {}) {
  const {
    navigator: navigator2 = defaultNavigator,
    document: document2 = defaultDocument
  } = options;
  const requestedType = shallowRef(false);
  const sentinel = shallowRef(null);
  const documentVisibility = useDocumentVisibility({ document: document2 });
  const isSupported = useSupported(() => navigator2 && "wakeLock" in navigator2);
  const isActive = computed(() => !!sentinel.value && documentVisibility.value === "visible");
  if (isSupported.value) {
    useEventListener(sentinel, "release", () => {
      var _a, _b;
      requestedType.value = (_b = (_a = sentinel.value) == null ? void 0 : _a.type) != null ? _b : false;
    }, { passive: true });
    whenever(
      () => documentVisibility.value === "visible" && (document2 == null ? void 0 : document2.visibilityState) === "visible" && requestedType.value,
      (type) => {
        requestedType.value = false;
        forceRequest(type);
      }
    );
  }
  async function forceRequest(type) {
    var _a;
    await ((_a = sentinel.value) == null ? void 0 : _a.release());
    sentinel.value = isSupported.value ? await navigator2.wakeLock.request(type) : null;
  }
  async function request(type) {
    if (documentVisibility.value === "visible")
      await forceRequest(type);
    else
      requestedType.value = type;
  }
  async function release() {
    requestedType.value = false;
    const s = sentinel.value;
    sentinel.value = null;
    await (s == null ? void 0 : s.release());
  }
  return {
    sentinel,
    isSupported,
    isActive,
    request,
    forceRequest,
    release
  };
}
function useWebNotification(options = {}) {
  const {
    window: window2 = defaultWindow,
    requestPermissions: _requestForPermissions = true
  } = options;
  const defaultWebNotificationOptions = options;
  const isSupported = useSupported(() => {
    if (!window2 || !("Notification" in window2))
      return false;
    if (Notification.permission === "granted")
      return true;
    try {
      const notification2 = new Notification("");
      notification2.onshow = () => {
        notification2.close();
      };
    } catch (e) {
      if (e.name === "TypeError")
        return false;
    }
    return true;
  });
  const permissionGranted = shallowRef(isSupported.value && "permission" in Notification && Notification.permission === "granted");
  const notification = ref(null);
  const ensurePermissions = async () => {
    if (!isSupported.value)
      return;
    if (!permissionGranted.value && Notification.permission !== "denied") {
      const result = await Notification.requestPermission();
      if (result === "granted")
        permissionGranted.value = true;
    }
    return permissionGranted.value;
  };
  const { on: onClick, trigger: clickTrigger } = createEventHook();
  const { on: onShow, trigger: showTrigger } = createEventHook();
  const { on: onError, trigger: errorTrigger } = createEventHook();
  const { on: onClose, trigger: closeTrigger } = createEventHook();
  const show = async (overrides) => {
    if (!isSupported.value || !permissionGranted.value)
      return;
    const options2 = Object.assign({}, defaultWebNotificationOptions, overrides);
    notification.value = new Notification(options2.title || "", options2);
    notification.value.onclick = clickTrigger;
    notification.value.onshow = showTrigger;
    notification.value.onerror = errorTrigger;
    notification.value.onclose = closeTrigger;
    return notification.value;
  };
  const close = () => {
    if (notification.value)
      notification.value.close();
    notification.value = null;
  };
  if (_requestForPermissions)
    tryOnMounted(ensurePermissions);
  tryOnScopeDispose(close);
  if (isSupported.value && window2) {
    const document2 = window2.document;
    useEventListener(document2, "visibilitychange", (e) => {
      e.preventDefault();
      if (document2.visibilityState === "visible") {
        close();
      }
    });
  }
  return {
    isSupported,
    notification,
    ensurePermissions,
    permissionGranted,
    show,
    close,
    onClick,
    onShow,
    onError,
    onClose
  };
}
const DEFAULT_PING_MESSAGE = "ping";
function resolveNestedOptions(options) {
  if (options === true)
    return {};
  return options;
}
function useWebSocket(url, options = {}) {
  const {
    onConnected,
    onDisconnected,
    onError,
    onMessage,
    immediate = true,
    autoConnect = true,
    autoClose = true,
    protocols = []
  } = options;
  const data = ref(null);
  const status = shallowRef("CLOSED");
  const wsRef = ref();
  const urlRef = toRef(url);
  let heartbeatPause;
  let heartbeatResume;
  let explicitlyClosed = false;
  let retried = 0;
  let bufferedData = [];
  let retryTimeout;
  let pongTimeoutWait;
  const _sendBuffer = () => {
    if (bufferedData.length && wsRef.value && status.value === "OPEN") {
      for (const buffer of bufferedData)
        wsRef.value.send(buffer);
      bufferedData = [];
    }
  };
  const resetRetry = () => {
    if (retryTimeout != null) {
      clearTimeout(retryTimeout);
      retryTimeout = void 0;
    }
  };
  const resetHeartbeat = () => {
    clearTimeout(pongTimeoutWait);
    pongTimeoutWait = void 0;
  };
  const close = (code = 1e3, reason) => {
    resetRetry();
    if (!isClient && !isWorker || !wsRef.value)
      return;
    explicitlyClosed = true;
    resetHeartbeat();
    heartbeatPause == null ? void 0 : heartbeatPause();
    wsRef.value.close(code, reason);
    wsRef.value = void 0;
  };
  const send = (data2, useBuffer = true) => {
    if (!wsRef.value || status.value !== "OPEN") {
      if (useBuffer)
        bufferedData.push(data2);
      return false;
    }
    _sendBuffer();
    wsRef.value.send(data2);
    return true;
  };
  const _init = () => {
    if (explicitlyClosed || typeof urlRef.value === "undefined")
      return;
    const ws = new WebSocket(urlRef.value, protocols);
    wsRef.value = ws;
    status.value = "CONNECTING";
    ws.onopen = () => {
      status.value = "OPEN";
      retried = 0;
      onConnected == null ? void 0 : onConnected(ws);
      heartbeatResume == null ? void 0 : heartbeatResume();
      _sendBuffer();
    };
    ws.onclose = (ev) => {
      status.value = "CLOSED";
      resetHeartbeat();
      heartbeatPause == null ? void 0 : heartbeatPause();
      onDisconnected == null ? void 0 : onDisconnected(ws, ev);
      if (!explicitlyClosed && options.autoReconnect && (wsRef.value == null || ws === wsRef.value)) {
        const {
          retries = -1,
          delay = 1e3,
          onFailed
        } = resolveNestedOptions(options.autoReconnect);
        const checkRetires = typeof retries === "function" ? retries : () => typeof retries === "number" && (retries < 0 || retried < retries);
        if (checkRetires(retried)) {
          retried += 1;
          retryTimeout = setTimeout(_init, delay);
        } else {
          onFailed == null ? void 0 : onFailed();
        }
      }
    };
    ws.onerror = (e) => {
      onError == null ? void 0 : onError(ws, e);
    };
    ws.onmessage = (e) => {
      if (options.heartbeat) {
        resetHeartbeat();
        const {
          message = DEFAULT_PING_MESSAGE,
          responseMessage = message
        } = resolveNestedOptions(options.heartbeat);
        if (e.data === toValue$1(responseMessage))
          return;
      }
      data.value = e.data;
      onMessage == null ? void 0 : onMessage(ws, e);
    };
  };
  if (options.heartbeat) {
    const {
      message = DEFAULT_PING_MESSAGE,
      interval = 1e3,
      pongTimeout = 1e3
    } = resolveNestedOptions(options.heartbeat);
    const { pause, resume } = useIntervalFn(
      () => {
        send(toValue$1(message), false);
        if (pongTimeoutWait != null)
          return;
        pongTimeoutWait = setTimeout(() => {
          close();
          explicitlyClosed = false;
        }, pongTimeout);
      },
      interval,
      { immediate: false }
    );
    heartbeatPause = pause;
    heartbeatResume = resume;
  }
  if (autoClose) {
    if (isClient)
      useEventListener("beforeunload", () => close(), { passive: true });
    tryOnScopeDispose(close);
  }
  const open = () => {
    if (!isClient && !isWorker)
      return;
    close();
    explicitlyClosed = false;
    retried = 0;
    _init();
  };
  if (immediate)
    open();
  if (autoConnect)
    watch(urlRef, open);
  return {
    data,
    status,
    close,
    send,
    open,
    ws: wsRef
  };
}
function useWebWorker(arg0, workerOptions, options) {
  const {
    window: window2 = defaultWindow
  } = options != null ? options : {};
  const data = ref(null);
  const worker = shallowRef();
  const post = (...args) => {
    if (!worker.value)
      return;
    worker.value.postMessage(...args);
  };
  const terminate = function terminate2() {
    if (!worker.value)
      return;
    worker.value.terminate();
  };
  if (window2) {
    if (typeof arg0 === "string")
      worker.value = new Worker(arg0, workerOptions);
    else if (typeof arg0 === "function")
      worker.value = arg0();
    else
      worker.value = arg0;
    worker.value.onmessage = (e) => {
      data.value = e.data;
    };
    tryOnScopeDispose(() => {
      if (worker.value)
        worker.value.terminate();
    });
  }
  return {
    data,
    post,
    terminate,
    worker
  };
}
function depsParser(deps, localDeps) {
  if (deps.length === 0 && localDeps.length === 0)
    return "";
  const depsString = deps.map((dep) => `'${dep}'`).toString();
  const depsFunctionString = localDeps.filter((dep) => typeof dep === "function").map((fn) => {
    const str = fn.toString();
    if (str.trim().startsWith("function")) {
      return str;
    } else {
      const name = fn.name;
      return `const ${name} = ${str}`;
    }
  }).join(";");
  const importString = `importScripts(${depsString});`;
  return `${depsString.trim() === "" ? "" : importString} ${depsFunctionString}`;
}
function jobRunner(userFunc) {
  return (e) => {
    const userFuncArgs = e.data[0];
    return Promise.resolve(userFunc.apply(void 0, userFuncArgs)).then((result) => {
      postMessage(["SUCCESS", result]);
    }).catch((error) => {
      postMessage(["ERROR", error]);
    });
  };
}
function createWorkerBlobUrl(fn, deps, localDeps) {
  const blobCode = `${depsParser(deps, localDeps)}; onmessage=(${jobRunner})(${fn})`;
  const blob = new Blob([blobCode], { type: "text/javascript" });
  const url = URL.createObjectURL(blob);
  return url;
}
function useWebWorkerFn(fn, options = {}) {
  const {
    dependencies = [],
    localDependencies = [],
    timeout,
    window: window2 = defaultWindow
  } = options;
  const worker = ref();
  const workerStatus = shallowRef("PENDING");
  const promise = ref({});
  const timeoutId = shallowRef();
  const workerTerminate = (status = "PENDING") => {
    if (worker.value && worker.value._url && window2) {
      worker.value.terminate();
      URL.revokeObjectURL(worker.value._url);
      promise.value = {};
      worker.value = void 0;
      window2.clearTimeout(timeoutId.value);
      workerStatus.value = status;
    }
  };
  workerTerminate();
  tryOnScopeDispose(workerTerminate);
  const generateWorker = () => {
    const blobUrl = createWorkerBlobUrl(fn, dependencies, localDependencies);
    const newWorker = new Worker(blobUrl);
    newWorker._url = blobUrl;
    newWorker.onmessage = (e) => {
      const { resolve = () => {
      }, reject = () => {
      } } = promise.value;
      const [status, result] = e.data;
      switch (status) {
        case "SUCCESS":
          resolve(result);
          workerTerminate(status);
          break;
        default:
          reject(result);
          workerTerminate("ERROR");
          break;
      }
    };
    newWorker.onerror = (e) => {
      const { reject = () => {
      } } = promise.value;
      e.preventDefault();
      reject(e);
      workerTerminate("ERROR");
    };
    if (timeout) {
      timeoutId.value = setTimeout(
        () => workerTerminate("TIMEOUT_EXPIRED"),
        timeout
      );
    }
    return newWorker;
  };
  const callWorker = (...fnArgs) => new Promise((resolve, reject) => {
    var _a;
    promise.value = {
      resolve,
      reject
    };
    (_a = worker.value) == null ? void 0 : _a.postMessage([[...fnArgs]]);
    workerStatus.value = "RUNNING";
  });
  const workerFn = (...fnArgs) => {
    if (workerStatus.value === "RUNNING") {
      console.error(
        "[useWebWorkerFn] You can only run one instance of the worker at a time."
      );
      return Promise.reject();
    }
    worker.value = generateWorker();
    return callWorker(...fnArgs);
  };
  return {
    workerFn,
    workerStatus,
    workerTerminate
  };
}
function useWindowFocus(options = {}) {
  const { window: window2 = defaultWindow } = options;
  if (!window2)
    return shallowRef(false);
  const focused = shallowRef(window2.document.hasFocus());
  const listenerOptions = { passive: true };
  useEventListener(window2, "blur", () => {
    focused.value = false;
  }, listenerOptions);
  useEventListener(window2, "focus", () => {
    focused.value = true;
  }, listenerOptions);
  return focused;
}
function useWindowScroll(options = {}) {
  const { window: window2 = defaultWindow, ...rest } = options;
  return useScroll(window2, rest);
}
function useWindowSize(options = {}) {
  const {
    window: window2 = defaultWindow,
    initialWidth = Number.POSITIVE_INFINITY,
    initialHeight = Number.POSITIVE_INFINITY,
    listenOrientation = true,
    includeScrollbar = true,
    type = "inner"
  } = options;
  const width = shallowRef(initialWidth);
  const height = shallowRef(initialHeight);
  const update = () => {
    if (window2) {
      if (type === "outer") {
        width.value = window2.outerWidth;
        height.value = window2.outerHeight;
      } else if (type === "visual" && window2.visualViewport) {
        const { width: visualViewportWidth, height: visualViewportHeight, scale } = window2.visualViewport;
        width.value = Math.round(visualViewportWidth * scale);
        height.value = Math.round(visualViewportHeight * scale);
      } else if (includeScrollbar) {
        width.value = window2.innerWidth;
        height.value = window2.innerHeight;
      } else {
        width.value = window2.document.documentElement.clientWidth;
        height.value = window2.document.documentElement.clientHeight;
      }
    }
  };
  update();
  tryOnMounted(update);
  const listenerOptions = { passive: true };
  useEventListener("resize", update, listenerOptions);
  if (window2 && type === "visual" && window2.visualViewport) {
    useEventListener(window2.visualViewport, "resize", update, listenerOptions);
  }
  if (listenOrientation) {
    const matches = useMediaQuery("(orientation: portrait)");
    watch(matches, () => update());
  }
  return { width, height };
}

'use strict';

/**
 * Create a bound version of a function with a specified `this` context
 *
 * @param {Function} fn - The function to bind
 * @param {*} thisArg - The value to be passed as the `this` parameter
 * @returns {Function} A new function that will call the original function with the specified `this` context
 */
function bind(fn, thisArg) {
  return function wrap() {
    return fn.apply(thisArg, arguments);
  };
}

"use strict";

// utils is a library of generic helper functions non-specific to axios

const { toString } = Object.prototype;
const { getPrototypeOf } = Object;
const { iterator, toStringTag } = Symbol;

const kindOf = ((cache) => (thing) => {
  const str = toString.call(thing);
  return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(Object.create(null));

const kindOfTest = (type) => {
  type = type.toLowerCase();
  return (thing) => kindOf(thing) === type;
};

const typeOfTest = (type) => (thing) => typeof thing === type;

/**
 * Determine if a value is a non-null object
 *
 * @param {Object} val The value to test
 *
 * @returns {boolean} True if value is an Array, otherwise false
 */
const { isArray: isArray$2 } = Array;

/**
 * Determine if a value is undefined
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if the value is undefined, otherwise false
 */
const isUndefined = typeOfTest("undefined");

/**
 * Determine if a value is a Buffer
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a Buffer, otherwise false
 */
function isBuffer(val) {
  return (
    val !== null &&
    !isUndefined(val) &&
    val.constructor !== null &&
    !isUndefined(val.constructor) &&
    isFunction$2(val.constructor.isBuffer) &&
    val.constructor.isBuffer(val)
  );
}

/**
 * Determine if a value is an ArrayBuffer
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is an ArrayBuffer, otherwise false
 */
const isArrayBuffer = kindOfTest("ArrayBuffer");

/**
 * Determine if a value is a view on an ArrayBuffer
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
 */
function isArrayBufferView(val) {
  let result;
  if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
    result = ArrayBuffer.isView(val);
  } else {
    result = val && val.buffer && isArrayBuffer(val.buffer);
  }
  return result;
}

/**
 * Determine if a value is a String
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a String, otherwise false
 */
const isString = typeOfTest("string");

/**
 * Determine if a value is a Function
 *
 * @param {*} val The value to test
 * @returns {boolean} True if value is a Function, otherwise false
 */
const isFunction$2 = typeOfTest("function");

/**
 * Determine if a value is a Number
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a Number, otherwise false
 */
const isNumber$1 = typeOfTest("number");

/**
 * Determine if a value is an Object
 *
 * @param {*} thing The value to test
 *
 * @returns {boolean} True if value is an Object, otherwise false
 */
const isObject$1 = (thing) => thing !== null && typeof thing === "object";

/**
 * Determine if a value is a Boolean
 *
 * @param {*} thing The value to test
 * @returns {boolean} True if value is a Boolean, otherwise false
 */
const isBoolean = (thing) => thing === true || thing === false;

/**
 * Determine if a value is a plain Object
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a plain Object, otherwise false
 */
const isPlainObject$2 = (val) => {
  if (kindOf(val) !== "object") {
    return false;
  }

  const prototype = getPrototypeOf(val);
  return (
    (prototype === null ||
      prototype === Object.prototype ||
      Object.getPrototypeOf(prototype) === null) &&
    !(toStringTag in val) &&
    !(iterator in val)
  );
};

/**
 * Determine if a value is an empty object (safely handles Buffers)
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is an empty object, otherwise false
 */
const isEmptyObject = (val) => {
  // Early return for non-objects or Buffers to prevent RangeError
  if (!isObject$1(val) || isBuffer(val)) {
    return false;
  }

  try {
    return (
      Object.keys(val).length === 0 &&
      Object.getPrototypeOf(val) === Object.prototype
    );
  } catch (e) {
    // Fallback for any other objects that might cause RangeError with Object.keys()
    return false;
  }
};

/**
 * Determine if a value is a Date
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a Date, otherwise false
 */
const isDate = kindOfTest("Date");

/**
 * Determine if a value is a File
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a File, otherwise false
 */
const isFile = kindOfTest("File");

/**
 * Determine if a value is a Blob
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a Blob, otherwise false
 */
const isBlob = kindOfTest("Blob");

/**
 * Determine if a value is a FileList
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a File, otherwise false
 */
const isFileList = kindOfTest("FileList");

/**
 * Determine if a value is a Stream
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a Stream, otherwise false
 */
const isStream = (val) => isObject$1(val) && isFunction$2(val.pipe);

/**
 * Determine if a value is a FormData
 *
 * @param {*} thing The value to test
 *
 * @returns {boolean} True if value is an FormData, otherwise false
 */
const isFormData = (thing) => {
  let kind;
  return (
    thing &&
    ((typeof FormData === "function" && thing instanceof FormData) ||
      (isFunction$2(thing.append) &&
        ((kind = kindOf(thing)) === "formdata" ||
          // detect form-data instance
          (kind === "object" &&
            isFunction$2(thing.toString) &&
            thing.toString() === "[object FormData]"))))
  );
};

/**
 * Determine if a value is a URLSearchParams object
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
 */
const isURLSearchParams = kindOfTest("URLSearchParams");

const [isReadableStream, isRequest, isResponse, isHeaders] = [
  "ReadableStream",
  "Request",
  "Response",
  "Headers",
].map(kindOfTest);

/**
 * Trim excess whitespace off the beginning and end of a string
 *
 * @param {String} str The String to trim
 *
 * @returns {String} The String freed of excess whitespace
 */
const trim = (str) =>
  str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");

/**
 * Iterate over an Array or an Object invoking a function for each item.
 *
 * If `obj` is an Array callback will be called passing
 * the value, index, and complete array for each item.
 *
 * If 'obj' is an Object callback will be called passing
 * the value, key, and complete object for each property.
 *
 * @param {Object|Array<unknown>} obj The object to iterate
 * @param {Function} fn The callback to invoke for each item
 *
 * @param {Object} [options]
 * @param {Boolean} [options.allOwnKeys = false]
 * @returns {any}
 */
function forEach(obj, fn, { allOwnKeys = false } = {}) {
  // Don't bother if no value provided
  if (obj === null || typeof obj === "undefined") {
    return;
  }

  let i;
  let l;

  // Force an array if not already something iterable
  if (typeof obj !== "object") {
    /*eslint no-param-reassign:0*/
    obj = [obj];
  }

  if (isArray$2(obj)) {
    // Iterate over array values
    for (i = 0, l = obj.length; i < l; i++) {
      fn.call(null, obj[i], i, obj);
    }
  } else {
    // Buffer check
    if (isBuffer(obj)) {
      return;
    }

    // Iterate over object keys
    const keys = allOwnKeys
      ? Object.getOwnPropertyNames(obj)
      : Object.keys(obj);
    const len = keys.length;
    let key;

    for (i = 0; i < len; i++) {
      key = keys[i];
      fn.call(null, obj[key], key, obj);
    }
  }
}

function findKey(obj, key) {
  if (isBuffer(obj)) {
    return null;
  }

  key = key.toLowerCase();
  const keys = Object.keys(obj);
  let i = keys.length;
  let _key;
  while (i-- > 0) {
    _key = keys[i];
    if (key === _key.toLowerCase()) {
      return _key;
    }
  }
  return null;
}

const _global = (() => {
  /*eslint no-undef:0*/
  if (typeof globalThis !== "undefined") return globalThis;
  return typeof self !== "undefined"
    ? self
    : typeof window !== "undefined"
      ? window
      : global;
})();

const isContextDefined = (context) =>
  !isUndefined(context) && context !== _global;

/**
 * Accepts varargs expecting each argument to be an object, then
 * immutably merges the properties of each object and returns result.
 *
 * When multiple objects contain the same key the later object in
 * the arguments list will take precedence.
 *
 * Example:
 *
 * ```js
 * const result = merge({foo: 123}, {foo: 456});
 * console.log(result.foo); // outputs 456
 * ```
 *
 * @param {Object} obj1 Object to merge
 *
 * @returns {Object} Result of all merge properties
 */
function merge$1(/* obj1, obj2, obj3, ... */) {
  const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};
  const result = {};
  const assignValue = (val, key) => {
    // Skip dangerous property names to prevent prototype pollution
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      return;
    }

    const targetKey = (caseless && findKey(result, key)) || key;
    if (isPlainObject$2(result[targetKey]) && isPlainObject$2(val)) {
      result[targetKey] = merge$1(result[targetKey], val);
    } else if (isPlainObject$2(val)) {
      result[targetKey] = merge$1({}, val);
    } else if (isArray$2(val)) {
      result[targetKey] = val.slice();
    } else if (!skipUndefined || !isUndefined(val)) {
      result[targetKey] = val;
    }
  };

  for (let i = 0, l = arguments.length; i < l; i++) {
    arguments[i] && forEach(arguments[i], assignValue);
  }
  return result;
}

/**
 * Extends object a by mutably adding to it the properties of object b.
 *
 * @param {Object} a The object to be extended
 * @param {Object} b The object to copy properties from
 * @param {Object} thisArg The object to bind function to
 *
 * @param {Object} [options]
 * @param {Boolean} [options.allOwnKeys]
 * @returns {Object} The resulting value of object a
 */
const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
  forEach(
    b,
    (val, key) => {
      if (thisArg && isFunction$2(val)) {
        Object.defineProperty(a, key, {
          value: bind(val, thisArg),
          writable: true,
          enumerable: true,
          configurable: true,
        });
      } else {
        Object.defineProperty(a, key, {
          value: val,
          writable: true,
          enumerable: true,
          configurable: true,
        });
      }
    },
    { allOwnKeys },
  );
  return a;
};

/**
 * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
 *
 * @param {string} content with BOM
 *
 * @returns {string} content value without BOM
 */
const stripBOM = (content) => {
  if (content.charCodeAt(0) === 0xfeff) {
    content = content.slice(1);
  }
  return content;
};

/**
 * Inherit the prototype methods from one constructor into another
 * @param {function} constructor
 * @param {function} superConstructor
 * @param {object} [props]
 * @param {object} [descriptors]
 *
 * @returns {void}
 */
const inherits = (constructor, superConstructor, props, descriptors) => {
  constructor.prototype = Object.create(
    superConstructor.prototype,
    descriptors,
  );
  Object.defineProperty(constructor.prototype, "constructor", {
    value: constructor,
    writable: true,
    enumerable: false,
    configurable: true,
  });
  Object.defineProperty(constructor, "super", {
    value: superConstructor.prototype,
  });
  props && Object.assign(constructor.prototype, props);
};

/**
 * Resolve object with deep prototype chain to a flat object
 * @param {Object} sourceObj source object
 * @param {Object} [destObj]
 * @param {Function|Boolean} [filter]
 * @param {Function} [propFilter]
 *
 * @returns {Object}
 */
const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
  let props;
  let i;
  let prop;
  const merged = {};

  destObj = destObj || {};
  // eslint-disable-next-line no-eq-null,eqeqeq
  if (sourceObj == null) return destObj;

  do {
    props = Object.getOwnPropertyNames(sourceObj);
    i = props.length;
    while (i-- > 0) {
      prop = props[i];
      if (
        (!propFilter || propFilter(prop, sourceObj, destObj)) &&
        !merged[prop]
      ) {
        destObj[prop] = sourceObj[prop];
        merged[prop] = true;
      }
    }
    sourceObj = filter !== false && getPrototypeOf(sourceObj);
  } while (
    sourceObj &&
    (!filter || filter(sourceObj, destObj)) &&
    sourceObj !== Object.prototype
  );

  return destObj;
};

/**
 * Determines whether a string ends with the characters of a specified string
 *
 * @param {String} str
 * @param {String} searchString
 * @param {Number} [position= 0]
 *
 * @returns {boolean}
 */
const endsWith = (str, searchString, position) => {
  str = String(str);
  if (position === undefined || position > str.length) {
    position = str.length;
  }
  position -= searchString.length;
  const lastIndex = str.indexOf(searchString, position);
  return lastIndex !== -1 && lastIndex === position;
};

/**
 * Returns new array from array like object or null if failed
 *
 * @param {*} [thing]
 *
 * @returns {?Array}
 */
const toArray = (thing) => {
  if (!thing) return null;
  if (isArray$2(thing)) return thing;
  let i = thing.length;
  if (!isNumber$1(i)) return null;
  const arr = new Array(i);
  while (i-- > 0) {
    arr[i] = thing[i];
  }
  return arr;
};

/**
 * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
 * thing passed in is an instance of Uint8Array
 *
 * @param {TypedArray}
 *
 * @returns {Array}
 */
// eslint-disable-next-line func-names
const isTypedArray = ((TypedArray) => {
  // eslint-disable-next-line func-names
  return (thing) => {
    return TypedArray && thing instanceof TypedArray;
  };
})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));

/**
 * For each entry in the object, call the function with the key and value.
 *
 * @param {Object<any, any>} obj - The object to iterate over.
 * @param {Function} fn - The function to call for each entry.
 *
 * @returns {void}
 */
const forEachEntry = (obj, fn) => {
  const generator = obj && obj[iterator];

  const _iterator = generator.call(obj);

  let result;

  while ((result = _iterator.next()) && !result.done) {
    const pair = result.value;
    fn.call(obj, pair[0], pair[1]);
  }
};

/**
 * It takes a regular expression and a string, and returns an array of all the matches
 *
 * @param {string} regExp - The regular expression to match against.
 * @param {string} str - The string to search.
 *
 * @returns {Array<boolean>}
 */
const matchAll = (regExp, str) => {
  let matches;
  const arr = [];

  while ((matches = regExp.exec(str)) !== null) {
    arr.push(matches);
  }

  return arr;
};

/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
const isHTMLForm = kindOfTest("HTMLFormElement");

const toCamelCase = (str) => {
  return str
    .toLowerCase()
    .replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
      return p1.toUpperCase() + p2;
    });
};

/* Creating a function that will check if an object has a property. */
const hasOwnProperty = (
  ({ hasOwnProperty }) =>
  (obj, prop) =>
    hasOwnProperty.call(obj, prop)
)(Object.prototype);

/**
 * Determine if a value is a RegExp object
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a RegExp object, otherwise false
 */
const isRegExp = kindOfTest("RegExp");

const reduceDescriptors = (obj, reducer) => {
  const descriptors = Object.getOwnPropertyDescriptors(obj);
  const reducedDescriptors = {};

  forEach(descriptors, (descriptor, name) => {
    let ret;
    if ((ret = reducer(descriptor, name, obj)) !== false) {
      reducedDescriptors[name] = ret || descriptor;
    }
  });

  Object.defineProperties(obj, reducedDescriptors);
};

/**
 * Makes all methods read-only
 * @param {Object} obj
 */

const freezeMethods = (obj) => {
  reduceDescriptors(obj, (descriptor, name) => {
    // skip restricted props in strict mode
    if (
      isFunction$2(obj) &&
      ["arguments", "caller", "callee"].indexOf(name) !== -1
    ) {
      return false;
    }

    const value = obj[name];

    if (!isFunction$2(value)) return;

    descriptor.enumerable = false;

    if ("writable" in descriptor) {
      descriptor.writable = false;
      return;
    }

    if (!descriptor.set) {
      descriptor.set = () => {
        throw Error("Can not rewrite read-only method '" + name + "'");
      };
    }
  });
};

const toObjectSet = (arrayOrString, delimiter) => {
  const obj = {};

  const define = (arr) => {
    arr.forEach((value) => {
      obj[value] = true;
    });
  };

  isArray$2(arrayOrString)
    ? define(arrayOrString)
    : define(String(arrayOrString).split(delimiter));

  return obj;
};

const noop$2 = () => {};

const toFiniteNumber$2 = (value, defaultValue) => {
  return value != null && Number.isFinite((value = +value))
    ? value
    : defaultValue;
};

/**
 * If the thing is a FormData object, return true, otherwise return false.
 *
 * @param {unknown} thing - The thing to check.
 *
 * @returns {boolean}
 */
function isSpecCompliantForm(thing) {
  return !!(
    thing &&
    isFunction$2(thing.append) &&
    thing[toStringTag] === "FormData" &&
    thing[iterator]
  );
}

const toJSONObject = (obj) => {
  const stack = new Array(10);

  const visit = (source, i) => {
    if (isObject$1(source)) {
      if (stack.indexOf(source) >= 0) {
        return;
      }

      //Buffer check
      if (isBuffer(source)) {
        return source;
      }

      if (!("toJSON" in source)) {
        stack[i] = source;
        const target = isArray$2(source) ? [] : {};

        forEach(source, (value, key) => {
          const reducedValue = visit(value, i + 1);
          !isUndefined(reducedValue) && (target[key] = reducedValue);
        });

        stack[i] = undefined;

        return target;
      }
    }

    return source;
  };

  return visit(obj, 0);
};

const isAsyncFn = kindOfTest("AsyncFunction");

const isThenable = (thing) =>
  thing &&
  (isObject$1(thing) || isFunction$2(thing)) &&
  isFunction$2(thing.then) &&
  isFunction$2(thing.catch);

// original code
// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34

const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
  if (setImmediateSupported) {
    return setImmediate;
  }

  return postMessageSupported
    ? ((token, callbacks) => {
        _global.addEventListener(
          "message",
          ({ source, data }) => {
            if (source === _global && data === token) {
              callbacks.length && callbacks.shift()();
            }
          },
          false,
        );

        return (cb) => {
          callbacks.push(cb);
          _global.postMessage(token, "*");
        };
      })(`axios@${Math.random()}`, [])
    : (cb) => setTimeout(cb);
})(typeof setImmediate === "function", isFunction$2(_global.postMessage));

const asap =
  typeof queueMicrotask !== "undefined"
    ? queueMicrotask.bind(_global)
    : (typeof process !== "undefined" && process.nextTick) || _setImmediate;

// *********************

const isIterable = (thing) => thing != null && isFunction$2(thing[iterator]);

const utils$2 = {
  isArray: isArray$2,
  isArrayBuffer,
  isBuffer,
  isFormData,
  isArrayBufferView,
  isString,
  isNumber: isNumber$1,
  isBoolean,
  isObject: isObject$1,
  isPlainObject: isPlainObject$2,
  isEmptyObject,
  isReadableStream,
  isRequest,
  isResponse,
  isHeaders,
  isUndefined,
  isDate,
  isFile,
  isBlob,
  isRegExp,
  isFunction: isFunction$2,
  isStream,
  isURLSearchParams,
  isTypedArray,
  isFileList,
  forEach,
  merge: merge$1,
  extend,
  trim,
  stripBOM,
  inherits,
  toFlatObject,
  kindOf,
  kindOfTest,
  endsWith,
  toArray,
  forEachEntry,
  matchAll,
  isHTMLForm,
  hasOwnProperty,
  hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
  reduceDescriptors,
  freezeMethods,
  toObjectSet,
  toCamelCase,
  noop: noop$2,
  toFiniteNumber: toFiniteNumber$2,
  findKey,
  global: _global,
  isContextDefined,
  isSpecCompliantForm,
  toJSONObject,
  isAsyncFn,
  isThenable,
  setImmediate: _setImmediate,
  asap,
  isIterable,
};

'use strict';

let AxiosError$1 = class AxiosError extends Error {
    static from(error, code, config, request, response, customProps) {
        const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
        axiosError.cause = error;
        axiosError.name = error.name;
        customProps && Object.assign(axiosError, customProps);
        return axiosError;
    }

    /**
     * Create an Error with the specified message, config, error code, request and response.
     *
     * @param {string} message The error message.
     * @param {string} [code] The error code (for example, 'ECONNABORTED').
     * @param {Object} [config] The config.
     * @param {Object} [request] The request.
     * @param {Object} [response] The response.
     *
     * @returns {Error} The created error.
     */
    constructor(message, code, config, request, response) {
        super(message);
        this.name = 'AxiosError';
        this.isAxiosError = true;
        code && (this.code = code);
        config && (this.config = config);
        request && (this.request = request);
        if (response) {
            this.response = response;
            this.status = response.status;
        }
    }

    toJSON() {
        return {
            // Standard
            message: this.message,
            name: this.name,
            // Microsoft
            description: this.description,
            number: this.number,
            // Mozilla
            fileName: this.fileName,
            lineNumber: this.lineNumber,
            columnNumber: this.columnNumber,
            stack: this.stack,
            // Axios
            config: utils$2.toJSONObject(this.config),
            code: this.code,
            status: this.status,
        };
    }
};

// This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
AxiosError$1.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
AxiosError$1.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
AxiosError$1.ECONNABORTED = 'ECONNABORTED';
AxiosError$1.ETIMEDOUT = 'ETIMEDOUT';
AxiosError$1.ERR_NETWORK = 'ERR_NETWORK';
AxiosError$1.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
AxiosError$1.ERR_DEPRECATED = 'ERR_DEPRECATED';
AxiosError$1.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
AxiosError$1.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
AxiosError$1.ERR_CANCELED = 'ERR_CANCELED';
AxiosError$1.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
AxiosError$1.ERR_INVALID_URL = 'ERR_INVALID_URL';

// eslint-disable-next-line strict
const httpAdapter = null;

'use strict';

/**
 * Determines if the given thing is a array or js object.
 *
 * @param {string} thing - The object or array to be visited.
 *
 * @returns {boolean}
 */
function isVisitable(thing) {
  return utils$2.isPlainObject(thing) || utils$2.isArray(thing);
}

/**
 * It removes the brackets from the end of a string
 *
 * @param {string} key - The key of the parameter.
 *
 * @returns {string} the key without the brackets.
 */
function removeBrackets(key) {
  return utils$2.endsWith(key, '[]') ? key.slice(0, -2) : key;
}

/**
 * It takes a path, a key, and a boolean, and returns a string
 *
 * @param {string} path - The path to the current key.
 * @param {string} key - The key of the current object being iterated over.
 * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
 *
 * @returns {string} The path to the current key.
 */
function renderKey(path, key, dots) {
  if (!path) return key;
  return path.concat(key).map(function each(token, i) {
    // eslint-disable-next-line no-param-reassign
    token = removeBrackets(token);
    return !dots && i ? '[' + token + ']' : token;
  }).join(dots ? '.' : '');
}

/**
 * If the array is an array and none of its elements are visitable, then it's a flat array.
 *
 * @param {Array<any>} arr - The array to check
 *
 * @returns {boolean}
 */
function isFlatArray(arr) {
  return utils$2.isArray(arr) && !arr.some(isVisitable);
}

const predicates = utils$2.toFlatObject(utils$2, {}, null, function filter(prop) {
  return /^is[A-Z]/.test(prop);
});

/**
 * Convert a data object to FormData
 *
 * @param {Object} obj
 * @param {?Object} [formData]
 * @param {?Object} [options]
 * @param {Function} [options.visitor]
 * @param {Boolean} [options.metaTokens = true]
 * @param {Boolean} [options.dots = false]
 * @param {?Boolean} [options.indexes = false]
 *
 * @returns {Object}
 **/

/**
 * It converts an object into a FormData object
 *
 * @param {Object<any, any>} obj - The object to convert to form data.
 * @param {string} formData - The FormData object to append to.
 * @param {Object<string, any>} options
 *
 * @returns
 */
function toFormData$1(obj, formData, options) {
  if (!utils$2.isObject(obj)) {
    throw new TypeError('target must be an object');
  }

  // eslint-disable-next-line no-param-reassign
  formData = formData || new (httpAdapter || FormData)();

  // eslint-disable-next-line no-param-reassign
  options = utils$2.toFlatObject(options, {
    metaTokens: true,
    dots: false,
    indexes: false
  }, false, function defined(option, source) {
    // eslint-disable-next-line no-eq-null,eqeqeq
    return !utils$2.isUndefined(source[option]);
  });

  const metaTokens = options.metaTokens;
  // eslint-disable-next-line no-use-before-define
  const visitor = options.visitor || defaultVisitor;
  const dots = options.dots;
  const indexes = options.indexes;
  const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
  const useBlob = _Blob && utils$2.isSpecCompliantForm(formData);

  if (!utils$2.isFunction(visitor)) {
    throw new TypeError('visitor must be a function');
  }

  function convertValue(value) {
    if (value === null) return '';

    if (utils$2.isDate(value)) {
      return value.toISOString();
    }

    if (utils$2.isBoolean(value)) {
      return value.toString();
    }

    if (!useBlob && utils$2.isBlob(value)) {
      throw new AxiosError$1('Blob is not supported. Use a Buffer instead.');
    }

    if (utils$2.isArrayBuffer(value) || utils$2.isTypedArray(value)) {
      return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
    }

    return value;
  }

  /**
   * Default visitor.
   *
   * @param {*} value
   * @param {String|Number} key
   * @param {Array<String|Number>} path
   * @this {FormData}
   *
   * @returns {boolean} return true to visit the each prop of the value recursively
   */
  function defaultVisitor(value, key, path) {
    let arr = value;

    if (value && !path && typeof value === 'object') {
      if (utils$2.endsWith(key, '{}')) {
        // eslint-disable-next-line no-param-reassign
        key = metaTokens ? key : key.slice(0, -2);
        // eslint-disable-next-line no-param-reassign
        value = JSON.stringify(value);
      } else if (
        (utils$2.isArray(value) && isFlatArray(value)) ||
        ((utils$2.isFileList(value) || utils$2.endsWith(key, '[]')) && (arr = utils$2.toArray(value))
        )) {
        // eslint-disable-next-line no-param-reassign
        key = removeBrackets(key);

        arr.forEach(function each(el, index) {
          !(utils$2.isUndefined(el) || el === null) && formData.append(
            // eslint-disable-next-line no-nested-ternary
            indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
            convertValue(el)
          );
        });
        return false;
      }
    }

    if (isVisitable(value)) {
      return true;
    }

    formData.append(renderKey(path, key, dots), convertValue(value));

    return false;
  }

  const stack = [];

  const exposedHelpers = Object.assign(predicates, {
    defaultVisitor,
    convertValue,
    isVisitable
  });

  function build(value, path) {
    if (utils$2.isUndefined(value)) return;

    if (stack.indexOf(value) !== -1) {
      throw Error('Circular reference detected in ' + path.join('.'));
    }

    stack.push(value);

    utils$2.forEach(value, function each(el, key) {
      const result = !(utils$2.isUndefined(el) || el === null) && visitor.call(
        formData, el, utils$2.isString(key) ? key.trim() : key, path, exposedHelpers
      );

      if (result === true) {
        build(el, path ? path.concat(key) : [key]);
      }
    });

    stack.pop();
  }

  if (!utils$2.isObject(obj)) {
    throw new TypeError('data must be an object');
  }

  build(obj);

  return formData;
}

'use strict';

/**
 * It encodes a string by replacing all characters that are not in the unreserved set with
 * their percent-encoded equivalents
 *
 * @param {string} str - The string to encode.
 *
 * @returns {string} The encoded string.
 */
function encode$1(str) {
  const charMap = {
    '!': '%21',
    "'": '%27',
    '(': '%28',
    ')': '%29',
    '~': '%7E',
    '%20': '+',
    '%00': '\x00'
  };
  return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
    return charMap[match];
  });
}

/**
 * It takes a params object and converts it to a FormData object
 *
 * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
 * @param {Object<string, any>} options - The options object passed to the Axios constructor.
 *
 * @returns {void}
 */
function AxiosURLSearchParams(params, options) {
  this._pairs = [];

  params && toFormData$1(params, this, options);
}

const prototype = AxiosURLSearchParams.prototype;

prototype.append = function append(name, value) {
  this._pairs.push([name, value]);
};

prototype.toString = function toString(encoder) {
  const _encode = encoder ? function(value) {
    return encoder.call(this, value, encode$1);
  } : encode$1;

  return this._pairs.map(function each(pair) {
    return _encode(pair[0]) + '=' + _encode(pair[1]);
  }, '').join('&');
};

'use strict';

/**
 * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
 * URI encoded counterparts
 *
 * @param {string} val The value to be encoded.
 *
 * @returns {string} The encoded value.
 */
function encode(val) {
  return encodeURIComponent(val).
    replace(/%3A/gi, ':').
    replace(/%24/g, '$').
    replace(/%2C/gi, ',').
    replace(/%20/g, '+');
}

/**
 * Build a URL by appending params to the end
 *
 * @param {string} url The base of the url (e.g., http://www.google.com)
 * @param {object} [params] The params to be appended
 * @param {?(object|Function)} options
 *
 * @returns {string} The formatted url
 */
function buildURL(url, params, options) {
  if (!params) {
    return url;
  }

  const _encode = options && options.encode || encode;

  const _options = utils$2.isFunction(options) ? {
    serialize: options
  } : options;

  const serializeFn = _options && _options.serialize;

  let serializedParams;

  if (serializeFn) {
    serializedParams = serializeFn(params, _options);
  } else {
    serializedParams = utils$2.isURLSearchParams(params) ?
      params.toString() :
      new AxiosURLSearchParams(params, _options).toString(_encode);
  }

  if (serializedParams) {
    const hashmarkIndex = url.indexOf("#");

    if (hashmarkIndex !== -1) {
      url = url.slice(0, hashmarkIndex);
    }
    url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  }

  return url;
}

'use strict';

class InterceptorManager {
  constructor() {
    this.handlers = [];
  }

  /**
   * Add a new interceptor to the stack
   *
   * @param {Function} fulfilled The function to handle `then` for a `Promise`
   * @param {Function} rejected The function to handle `reject` for a `Promise`
   * @param {Object} options The options for the interceptor, synchronous and runWhen
   *
   * @return {Number} An ID used to remove interceptor later
   */
  use(fulfilled, rejected, options) {
    this.handlers.push({
      fulfilled,
      rejected,
      synchronous: options ? options.synchronous : false,
      runWhen: options ? options.runWhen : null
    });
    return this.handlers.length - 1;
  }

  /**
   * Remove an interceptor from the stack
   *
   * @param {Number} id The ID that was returned by `use`
   *
   * @returns {void}
   */
  eject(id) {
    if (this.handlers[id]) {
      this.handlers[id] = null;
    }
  }

  /**
   * Clear all interceptors from the stack
   *
   * @returns {void}
   */
  clear() {
    if (this.handlers) {
      this.handlers = [];
    }
  }

  /**
   * Iterate over all the registered interceptors
   *
   * This method is particularly useful for skipping over any
   * interceptors that may have become `null` calling `eject`.
   *
   * @param {Function} fn The function to call for each interceptor
   *
   * @returns {void}
   */
  forEach(fn) {
    utils$2.forEach(this.handlers, function forEachHandler(h) {
      if (h !== null) {
        fn(h);
      }
    });
  }
}

'use strict';

const transitionalDefaults = {
  silentJSONParsing: true,
  forcedJSONParsing: true,
  clarifyTimeoutError: false,
  legacyInterceptorReqResOrdering: true
};

'use strict';
const URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;

'use strict';

const FormData$1 = typeof FormData !== 'undefined' ? FormData : null;

'use strict';

const Blob$1 = typeof Blob !== 'undefined' ? Blob : null;

const platform$1 = {
  isBrowser: true,
  classes: {
    URLSearchParams: URLSearchParams$1,
    FormData: FormData$1,
    Blob: Blob$1
  },
  protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
};

const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';

const _navigator = typeof navigator === 'object' && navigator || undefined;

/**
 * Determine if we're running in a standard browser environment
 *
 * This allows axios to run in a web worker, and react-native.
 * Both environments support XMLHttpRequest, but not fully standard globals.
 *
 * web workers:
 *  typeof window -> undefined
 *  typeof document -> undefined
 *
 * react-native:
 *  navigator.product -> 'ReactNative'
 * nativescript
 *  navigator.product -> 'NativeScript' or 'NS'
 *
 * @returns {boolean}
 */
const hasStandardBrowserEnv = hasBrowserEnv &&
  (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);

/**
 * Determine if we're running in a standard browser webWorker environment
 *
 * Although the `isStandardBrowserEnv` method indicates that
 * `allows axios to run in a web worker`, the WebWorker will still be
 * filtered out due to its judgment standard
 * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
 * This leads to a problem when axios post `FormData` in webWorker
 */
const hasStandardBrowserWebWorkerEnv = (() => {
  return (
    typeof WorkerGlobalScope !== 'undefined' &&
    // eslint-disable-next-line no-undef
    self instanceof WorkerGlobalScope &&
    typeof self.importScripts === 'function'
  );
})();

const origin = hasBrowserEnv && window.location.href || 'http://localhost';

const utils$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  hasBrowserEnv,
  hasStandardBrowserEnv,
  hasStandardBrowserWebWorkerEnv,
  navigator: _navigator,
  origin
}, Symbol.toStringTag, { value: 'Module' }));

const platform = {
  ...utils$1,
  ...platform$1
};

'use strict';

function toURLEncodedForm(data, options) {
  return toFormData$1(data, new platform.classes.URLSearchParams(), {
    visitor: function(value, key, path, helpers) {
      if (platform.isNode && utils$2.isBuffer(value)) {
        this.append(key, value.toString('base64'));
        return false;
      }

      return helpers.defaultVisitor.apply(this, arguments);
    },
    ...options
  });
}

'use strict';

/**
 * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
 *
 * @param {string} name - The name of the property to get.
 *
 * @returns An array of strings.
 */
function parsePropPath(name) {
  // foo[x][y][z]
  // foo.x.y.z
  // foo-x-y-z
  // foo x y z
  return utils$2.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
    return match[0] === '[]' ? '' : match[1] || match[0];
  });
}

/**
 * Convert an array to an object.
 *
 * @param {Array<any>} arr - The array to convert to an object.
 *
 * @returns An object with the same keys and values as the array.
 */
function arrayToObject(arr) {
  const obj = {};
  const keys = Object.keys(arr);
  let i;
  const len = keys.length;
  let key;
  for (i = 0; i < len; i++) {
    key = keys[i];
    obj[key] = arr[key];
  }
  return obj;
}

/**
 * It takes a FormData object and returns a JavaScript object
 *
 * @param {string} formData The FormData object to convert to JSON.
 *
 * @returns {Object<string, any> | null} The converted object.
 */
function formDataToJSON(formData) {
  function buildPath(path, value, target, index) {
    let name = path[index++];

    if (name === '__proto__') return true;

    const isNumericKey = Number.isFinite(+name);
    const isLast = index >= path.length;
    name = !name && utils$2.isArray(target) ? target.length : name;

    if (isLast) {
      if (utils$2.hasOwnProp(target, name)) {
        target[name] = [target[name], value];
      } else {
        target[name] = value;
      }

      return !isNumericKey;
    }

    if (!target[name] || !utils$2.isObject(target[name])) {
      target[name] = [];
    }

    const result = buildPath(path, value, target[name], index);

    if (result && utils$2.isArray(target[name])) {
      target[name] = arrayToObject(target[name]);
    }

    return !isNumericKey;
  }

  if (utils$2.isFormData(formData) && utils$2.isFunction(formData.entries)) {
    const obj = {};

    utils$2.forEachEntry(formData, (name, value) => {
      buildPath(parsePropPath(name), value, obj, 0);
    });

    return obj;
  }

  return null;
}

'use strict';

/**
 * It takes a string, tries to parse it, and if it fails, it returns the stringified version
 * of the input
 *
 * @param {any} rawValue - The value to be stringified.
 * @param {Function} parser - A function that parses a string into a JavaScript object.
 * @param {Function} encoder - A function that takes a value and returns a string.
 *
 * @returns {string} A stringified version of the rawValue.
 */
function stringifySafely(rawValue, parser, encoder) {
  if (utils$2.isString(rawValue)) {
    try {
      (parser || JSON.parse)(rawValue);
      return utils$2.trim(rawValue);
    } catch (e) {
      if (e.name !== 'SyntaxError') {
        throw e;
      }
    }
  }

  return (encoder || JSON.stringify)(rawValue);
}

const defaults$1 = {

  transitional: transitionalDefaults,

  adapter: ['xhr', 'http', 'fetch'],

  transformRequest: [function transformRequest(data, headers) {
    const contentType = headers.getContentType() || '';
    const hasJSONContentType = contentType.indexOf('application/json') > -1;
    const isObjectPayload = utils$2.isObject(data);

    if (isObjectPayload && utils$2.isHTMLForm(data)) {
      data = new FormData(data);
    }

    const isFormData = utils$2.isFormData(data);

    if (isFormData) {
      return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
    }

    if (utils$2.isArrayBuffer(data) ||
      utils$2.isBuffer(data) ||
      utils$2.isStream(data) ||
      utils$2.isFile(data) ||
      utils$2.isBlob(data) ||
      utils$2.isReadableStream(data)
    ) {
      return data;
    }
    if (utils$2.isArrayBufferView(data)) {
      return data.buffer;
    }
    if (utils$2.isURLSearchParams(data)) {
      headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
      return data.toString();
    }

    let isFileList;

    if (isObjectPayload) {
      if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
        return toURLEncodedForm(data, this.formSerializer).toString();
      }

      if ((isFileList = utils$2.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
        const _FormData = this.env && this.env.FormData;

        return toFormData$1(
          isFileList ? {'files[]': data} : data,
          _FormData && new _FormData(),
          this.formSerializer
        );
      }
    }

    if (isObjectPayload || hasJSONContentType ) {
      headers.setContentType('application/json', false);
      return stringifySafely(data);
    }

    return data;
  }],

  transformResponse: [function transformResponse(data) {
    const transitional = this.transitional || defaults$1.transitional;
    const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
    const JSONRequested = this.responseType === 'json';

    if (utils$2.isResponse(data) || utils$2.isReadableStream(data)) {
      return data;
    }

    if (data && utils$2.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
      const silentJSONParsing = transitional && transitional.silentJSONParsing;
      const strictJSONParsing = !silentJSONParsing && JSONRequested;

      try {
        return JSON.parse(data, this.parseReviver);
      } catch (e) {
        if (strictJSONParsing) {
          if (e.name === 'SyntaxError') {
            throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
          }
          throw e;
        }
      }
    }

    return data;
  }],

  /**
   * A timeout in milliseconds to abort a request. If set to 0 (default) a
   * timeout is not created.
   */
  timeout: 0,

  xsrfCookieName: 'XSRF-TOKEN',
  xsrfHeaderName: 'X-XSRF-TOKEN',

  maxContentLength: -1,
  maxBodyLength: -1,

  env: {
    FormData: platform.classes.FormData,
    Blob: platform.classes.Blob
  },

  validateStatus: function validateStatus(status) {
    return status >= 200 && status < 300;
  },

  headers: {
    common: {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': undefined
    }
  }
};

utils$2.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
  defaults$1.headers[method] = {};
});

'use strict';

// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
const ignoreDuplicateOf = utils$2.toObjectSet([
  'age', 'authorization', 'content-length', 'content-type', 'etag',
  'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  'referer', 'retry-after', 'user-agent'
]);

/**
 * Parse headers into an object
 *
 * ```
 * Date: Wed, 27 Aug 2014 08:58:49 GMT
 * Content-Type: application/json
 * Connection: keep-alive
 * Transfer-Encoding: chunked
 * ```
 *
 * @param {String} rawHeaders Headers needing to be parsed
 *
 * @returns {Object} Headers parsed into an object
 */
const parseHeaders = rawHeaders => {
  const parsed = {};
  let key;
  let val;
  let i;

  rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
    i = line.indexOf(':');
    key = line.substring(0, i).trim().toLowerCase();
    val = line.substring(i + 1).trim();

    if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
      return;
    }

    if (key === 'set-cookie') {
      if (parsed[key]) {
        parsed[key].push(val);
      } else {
        parsed[key] = [val];
      }
    } else {
      parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
    }
  });

  return parsed;
};

'use strict';

const $internals = Symbol('internals');

function normalizeHeader(header) {
  return header && String(header).trim().toLowerCase();
}

function normalizeValue(value) {
  if (value === false || value == null) {
    return value;
  }

  return utils$2.isArray(value) ? value.map(normalizeValue) : String(value);
}

function parseTokens(str) {
  const tokens = Object.create(null);
  const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  let match;

  while ((match = tokensRE.exec(str))) {
    tokens[match[1]] = match[2];
  }

  return tokens;
}

const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());

function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
  if (utils$2.isFunction(filter)) {
    return filter.call(this, value, header);
  }

  if (isHeaderNameFilter) {
    value = header;
  }

  if (!utils$2.isString(value)) return;

  if (utils$2.isString(filter)) {
    return value.indexOf(filter) !== -1;
  }

  if (utils$2.isRegExp(filter)) {
    return filter.test(value);
  }
}

function formatHeader(header) {
  return header.trim()
    .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
      return char.toUpperCase() + str;
    });
}

function buildAccessors(obj, header) {
  const accessorName = utils$2.toCamelCase(' ' + header);

  ['get', 'set', 'has'].forEach(methodName => {
    Object.defineProperty(obj, methodName + accessorName, {
      value: function(arg1, arg2, arg3) {
        return this[methodName].call(this, header, arg1, arg2, arg3);
      },
      configurable: true
    });
  });
}

let AxiosHeaders$1 = class AxiosHeaders {
  constructor(headers) {
    headers && this.set(headers);
  }

  set(header, valueOrRewrite, rewrite) {
    const self = this;

    function setHeader(_value, _header, _rewrite) {
      const lHeader = normalizeHeader(_header);

      if (!lHeader) {
        throw new Error('header name must be a non-empty string');
      }

      const key = utils$2.findKey(self, lHeader);

      if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
        self[key || _header] = normalizeValue(_value);
      }
    }

    const setHeaders = (headers, _rewrite) =>
      utils$2.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));

    if (utils$2.isPlainObject(header) || header instanceof this.constructor) {
      setHeaders(header, valueOrRewrite);
    } else if(utils$2.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
      setHeaders(parseHeaders(header), valueOrRewrite);
    } else if (utils$2.isObject(header) && utils$2.isIterable(header)) {
      let obj = {}, dest, key;
      for (const entry of header) {
        if (!utils$2.isArray(entry)) {
          throw TypeError('Object iterator must return a key-value pair');
        }

        obj[key = entry[0]] = (dest = obj[key]) ?
          (utils$2.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]]) : entry[1];
      }

      setHeaders(obj, valueOrRewrite);
    } else {
      header != null && setHeader(valueOrRewrite, header, rewrite);
    }

    return this;
  }

  get(header, parser) {
    header = normalizeHeader(header);

    if (header) {
      const key = utils$2.findKey(this, header);

      if (key) {
        const value = this[key];

        if (!parser) {
          return value;
        }

        if (parser === true) {
          return parseTokens(value);
        }

        if (utils$2.isFunction(parser)) {
          return parser.call(this, value, key);
        }

        if (utils$2.isRegExp(parser)) {
          return parser.exec(value);
        }

        throw new TypeError('parser must be boolean|regexp|function');
      }
    }
  }

  has(header, matcher) {
    header = normalizeHeader(header);

    if (header) {
      const key = utils$2.findKey(this, header);

      return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
    }

    return false;
  }

  delete(header, matcher) {
    const self = this;
    let deleted = false;

    function deleteHeader(_header) {
      _header = normalizeHeader(_header);

      if (_header) {
        const key = utils$2.findKey(self, _header);

        if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
          delete self[key];

          deleted = true;
        }
      }
    }

    if (utils$2.isArray(header)) {
      header.forEach(deleteHeader);
    } else {
      deleteHeader(header);
    }

    return deleted;
  }

  clear(matcher) {
    const keys = Object.keys(this);
    let i = keys.length;
    let deleted = false;

    while (i--) {
      const key = keys[i];
      if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
        delete this[key];
        deleted = true;
      }
    }

    return deleted;
  }

  normalize(format) {
    const self = this;
    const headers = {};

    utils$2.forEach(this, (value, header) => {
      const key = utils$2.findKey(headers, header);

      if (key) {
        self[key] = normalizeValue(value);
        delete self[header];
        return;
      }

      const normalized = format ? formatHeader(header) : String(header).trim();

      if (normalized !== header) {
        delete self[header];
      }

      self[normalized] = normalizeValue(value);

      headers[normalized] = true;
    });

    return this;
  }

  concat(...targets) {
    return this.constructor.concat(this, ...targets);
  }

  toJSON(asStrings) {
    const obj = Object.create(null);

    utils$2.forEach(this, (value, header) => {
      value != null && value !== false && (obj[header] = asStrings && utils$2.isArray(value) ? value.join(', ') : value);
    });

    return obj;
  }

  [Symbol.iterator]() {
    return Object.entries(this.toJSON())[Symbol.iterator]();
  }

  toString() {
    return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
  }

  getSetCookie() {
    return this.get("set-cookie") || [];
  }

  get [Symbol.toStringTag]() {
    return 'AxiosHeaders';
  }

  static from(thing) {
    return thing instanceof this ? thing : new this(thing);
  }

  static concat(first, ...targets) {
    const computed = new this(first);

    targets.forEach((target) => computed.set(target));

    return computed;
  }

  static accessor(header) {
    const internals = this[$internals] = (this[$internals] = {
      accessors: {}
    });

    const accessors = internals.accessors;
    const prototype = this.prototype;

    function defineAccessor(_header) {
      const lHeader = normalizeHeader(_header);

      if (!accessors[lHeader]) {
        buildAccessors(prototype, _header);
        accessors[lHeader] = true;
      }
    }

    utils$2.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);

    return this;
  }
};

AxiosHeaders$1.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);

// reserved names hotfix
utils$2.reduceDescriptors(AxiosHeaders$1.prototype, ({value}, key) => {
  let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
  return {
    get: () => value,
    set(headerValue) {
      this[mapped] = headerValue;
    }
  }
});

utils$2.freezeMethods(AxiosHeaders$1);

'use strict';

/**
 * Transform the data for a request or a response
 *
 * @param {Array|Function} fns A single function or Array of functions
 * @param {?Object} response The response object
 *
 * @returns {*} The resulting transformed data
 */
function transformData(fns, response) {
  const config = this || defaults$1;
  const context = response || config;
  const headers = AxiosHeaders$1.from(context.headers);
  let data = context.data;

  utils$2.forEach(fns, function transform(fn) {
    data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
  });

  headers.normalize();

  return data;
}

'use strict';

function isCancel$1(value) {
  return !!(value && value.__CANCEL__);
}

'use strict';

let CanceledError$1 = class CanceledError extends AxiosError$1 {
  /**
   * A `CanceledError` is an object that is thrown when an operation is canceled.
   *
   * @param {string=} message The message.
   * @param {Object=} config The config.
   * @param {Object=} request The request.
   *
   * @returns {CanceledError} The created error.
   */
  constructor(message, config, request) {
    super(message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request);
    this.name = 'CanceledError';
    this.__CANCEL__ = true;
  }
};

'use strict';

/**
 * Resolve or reject a Promise based on response status.
 *
 * @param {Function} resolve A function that resolves the promise.
 * @param {Function} reject A function that rejects the promise.
 * @param {object} response The response.
 *
 * @returns {object} The response.
 */
function settle(resolve, reject, response) {
  const validateStatus = response.config.validateStatus;
  if (!response.status || !validateStatus || validateStatus(response.status)) {
    resolve(response);
  } else {
    reject(new AxiosError$1(
      'Request failed with status code ' + response.status,
      [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
      response.config,
      response.request,
      response
    ));
  }
}

'use strict';

function parseProtocol(url) {
  const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
  return match && match[1] || '';
}

'use strict';

/**
 * Calculate data maxRate
 * @param {Number} [samplesCount= 10]
 * @param {Number} [min= 1000]
 * @returns {Function}
 */
function speedometer(samplesCount, min) {
  samplesCount = samplesCount || 10;
  const bytes = new Array(samplesCount);
  const timestamps = new Array(samplesCount);
  let head = 0;
  let tail = 0;
  let firstSampleTS;

  min = min !== undefined ? min : 1000;

  return function push(chunkLength) {
    const now = Date.now();

    const startedAt = timestamps[tail];

    if (!firstSampleTS) {
      firstSampleTS = now;
    }

    bytes[head] = chunkLength;
    timestamps[head] = now;

    let i = tail;
    let bytesCount = 0;

    while (i !== head) {
      bytesCount += bytes[i++];
      i = i % samplesCount;
    }

    head = (head + 1) % samplesCount;

    if (head === tail) {
      tail = (tail + 1) % samplesCount;
    }

    if (now - firstSampleTS < min) {
      return;
    }

    const passed = startedAt && now - startedAt;

    return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
  };
}

/**
 * Throttle decorator
 * @param {Function} fn
 * @param {Number} freq
 * @return {Function}
 */
function throttle(fn, freq) {
  let timestamp = 0;
  let threshold = 1000 / freq;
  let lastArgs;
  let timer;

  const invoke = (args, now = Date.now()) => {
    timestamp = now;
    lastArgs = null;
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    fn(...args);
  };

  const throttled = (...args) => {
    const now = Date.now();
    const passed = now - timestamp;
    if ( passed >= threshold) {
      invoke(args, now);
    } else {
      lastArgs = args;
      if (!timer) {
        timer = setTimeout(() => {
          timer = null;
          invoke(lastArgs);
        }, threshold - passed);
      }
    }
  };

  const flush = () => lastArgs && invoke(lastArgs);

  return [throttled, flush];
}

const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
  let bytesNotified = 0;
  const _speedometer = speedometer(50, 250);

  return throttle(e => {
    const loaded = e.loaded;
    const total = e.lengthComputable ? e.total : undefined;
    const progressBytes = loaded - bytesNotified;
    const rate = _speedometer(progressBytes);
    const inRange = loaded <= total;

    bytesNotified = loaded;

    const data = {
      loaded,
      total,
      progress: total ? (loaded / total) : undefined,
      bytes: progressBytes,
      rate: rate ? rate : undefined,
      estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
      event: e,
      lengthComputable: total != null,
      [isDownloadStream ? 'download' : 'upload']: true
    };

    listener(data);
  }, freq);
};

const progressEventDecorator = (total, throttled) => {
  const lengthComputable = total != null;

  return [(loaded) => throttled[0]({
    lengthComputable,
    total,
    loaded
  }), throttled[1]];
};

const asyncDecorator = (fn) => (...args) => utils$2.asap(() => fn(...args));

const isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {
  url = new URL(url, platform.origin);

  return (
    origin.protocol === url.protocol &&
    origin.host === url.host &&
    (isMSIE || origin.port === url.port)
  );
})(
  new URL(platform.origin),
  platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
) : () => true;

const cookies = platform.hasStandardBrowserEnv ?

  // Standard browser envs support document.cookie
  {
    write(name, value, expires, path, domain, secure, sameSite) {
      if (typeof document === 'undefined') return;

      const cookie = [`${name}=${encodeURIComponent(value)}`];

      if (utils$2.isNumber(expires)) {
        cookie.push(`expires=${new Date(expires).toUTCString()}`);
      }
      if (utils$2.isString(path)) {
        cookie.push(`path=${path}`);
      }
      if (utils$2.isString(domain)) {
        cookie.push(`domain=${domain}`);
      }
      if (secure === true) {
        cookie.push('secure');
      }
      if (utils$2.isString(sameSite)) {
        cookie.push(`SameSite=${sameSite}`);
      }

      document.cookie = cookie.join('; ');
    },

    read(name) {
      if (typeof document === 'undefined') return null;
      const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
      return match ? decodeURIComponent(match[1]) : null;
    },

    remove(name) {
      this.write(name, '', Date.now() - 86400000, '/');
    }
  }

  :

  // Non-standard browser env (web workers, react-native) lack needed support.
  {
    write() {},
    read() {
      return null;
    },
    remove() {}
  };

'use strict';

/**
 * Determines whether the specified URL is absolute
 *
 * @param {string} url The URL to test
 *
 * @returns {boolean} True if the specified URL is absolute, otherwise false
 */
function isAbsoluteURL(url) {
  // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  // by any combination of letters, digits, plus, period, or hyphen.
  if (typeof url !== 'string') {
    return false;
  }

  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}

'use strict';

/**
 * Creates a new URL by combining the specified URLs
 *
 * @param {string} baseURL The base URL
 * @param {string} relativeURL The relative URL
 *
 * @returns {string} The combined URL
 */
function combineURLs(baseURL, relativeURL) {
  return relativeURL
    ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
    : baseURL;
}

'use strict';

/**
 * Creates a new URL by combining the baseURL with the requestedURL,
 * only when the requestedURL is not already an absolute URL.
 * If the requestURL is absolute, this function returns the requestedURL untouched.
 *
 * @param {string} baseURL The base URL
 * @param {string} requestedURL Absolute or relative URL to combine
 *
 * @returns {string} The combined full path
 */
function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
  let isRelativeUrl = !isAbsoluteURL(requestedURL);
  if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
}

"use strict";

const headersToObject = (thing) =>
  thing instanceof AxiosHeaders$1 ? { ...thing } : thing;

/**
 * Config-specific merge-function which creates a new config-object
 * by merging two configuration objects together.
 *
 * @param {Object} config1
 * @param {Object} config2
 *
 * @returns {Object} New object resulting from merging config2 to config1
 */
function mergeConfig$1(config1, config2) {
  // eslint-disable-next-line no-param-reassign
  config2 = config2 || {};
  const config = {};

  function getMergedValue(target, source, prop, caseless) {
    if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source)) {
      return utils$2.merge.call({ caseless }, target, source);
    } else if (utils$2.isPlainObject(source)) {
      return utils$2.merge({}, source);
    } else if (utils$2.isArray(source)) {
      return source.slice();
    }
    return source;
  }

  function mergeDeepProperties(a, b, prop, caseless) {
    if (!utils$2.isUndefined(b)) {
      return getMergedValue(a, b, prop, caseless);
    } else if (!utils$2.isUndefined(a)) {
      return getMergedValue(undefined, a, prop, caseless);
    }
  }

  // eslint-disable-next-line consistent-return
  function valueFromConfig2(a, b) {
    if (!utils$2.isUndefined(b)) {
      return getMergedValue(undefined, b);
    }
  }

  // eslint-disable-next-line consistent-return
  function defaultToConfig2(a, b) {
    if (!utils$2.isUndefined(b)) {
      return getMergedValue(undefined, b);
    } else if (!utils$2.isUndefined(a)) {
      return getMergedValue(undefined, a);
    }
  }

  // eslint-disable-next-line consistent-return
  function mergeDirectKeys(a, b, prop) {
    if (prop in config2) {
      return getMergedValue(a, b);
    } else if (prop in config1) {
      return getMergedValue(undefined, a);
    }
  }

  const mergeMap = {
    url: valueFromConfig2,
    method: valueFromConfig2,
    data: valueFromConfig2,
    baseURL: defaultToConfig2,
    transformRequest: defaultToConfig2,
    transformResponse: defaultToConfig2,
    paramsSerializer: defaultToConfig2,
    timeout: defaultToConfig2,
    timeoutMessage: defaultToConfig2,
    withCredentials: defaultToConfig2,
    withXSRFToken: defaultToConfig2,
    adapter: defaultToConfig2,
    responseType: defaultToConfig2,
    xsrfCookieName: defaultToConfig2,
    xsrfHeaderName: defaultToConfig2,
    onUploadProgress: defaultToConfig2,
    onDownloadProgress: defaultToConfig2,
    decompress: defaultToConfig2,
    maxContentLength: defaultToConfig2,
    maxBodyLength: defaultToConfig2,
    beforeRedirect: defaultToConfig2,
    transport: defaultToConfig2,
    httpAgent: defaultToConfig2,
    httpsAgent: defaultToConfig2,
    cancelToken: defaultToConfig2,
    socketPath: defaultToConfig2,
    responseEncoding: defaultToConfig2,
    validateStatus: mergeDirectKeys,
    headers: (a, b, prop) =>
      mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true),
  };

  utils$2.forEach(
    Object.keys({ ...config1, ...config2 }),
    function computeConfigValue(prop) {
      if (
        prop === "__proto__" ||
        prop === "constructor" ||
        prop === "prototype"
      )
        return;
      const merge = utils$2.hasOwnProp(mergeMap, prop)
        ? mergeMap[prop]
        : mergeDeepProperties;
      const configValue = merge(config1[prop], config2[prop], prop);
      (utils$2.isUndefined(configValue) && merge !== mergeDirectKeys) ||
        (config[prop] = configValue);
    },
  );

  return config;
}

const resolveConfig = (config) => {
  const newConfig = mergeConfig$1({}, config);

  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;

  newConfig.headers = headers = AxiosHeaders$1.from(headers);

  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);

  // HTTP basic authentication
  if (auth) {
    headers.set('Authorization', 'Basic ' +
      btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
    );
  }

  if (utils$2.isFormData(data)) {
    if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
      headers.setContentType(undefined); // browser handles it
    } else if (utils$2.isFunction(data.getHeaders)) {
      // Node.js FormData (like form-data package)
      const formHeaders = data.getHeaders();
      // Only set safe headers to avoid overwriting security headers
      const allowedHeaders = ['content-type', 'content-length'];
      Object.entries(formHeaders).forEach(([key, val]) => {
        if (allowedHeaders.includes(key.toLowerCase())) {
          headers.set(key, val);
        }
      });
    }
  }  

  // Add xsrf header
  // This is only done if running in a standard browser environment.
  // Specifically not if we're in a web worker, or react-native.

  if (platform.hasStandardBrowserEnv) {
    withXSRFToken && utils$2.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));

    if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
      // Add xsrf header
      const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);

      if (xsrfValue) {
        headers.set(xsrfHeaderName, xsrfValue);
      }
    }
  }

  return newConfig;
};

const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';

const xhrAdapter = isXHRAdapterSupported && function (config) {
  return new Promise(function dispatchXhrRequest(resolve, reject) {
    const _config = resolveConfig(config);
    let requestData = _config.data;
    const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
    let {responseType, onUploadProgress, onDownloadProgress} = _config;
    let onCanceled;
    let uploadThrottled, downloadThrottled;
    let flushUpload, flushDownload;

    function done() {
      flushUpload && flushUpload(); // flush events
      flushDownload && flushDownload(); // flush events

      _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);

      _config.signal && _config.signal.removeEventListener('abort', onCanceled);
    }

    let request = new XMLHttpRequest();

    request.open(_config.method.toUpperCase(), _config.url, true);

    // Set the request timeout in MS
    request.timeout = _config.timeout;

    function onloadend() {
      if (!request) {
        return;
      }
      // Prepare the response
      const responseHeaders = AxiosHeaders$1.from(
        'getAllResponseHeaders' in request && request.getAllResponseHeaders()
      );
      const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
        request.responseText : request.response;
      const response = {
        data: responseData,
        status: request.status,
        statusText: request.statusText,
        headers: responseHeaders,
        config,
        request
      };

      settle(function _resolve(value) {
        resolve(value);
        done();
      }, function _reject(err) {
        reject(err);
        done();
      }, response);

      // Clean up request
      request = null;
    }

    if ('onloadend' in request) {
      // Use onloadend if available
      request.onloadend = onloadend;
    } else {
      // Listen for ready state to emulate onloadend
      request.onreadystatechange = function handleLoad() {
        if (!request || request.readyState !== 4) {
          return;
        }

        // The request errored out and we didn't get a response, this will be
        // handled by onerror instead
        // With one exception: request that using file: protocol, most browsers
        // will return status as 0 even though it's a successful request
        if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
          return;
        }
        // readystate handler is calling before onerror or ontimeout handlers,
        // so we should call onloadend on the next 'tick'
        setTimeout(onloadend);
      };
    }

    // Handle browser request cancellation (as opposed to a manual cancellation)
    request.onabort = function handleAbort() {
      if (!request) {
        return;
      }

      reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request));

      // Clean up request
      request = null;
    };

    // Handle low level network errors
  request.onerror = function handleError(event) {
       // Browsers deliver a ProgressEvent in XHR onerror
       // (message may be empty; when present, surface it)
       // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
       const msg = event && event.message ? event.message : 'Network Error';
       const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config, request);
       // attach the underlying event for consumers who want details
       err.event = event || null;
       reject(err);
       request = null;
    };
    
    // Handle timeout
    request.ontimeout = function handleTimeout() {
      let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
      const transitional = _config.transitional || transitionalDefaults;
      if (_config.timeoutErrorMessage) {
        timeoutErrorMessage = _config.timeoutErrorMessage;
      }
      reject(new AxiosError$1(
        timeoutErrorMessage,
        transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
        config,
        request));

      // Clean up request
      request = null;
    };

    // Remove Content-Type if data is undefined
    requestData === undefined && requestHeaders.setContentType(null);

    // Add headers to the request
    if ('setRequestHeader' in request) {
      utils$2.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
        request.setRequestHeader(key, val);
      });
    }

    // Add withCredentials to request if needed
    if (!utils$2.isUndefined(_config.withCredentials)) {
      request.withCredentials = !!_config.withCredentials;
    }

    // Add responseType to request if needed
    if (responseType && responseType !== 'json') {
      request.responseType = _config.responseType;
    }

    // Handle progress if needed
    if (onDownloadProgress) {
      ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
      request.addEventListener('progress', downloadThrottled);
    }

    // Not all browsers support upload events
    if (onUploadProgress && request.upload) {
      ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));

      request.upload.addEventListener('progress', uploadThrottled);

      request.upload.addEventListener('loadend', flushUpload);
    }

    if (_config.cancelToken || _config.signal) {
      // Handle cancellation
      // eslint-disable-next-line func-names
      onCanceled = cancel => {
        if (!request) {
          return;
        }
        reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel);
        request.abort();
        request = null;
      };

      _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
      if (_config.signal) {
        _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
      }
    }

    const protocol = parseProtocol(_config.url);

    if (protocol && platform.protocols.indexOf(protocol) === -1) {
      reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config));
      return;
    }


    // Send the request
    request.send(requestData || null);
  });
};

const composeSignals = (signals, timeout) => {
  const {length} = (signals = signals ? signals.filter(Boolean) : []);

  if (timeout || length) {
    let controller = new AbortController();

    let aborted;

    const onabort = function (reason) {
      if (!aborted) {
        aborted = true;
        unsubscribe();
        const err = reason instanceof Error ? reason : this.reason;
        controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err));
      }
    };

    let timer = timeout && setTimeout(() => {
      timer = null;
      onabort(new AxiosError$1(`timeout of ${timeout}ms exceeded`, AxiosError$1.ETIMEDOUT));
    }, timeout);

    const unsubscribe = () => {
      if (signals) {
        timer && clearTimeout(timer);
        timer = null;
        signals.forEach(signal => {
          signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
        });
        signals = null;
      }
    };

    signals.forEach((signal) => signal.addEventListener('abort', onabort));

    const {signal} = controller;

    signal.unsubscribe = () => utils$2.asap(unsubscribe);

    return signal;
  }
};

const streamChunk = function* (chunk, chunkSize) {
  let len = chunk.byteLength;

  if (!chunkSize || len < chunkSize) {
    yield chunk;
    return;
  }

  let pos = 0;
  let end;

  while (pos < len) {
    end = pos + chunkSize;
    yield chunk.slice(pos, end);
    pos = end;
  }
};

const readBytes = async function* (iterable, chunkSize) {
  for await (const chunk of readStream(iterable)) {
    yield* streamChunk(chunk, chunkSize);
  }
};

const readStream = async function* (stream) {
  if (stream[Symbol.asyncIterator]) {
    yield* stream;
    return;
  }

  const reader = stream.getReader();
  try {
    for (;;) {
      const {done, value} = await reader.read();
      if (done) {
        break;
      }
      yield value;
    }
  } finally {
    await reader.cancel();
  }
};

const trackStream = (stream, chunkSize, onProgress, onFinish) => {
  const iterator = readBytes(stream, chunkSize);

  let bytes = 0;
  let done;
  let _onFinish = (e) => {
    if (!done) {
      done = true;
      onFinish && onFinish(e);
    }
  };

  return new ReadableStream({
    async pull(controller) {
      try {
        const {done, value} = await iterator.next();

        if (done) {
         _onFinish();
          controller.close();
          return;
        }

        let len = value.byteLength;
        if (onProgress) {
          let loadedBytes = bytes += len;
          onProgress(loadedBytes);
        }
        controller.enqueue(new Uint8Array(value));
      } catch (err) {
        _onFinish(err);
        throw err;
      }
    },
    cancel(reason) {
      _onFinish(reason);
      return iterator.return();
    }
  }, {
    highWaterMark: 2
  })
};

const DEFAULT_CHUNK_SIZE = 64 * 1024;

const {isFunction: isFunction$1} = utils$2;

const globalFetchAPI = (({Request, Response}) => ({
  Request, Response
}))(utils$2.global);

const {
  ReadableStream: ReadableStream$1, TextEncoder: TextEncoder$1
} = utils$2.global;


const test = (fn, ...args) => {
  try {
    return !!fn(...args);
  } catch (e) {
    return false
  }
};

const factory = (env) => {
  env = utils$2.merge.call({
    skipUndefined: true
  }, globalFetchAPI, env);

  const {fetch: envFetch, Request, Response} = env;
  const isFetchSupported = envFetch ? isFunction$1(envFetch) : typeof fetch === 'function';
  const isRequestSupported = isFunction$1(Request);
  const isResponseSupported = isFunction$1(Response);

  if (!isFetchSupported) {
    return false;
  }

  const isReadableStreamSupported = isFetchSupported && isFunction$1(ReadableStream$1);

  const encodeText = isFetchSupported && (typeof TextEncoder$1 === 'function' ?
      ((encoder) => (str) => encoder.encode(str))(new TextEncoder$1()) :
      async (str) => new Uint8Array(await new Request(str).arrayBuffer())
  );

  const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
    let duplexAccessed = false;

    const hasContentType = new Request(platform.origin, {
      body: new ReadableStream$1(),
      method: 'POST',
      get duplex() {
        duplexAccessed = true;
        return 'half';
      },
    }).headers.has('Content-Type');

    return duplexAccessed && !hasContentType;
  });

  const supportsResponseStream = isResponseSupported && isReadableStreamSupported &&
    test(() => utils$2.isReadableStream(new Response('').body));

  const resolvers = {
    stream: supportsResponseStream && ((res) => res.body)
  };

  isFetchSupported && ((() => {
    ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
      !resolvers[type] && (resolvers[type] = (res, config) => {
        let method = res && res[type];

        if (method) {
          return method.call(res);
        }

        throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config);
      });
    });
  })());

  const getBodyLength = async (body) => {
    if (body == null) {
      return 0;
    }

    if (utils$2.isBlob(body)) {
      return body.size;
    }

    if (utils$2.isSpecCompliantForm(body)) {
      const _request = new Request(platform.origin, {
        method: 'POST',
        body,
      });
      return (await _request.arrayBuffer()).byteLength;
    }

    if (utils$2.isArrayBufferView(body) || utils$2.isArrayBuffer(body)) {
      return body.byteLength;
    }

    if (utils$2.isURLSearchParams(body)) {
      body = body + '';
    }

    if (utils$2.isString(body)) {
      return (await encodeText(body)).byteLength;
    }
  };

  const resolveBodyLength = async (headers, body) => {
    const length = utils$2.toFiniteNumber(headers.getContentLength());

    return length == null ? getBodyLength(body) : length;
  };

  return async (config) => {
    let {
      url,
      method,
      data,
      signal,
      cancelToken,
      timeout,
      onDownloadProgress,
      onUploadProgress,
      responseType,
      headers,
      withCredentials = 'same-origin',
      fetchOptions
    } = resolveConfig(config);

    let _fetch = envFetch || fetch;

    responseType = responseType ? (responseType + '').toLowerCase() : 'text';

    let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);

    let request = null;

    const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
      composedSignal.unsubscribe();
    });

    let requestContentLength;

    try {
      if (
        onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
        (requestContentLength = await resolveBodyLength(headers, data)) !== 0
      ) {
        let _request = new Request(url, {
          method: 'POST',
          body: data,
          duplex: "half"
        });

        let contentTypeHeader;

        if (utils$2.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
          headers.setContentType(contentTypeHeader);
        }

        if (_request.body) {
          const [onProgress, flush] = progressEventDecorator(
            requestContentLength,
            progressEventReducer(asyncDecorator(onUploadProgress))
          );

          data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
        }
      }

      if (!utils$2.isString(withCredentials)) {
        withCredentials = withCredentials ? 'include' : 'omit';
      }

      // Cloudflare Workers throws when credentials are defined
      // see https://github.com/cloudflare/workerd/issues/902
      const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;

      const resolvedOptions = {
        ...fetchOptions,
        signal: composedSignal,
        method: method.toUpperCase(),
        headers: headers.normalize().toJSON(),
        body: data,
        duplex: "half",
        credentials: isCredentialsSupported ? withCredentials : undefined
      };

      request = isRequestSupported && new Request(url, resolvedOptions);

      let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));

      const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');

      if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
        const options = {};

        ['status', 'statusText', 'headers'].forEach(prop => {
          options[prop] = response[prop];
        });

        const responseContentLength = utils$2.toFiniteNumber(response.headers.get('content-length'));

        const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
          responseContentLength,
          progressEventReducer(asyncDecorator(onDownloadProgress), true)
        ) || [];

        response = new Response(
          trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
            flush && flush();
            unsubscribe && unsubscribe();
          }),
          options
        );
      }

      responseType = responseType || 'text';

      let responseData = await resolvers[utils$2.findKey(resolvers, responseType) || 'text'](response, config);

      !isStreamResponse && unsubscribe && unsubscribe();

      return await new Promise((resolve, reject) => {
        settle(resolve, reject, {
          data: responseData,
          headers: AxiosHeaders$1.from(response.headers),
          status: response.status,
          statusText: response.statusText,
          config,
          request
        });
      })
    } catch (err) {
      unsubscribe && unsubscribe();

      if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
        throw Object.assign(
          new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request, err && err.response),
          {
            cause: err.cause || err
          }
        )
      }

      throw AxiosError$1.from(err, err && err.code, config, request, err && err.response);
    }
  }
};

const seedCache = new Map();

const getFetch = (config) => {
  let env = (config && config.env) || {};
  const {fetch, Request, Response} = env;
  const seeds = [
    Request, Response, fetch
  ];

  let len = seeds.length, i = len,
    seed, target, map = seedCache;

  while (i--) {
    seed = seeds[i];
    target = map.get(seed);

    target === undefined && map.set(seed, target = (i ? new Map() : factory(env)));

    map = target;
  }

  return target;
};

const adapter = getFetch();

/**
 * Known adapters mapping.
 * Provides environment-specific adapters for Axios:
 * - `http` for Node.js
 * - `xhr` for browsers
 * - `fetch` for fetch API-based requests
 * 
 * @type {Object<string, Function|Object>}
 */
const knownAdapters = {
  http: httpAdapter,
  xhr: xhrAdapter,
  fetch: {
    get: getFetch,
  }
};

// Assign adapter names for easier debugging and identification
utils$2.forEach(knownAdapters, (fn, value) => {
  if (fn) {
    try {
      Object.defineProperty(fn, 'name', { value });
    } catch (e) {
      // eslint-disable-next-line no-empty
    }
    Object.defineProperty(fn, 'adapterName', { value });
  }
});

/**
 * Render a rejection reason string for unknown or unsupported adapters
 * 
 * @param {string} reason
 * @returns {string}
 */
const renderReason = (reason) => `- ${reason}`;

/**
 * Check if the adapter is resolved (function, null, or false)
 * 
 * @param {Function|null|false} adapter
 * @returns {boolean}
 */
const isResolvedHandle = (adapter) => utils$2.isFunction(adapter) || adapter === null || adapter === false;

/**
 * Get the first suitable adapter from the provided list.
 * Tries each adapter in order until a supported one is found.
 * Throws an AxiosError if no adapter is suitable.
 * 
 * @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
 * @param {Object} config - Axios request configuration
 * @throws {AxiosError} If no suitable adapter is available
 * @returns {Function} The resolved adapter function
 */
function getAdapter$1(adapters, config) {
  adapters = utils$2.isArray(adapters) ? adapters : [adapters];

  const { length } = adapters;
  let nameOrAdapter;
  let adapter;

  const rejectedReasons = {};

  for (let i = 0; i < length; i++) {
    nameOrAdapter = adapters[i];
    let id;

    adapter = nameOrAdapter;

    if (!isResolvedHandle(nameOrAdapter)) {
      adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];

      if (adapter === undefined) {
        throw new AxiosError$1(`Unknown adapter '${id}'`);
      }
    }

    if (adapter && (utils$2.isFunction(adapter) || (adapter = adapter.get(config)))) {
      break;
    }

    rejectedReasons[id || '#' + i] = adapter;
  }

  if (!adapter) {
    const reasons = Object.entries(rejectedReasons)
      .map(([id, state]) => `adapter ${id} ` +
        (state === false ? 'is not supported by the environment' : 'is not available in the build')
      );

    let s = length ?
      (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
      'as no adapter specified';

    throw new AxiosError$1(
      `There is no suitable adapter to dispatch the request ` + s,
      'ERR_NOT_SUPPORT'
    );
  }

  return adapter;
}

/**
 * Exports Axios adapters and utility to resolve an adapter
 */
const adapters$1 = {
  /**
   * Resolve an adapter from a list of adapter names or functions.
   * @type {Function}
   */
  getAdapter: getAdapter$1,

  /**
   * Exposes all known adapters
   * @type {Object<string, Function|Object>}
   */
  adapters: knownAdapters
};

'use strict';

/**
 * Throws a `CanceledError` if cancellation has been requested.
 *
 * @param {Object} config The config that is to be used for the request
 *
 * @returns {void}
 */
function throwIfCancellationRequested(config) {
  if (config.cancelToken) {
    config.cancelToken.throwIfRequested();
  }

  if (config.signal && config.signal.aborted) {
    throw new CanceledError$1(null, config);
  }
}

/**
 * Dispatch a request to the server using the configured adapter.
 *
 * @param {object} config The config that is to be used for the request
 *
 * @returns {Promise} The Promise to be fulfilled
 */
function dispatchRequest(config) {
  throwIfCancellationRequested(config);

  config.headers = AxiosHeaders$1.from(config.headers);

  // Transform request data
  config.data = transformData.call(
    config,
    config.transformRequest
  );

  if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
    config.headers.setContentType('application/x-www-form-urlencoded', false);
  }

  const adapter = adapters$1.getAdapter(config.adapter || defaults$1.adapter, config);

  return adapter(config).then(function onAdapterResolution(response) {
    throwIfCancellationRequested(config);

    // Transform response data
    response.data = transformData.call(
      config,
      config.transformResponse,
      response
    );

    response.headers = AxiosHeaders$1.from(response.headers);

    return response;
  }, function onAdapterRejection(reason) {
    if (!isCancel$1(reason)) {
      throwIfCancellationRequested(config);

      // Transform response data
      if (reason && reason.response) {
        reason.response.data = transformData.call(
          config,
          config.transformResponse,
          reason.response
        );
        reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
      }
    }

    return Promise.reject(reason);
  });
}

const VERSION$1 = "1.13.5";

'use strict';

const validators$1 = {};

// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
  validators$1[type] = function validator(thing) {
    return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
  };
});

const deprecatedWarnings = {};

/**
 * Transitional option validator
 *
 * @param {function|boolean?} validator - set to false if the transitional option has been removed
 * @param {string?} version - deprecated version / removed since version
 * @param {string?} message - some message with additional info
 *
 * @returns {function}
 */
validators$1.transitional = function transitional(validator, version, message) {
  function formatMessage(opt, desc) {
    return '[Axios v' + VERSION$1 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
  }

  // eslint-disable-next-line func-names
  return (value, opt, opts) => {
    if (validator === false) {
      throw new AxiosError$1(
        formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
        AxiosError$1.ERR_DEPRECATED
      );
    }

    if (version && !deprecatedWarnings[opt]) {
      deprecatedWarnings[opt] = true;
      // eslint-disable-next-line no-console
      console.warn(
        formatMessage(
          opt,
          ' has been deprecated since v' + version + ' and will be removed in the near future'
        )
      );
    }

    return validator ? validator(value, opt, opts) : true;
  };
};

validators$1.spelling = function spelling(correctSpelling) {
  return (value, opt) => {
    // eslint-disable-next-line no-console
    console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
    return true;
  }
};

/**
 * Assert object's properties type
 *
 * @param {object} options
 * @param {object} schema
 * @param {boolean?} allowUnknown
 *
 * @returns {object}
 */

function assertOptions(options, schema, allowUnknown) {
  if (typeof options !== 'object') {
    throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE);
  }
  const keys = Object.keys(options);
  let i = keys.length;
  while (i-- > 0) {
    const opt = keys[i];
    const validator = schema[opt];
    if (validator) {
      const value = options[opt];
      const result = value === undefined || validator(value, opt, options);
      if (result !== true) {
        throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE);
      }
      continue;
    }
    if (allowUnknown !== true) {
      throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION);
    }
  }
}

const validator = {
  assertOptions,
  validators: validators$1
};

'use strict';

const validators = validator.validators;

/**
 * Create a new instance of Axios
 *
 * @param {Object} instanceConfig The default config for the instance
 *
 * @return {Axios} A new instance of Axios
 */
let Axios$1 = class Axios {
  constructor(instanceConfig) {
    this.defaults = instanceConfig || {};
    this.interceptors = {
      request: new InterceptorManager(),
      response: new InterceptorManager()
    };
  }

  /**
   * Dispatch a request
   *
   * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
   * @param {?Object} config
   *
   * @returns {Promise} The Promise to be fulfilled
   */
  async request(configOrUrl, config) {
    try {
      return await this._request(configOrUrl, config);
    } catch (err) {
      if (err instanceof Error) {
        let dummy = {};

        Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());

        // slice off the Error: ... line
        const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
        try {
          if (!err.stack) {
            err.stack = stack;
            // match without the 2 top stack lines
          } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
            err.stack += '\n' + stack;
          }
        } catch (e) {
          // ignore the case where "stack" is an un-writable property
        }
      }

      throw err;
    }
  }

  _request(configOrUrl, config) {
    /*eslint no-param-reassign:0*/
    // Allow for axios('example/url'[, config]) a la fetch API
    if (typeof configOrUrl === 'string') {
      config = config || {};
      config.url = configOrUrl;
    } else {
      config = configOrUrl || {};
    }

    config = mergeConfig$1(this.defaults, config);

    const {transitional, paramsSerializer, headers} = config;

    if (transitional !== undefined) {
      validator.assertOptions(transitional, {
        silentJSONParsing: validators.transitional(validators.boolean),
        forcedJSONParsing: validators.transitional(validators.boolean),
        clarifyTimeoutError: validators.transitional(validators.boolean),
        legacyInterceptorReqResOrdering: validators.transitional(validators.boolean)
      }, false);
    }

    if (paramsSerializer != null) {
      if (utils$2.isFunction(paramsSerializer)) {
        config.paramsSerializer = {
          serialize: paramsSerializer
        };
      } else {
        validator.assertOptions(paramsSerializer, {
          encode: validators.function,
          serialize: validators.function
        }, true);
      }
    }

    // Set config.allowAbsoluteUrls
    if (config.allowAbsoluteUrls !== undefined) {
      // do nothing
    } else if (this.defaults.allowAbsoluteUrls !== undefined) {
      config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
    } else {
      config.allowAbsoluteUrls = true;
    }

    validator.assertOptions(config, {
      baseUrl: validators.spelling('baseURL'),
      withXsrfToken: validators.spelling('withXSRFToken')
    }, true);

    // Set config.method
    config.method = (config.method || this.defaults.method || 'get').toLowerCase();

    // Flatten headers
    let contextHeaders = headers && utils$2.merge(
      headers.common,
      headers[config.method]
    );

    headers && utils$2.forEach(
      ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
      (method) => {
        delete headers[method];
      }
    );

    config.headers = AxiosHeaders$1.concat(contextHeaders, headers);

    // filter out skipped interceptors
    const requestInterceptorChain = [];
    let synchronousRequestInterceptors = true;
    this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
      if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
        return;
      }

      synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;

      const transitional = config.transitional || transitionalDefaults;
      const legacyInterceptorReqResOrdering = transitional && transitional.legacyInterceptorReqResOrdering;

      if (legacyInterceptorReqResOrdering) {
        requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
      } else {
        requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
      }
    });

    const responseInterceptorChain = [];
    this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
      responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
    });

    let promise;
    let i = 0;
    let len;

    if (!synchronousRequestInterceptors) {
      const chain = [dispatchRequest.bind(this), undefined];
      chain.unshift(...requestInterceptorChain);
      chain.push(...responseInterceptorChain);
      len = chain.length;

      promise = Promise.resolve(config);

      while (i < len) {
        promise = promise.then(chain[i++], chain[i++]);
      }

      return promise;
    }

    len = requestInterceptorChain.length;

    let newConfig = config;

    while (i < len) {
      const onFulfilled = requestInterceptorChain[i++];
      const onRejected = requestInterceptorChain[i++];
      try {
        newConfig = onFulfilled(newConfig);
      } catch (error) {
        onRejected.call(this, error);
        break;
      }
    }

    try {
      promise = dispatchRequest.call(this, newConfig);
    } catch (error) {
      return Promise.reject(error);
    }

    i = 0;
    len = responseInterceptorChain.length;

    while (i < len) {
      promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
    }

    return promise;
  }

  getUri(config) {
    config = mergeConfig$1(this.defaults, config);
    const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
    return buildURL(fullPath, config.params, config.paramsSerializer);
  }
};

// Provide aliases for supported request methods
utils$2.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  /*eslint func-names:0*/
  Axios$1.prototype[method] = function(url, config) {
    return this.request(mergeConfig$1(config || {}, {
      method,
      url,
      data: (config || {}).data
    }));
  };
});

utils$2.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  /*eslint func-names:0*/

  function generateHTTPMethod(isForm) {
    return function httpMethod(url, data, config) {
      return this.request(mergeConfig$1(config || {}, {
        method,
        headers: isForm ? {
          'Content-Type': 'multipart/form-data'
        } : {},
        url,
        data
      }));
    };
  }

  Axios$1.prototype[method] = generateHTTPMethod();

  Axios$1.prototype[method + 'Form'] = generateHTTPMethod(true);
});

'use strict';

/**
 * A `CancelToken` is an object that can be used to request cancellation of an operation.
 *
 * @param {Function} executor The executor function.
 *
 * @returns {CancelToken}
 */
let CancelToken$1 = class CancelToken {
  constructor(executor) {
    if (typeof executor !== 'function') {
      throw new TypeError('executor must be a function.');
    }

    let resolvePromise;

    this.promise = new Promise(function promiseExecutor(resolve) {
      resolvePromise = resolve;
    });

    const token = this;

    // eslint-disable-next-line func-names
    this.promise.then(cancel => {
      if (!token._listeners) return;

      let i = token._listeners.length;

      while (i-- > 0) {
        token._listeners[i](cancel);
      }
      token._listeners = null;
    });

    // eslint-disable-next-line func-names
    this.promise.then = onfulfilled => {
      let _resolve;
      // eslint-disable-next-line func-names
      const promise = new Promise(resolve => {
        token.subscribe(resolve);
        _resolve = resolve;
      }).then(onfulfilled);

      promise.cancel = function reject() {
        token.unsubscribe(_resolve);
      };

      return promise;
    };

    executor(function cancel(message, config, request) {
      if (token.reason) {
        // Cancellation has already been requested
        return;
      }

      token.reason = new CanceledError$1(message, config, request);
      resolvePromise(token.reason);
    });
  }

  /**
   * Throws a `CanceledError` if cancellation has been requested.
   */
  throwIfRequested() {
    if (this.reason) {
      throw this.reason;
    }
  }

  /**
   * Subscribe to the cancel signal
   */

  subscribe(listener) {
    if (this.reason) {
      listener(this.reason);
      return;
    }

    if (this._listeners) {
      this._listeners.push(listener);
    } else {
      this._listeners = [listener];
    }
  }

  /**
   * Unsubscribe from the cancel signal
   */

  unsubscribe(listener) {
    if (!this._listeners) {
      return;
    }
    const index = this._listeners.indexOf(listener);
    if (index !== -1) {
      this._listeners.splice(index, 1);
    }
  }

  toAbortSignal() {
    const controller = new AbortController();

    const abort = (err) => {
      controller.abort(err);
    };

    this.subscribe(abort);

    controller.signal.unsubscribe = () => this.unsubscribe(abort);

    return controller.signal;
  }

  /**
   * Returns an object that contains a new `CancelToken` and a function that, when called,
   * cancels the `CancelToken`.
   */
  static source() {
    let cancel;
    const token = new CancelToken(function executor(c) {
      cancel = c;
    });
    return {
      token,
      cancel
    };
  }
};

'use strict';

/**
 * Syntactic sugar for invoking a function and expanding an array for arguments.
 *
 * Common use case would be to use `Function.prototype.apply`.
 *
 *  ```js
 *  function f(x, y, z) {}
 *  const args = [1, 2, 3];
 *  f.apply(null, args);
 *  ```
 *
 * With `spread` this example can be re-written.
 *
 *  ```js
 *  spread(function(x, y, z) {})([1, 2, 3]);
 *  ```
 *
 * @param {Function} callback
 *
 * @returns {Function}
 */
function spread$1(callback) {
  return function wrap(arr) {
    return callback.apply(null, arr);
  };
}

'use strict';

/**
 * Determines whether the payload is an error thrown by Axios
 *
 * @param {*} payload The value to test
 *
 * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
 */
function isAxiosError$1(payload) {
  return utils$2.isObject(payload) && (payload.isAxiosError === true);
}

const HttpStatusCode$1 = {
  Continue: 100,
  SwitchingProtocols: 101,
  Processing: 102,
  EarlyHints: 103,
  Ok: 200,
  Created: 201,
  Accepted: 202,
  NonAuthoritativeInformation: 203,
  NoContent: 204,
  ResetContent: 205,
  PartialContent: 206,
  MultiStatus: 207,
  AlreadyReported: 208,
  ImUsed: 226,
  MultipleChoices: 300,
  MovedPermanently: 301,
  Found: 302,
  SeeOther: 303,
  NotModified: 304,
  UseProxy: 305,
  Unused: 306,
  TemporaryRedirect: 307,
  PermanentRedirect: 308,
  BadRequest: 400,
  Unauthorized: 401,
  PaymentRequired: 402,
  Forbidden: 403,
  NotFound: 404,
  MethodNotAllowed: 405,
  NotAcceptable: 406,
  ProxyAuthenticationRequired: 407,
  RequestTimeout: 408,
  Conflict: 409,
  Gone: 410,
  LengthRequired: 411,
  PreconditionFailed: 412,
  PayloadTooLarge: 413,
  UriTooLong: 414,
  UnsupportedMediaType: 415,
  RangeNotSatisfiable: 416,
  ExpectationFailed: 417,
  ImATeapot: 418,
  MisdirectedRequest: 421,
  UnprocessableEntity: 422,
  Locked: 423,
  FailedDependency: 424,
  TooEarly: 425,
  UpgradeRequired: 426,
  PreconditionRequired: 428,
  TooManyRequests: 429,
  RequestHeaderFieldsTooLarge: 431,
  UnavailableForLegalReasons: 451,
  InternalServerError: 500,
  NotImplemented: 501,
  BadGateway: 502,
  ServiceUnavailable: 503,
  GatewayTimeout: 504,
  HttpVersionNotSupported: 505,
  VariantAlsoNegotiates: 506,
  InsufficientStorage: 507,
  LoopDetected: 508,
  NotExtended: 510,
  NetworkAuthenticationRequired: 511,
  WebServerIsDown: 521,
  ConnectionTimedOut: 522,
  OriginIsUnreachable: 523,
  TimeoutOccurred: 524,
  SslHandshakeFailed: 525,
  InvalidSslCertificate: 526,
};

Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
  HttpStatusCode$1[value] = key;
});

'use strict';

/**
 * Create an instance of Axios
 *
 * @param {Object} defaultConfig The default config for the instance
 *
 * @returns {Axios} A new instance of Axios
 */
function createInstance(defaultConfig) {
  const context = new Axios$1(defaultConfig);
  const instance = bind(Axios$1.prototype.request, context);

  // Copy axios.prototype to instance
  utils$2.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});

  // Copy context to instance
  utils$2.extend(instance, context, null, {allOwnKeys: true});

  // Factory for creating new instances
  instance.create = function create(instanceConfig) {
    return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
  };

  return instance;
}

// Create the default instance to be exported
const axios = createInstance(defaults$1);

// Expose Axios class to allow class inheritance
axios.Axios = Axios$1;

// Expose Cancel & CancelToken
axios.CanceledError = CanceledError$1;
axios.CancelToken = CancelToken$1;
axios.isCancel = isCancel$1;
axios.VERSION = VERSION$1;
axios.toFormData = toFormData$1;

// Expose AxiosError class
axios.AxiosError = AxiosError$1;

// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;

// Expose all/spread
axios.all = function all(promises) {
  return Promise.all(promises);
};

axios.spread = spread$1;

// Expose isAxiosError
axios.isAxiosError = isAxiosError$1;

// Expose mergeConfig
axios.mergeConfig = mergeConfig$1;

axios.AxiosHeaders = AxiosHeaders$1;

axios.formToJSON = thing => formDataToJSON(utils$2.isHTMLForm(thing) ? new FormData(thing) : thing);

axios.getAdapter = adapters$1.getAdapter;

axios.HttpStatusCode = HttpStatusCode$1;

axios.default = axios;

// This module is intended to unwrap Axios default export as named.
// Keep top-level export same with static properties
// so that it can keep same with es module or cjs
const {
  Axios,
  AxiosError,
  CanceledError,
  isCancel,
  CancelToken,
  VERSION,
  all,
  Cancel,
  isAxiosError,
  spread,
  toFormData,
  AxiosHeaders,
  HttpStatusCode,
  formToJSON,
  getAdapter,
  mergeConfig
} = axios;

const CACHE_INVALIDATION_THROTTLE_MS = 30 * 1000;
const CACHE_BUST_PARAM = "force_update";
const KNOWN_INDEXED_DB_NAMES = ["workbox-expiration", "workbox-background-sync", "pleno", "truckwash"];

let lastErrorInvalidationAt = 0;

const browserWindow = () => (typeof window !== "undefined" ? window : null);
const browserNavigator = () => (typeof navigator !== "undefined" ? navigator : null);

const clearStorage = (storage) => {
  try {
    storage?.clear();
    return true;
  } catch {
    return false;
  }
};

const clearCacheStorage = async () => {
  const win = browserWindow();
  if (!win?.caches) {
    return [];
  }

  const cacheNames = await win.caches.keys();
  await Promise.all(cacheNames.map((cacheName) => win.caches.delete(cacheName)));
  return cacheNames;
};

const updateServiceWorkers = async () => {
  const nav = browserNavigator();
  if (!nav?.serviceWorker?.getRegistrations) {
    return 0;
  }

  const registrations = await nav.serviceWorker.getRegistrations();
  await Promise.all(
    registrations.map((registration) => (typeof registration.update === "function" ? registration.update() : null))
  );
  return registrations.length;
};

const unregisterServiceWorkers = async () => {
  const nav = browserNavigator();
  if (!nav?.serviceWorker?.getRegistrations) {
    return 0;
  }

  const registrations = await nav.serviceWorker.getRegistrations();
  await Promise.all(registrations.map((registration) => registration.unregister()));
  return registrations.length;
};

const browserIndexedDb = () => {
  const win = browserWindow();
  if (win?.indexedDB) {
    return win.indexedDB;
  }

  return typeof indexedDB !== "undefined" ? indexedDB : null;
};

const deleteIndexedDatabase = (indexedDb, databaseName) =>
  new Promise((resolve) => {
    if (!indexedDb || !databaseName) {
      resolve(false);
      return;
    }

    try {
      const request = indexedDb.deleteDatabase(databaseName);
      request.onsuccess = () => resolve(true);
      request.onerror = () => resolve(false);
      request.onblocked = () => resolve(false);
    } catch {
      resolve(false);
    }
  });

const getIndexedDatabaseNames = async (indexedDb) => {
  if (typeof indexedDb?.databases !== "function") {
    return KNOWN_INDEXED_DB_NAMES;
  }

  try {
    const databases = await indexedDb.databases();
    return [
      ...new Set(
        databases
          .map((database) => database?.name)
          .filter((databaseName) => typeof databaseName === "string" && databaseName.length > 0)
      ),
    ];
  } catch {
    return KNOWN_INDEXED_DB_NAMES;
  }
};

const deleteIndexedDatabases = async () => {
  const indexedDb = browserIndexedDb();
  if (!indexedDb) {
    return [];
  }

  const databaseNames = await getIndexedDatabaseNames(indexedDb);
  await Promise.all(databaseNames.map((databaseName) => deleteIndexedDatabase(indexedDb, databaseName)));
  return databaseNames;
};

const reloadWithCacheBust = () => {
  const win = browserWindow();
  if (!win?.location) {
    return;
  }

  const nextUrl = new URL(win.location.href);
  nextUrl.searchParams.set(CACHE_BUST_PARAM, String(Date.now()));
  win.location.replace(nextUrl.toString());
};

const invalidateFrontendCachesAfterError = async ({ now = Date.now() } = {}) => {
  if (lastErrorInvalidationAt > 0 && now - lastErrorInvalidationAt < CACHE_INVALIDATION_THROTTLE_MS) {
    return { skipped: true, cacheNames: [], serviceWorkerRegistrations: 0 };
  }

  lastErrorInvalidationAt = now;
  const [cacheNames, serviceWorkerRegistrations] = await Promise.all([clearCacheStorage(), updateServiceWorkers()]);
  return { skipped: false, cacheNames, serviceWorkerRegistrations };
};

const forceFrontendUpdateAndClearLocal = async ({ reload = reloadWithCacheBust } = {}) => {
  const win = browserWindow();
  clearStorage(win?.localStorage);
  clearStorage(win?.sessionStorage);

  const [cacheNames, serviceWorkerRegistrations, indexedDatabaseNames] = await Promise.all([
    clearCacheStorage(),
    unregisterServiceWorkers(),
    deleteIndexedDatabases(),
  ]);

  reload();
  return { cacheNames, serviceWorkerRegistrations, indexedDatabaseNames };
};

const __resetFrontendMaintenanceForTests = () => {
  lastErrorInvalidationAt = 0;
};

const normalizeOrigin = (value) => {
  const raw = String(value || "").trim();
  if (!raw) {
    return "";
  }
  try {
    return new URL(raw).origin;
  } catch {
    return "";
  }
};

const browserOrigin$1 = () => {
  if (typeof window !== "undefined" && window.location?.origin) {
    return window.location.origin;
  }
  return "";
};

const configuredTrustedOrigins = () =>
  [
    browserOrigin$1(),
    ...ALLOWED_ORIGINS,
    ...RELEASE_TRUSTED_ORIGINS,
    API_URL,
    RELEASE_MANAGER_CONTROL_API_URL,
    ...RELEASE_MANAGER_CONTROL_API_FALLBACK_URLS,
    RELEASE_PUBLIC_GATEWAY_API_URL,
    DEFAULT_LEGACY_API_URL,
    DEFAULT_PUBLIC_GATEWAY_API_URL,
    DEFAULT_STABLE_API_URL,
  ]
    .map(normalizeOrigin)
    .filter(Boolean);

const trustedReleaseOrigins = () => Array.from(new Set(configuredTrustedOrigins()));

const isTrustedReleaseOrigin = (value) => {
  const origin = normalizeOrigin(value);
  return Boolean(origin) && trustedReleaseOrigins().includes(origin);
};

const isRelativeReleaseUrl = (value) => {
  const raw = String(value || "").trim();
  return Boolean(raw) && raw.startsWith("/") && !raw.startsWith("//");
};

const isTrustedReleaseUrl = (value, { allowRelative = true } = {}) => {
  if (allowRelative && isRelativeReleaseUrl(value)) {
    return true;
  }
  return isTrustedReleaseOrigin(value);
};

const sameOriginReleaseUrl = (value, expectedBaseUrl) => {
  const resolvedOrigin = normalizeOrigin(value);
  const expectedOrigin = normalizeOrigin(expectedBaseUrl);
  return Boolean(resolvedOrigin && expectedOrigin && resolvedOrigin === expectedOrigin);
};

const RELEASE_TRACE_STORAGE_KEY = "release_trace_id";
const RELEASE_CHANNEL_SELECTION_STORAGE_KEY$2 = "release_channel_selected_slug";
const browserStorage$2 = () => {
  if (typeof window === "undefined") {
    return null;
  }
  try {
    return window.localStorage || null;
  } catch {
    return null;
  }
};
const normalizeIdentifier = (value, maxLength = 128) => String(value || "").trim().replace(/[^a-zA-Z0-9_.:-]/g, "").slice(0, Math.max(1, maxLength));
const normalizeReleaseChannelSlug$2 = (value) => String(value || "").trim().toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 64);
const selectedReleaseChannelSlugFromStorage = () => normalizeReleaseChannelSlug$2(browserStorage$2()?.getItem(RELEASE_CHANNEL_SELECTION_STORAGE_KEY$2) || "");
const releaseTraceIdFromStorage = () => normalizeIdentifier(browserStorage$2()?.getItem(RELEASE_TRACE_STORAGE_KEY) || "", 64);
const fallbackFrontendVersion = () => normalizeIdentifier(undefined                                 || undefined                                 || "unknown", 128);
const buildReleaseHeaders = ({
  traceId = "",
  channelSlug = "",
  frontendVersion = ""
} = {}) => {
  const headers = {};
  const normalizedTraceId = normalizeIdentifier(traceId || releaseTraceIdFromStorage(), 64);
  const normalizedChannelSlug = normalizeReleaseChannelSlug$2(channelSlug || selectedReleaseChannelSlugFromStorage());
  const normalizedFrontendVersion = normalizeIdentifier(frontendVersion || fallbackFrontendVersion(), 128);
  if (normalizedTraceId) {
    headers["X-Release-Trace"] = normalizedTraceId;
  }
  if (normalizedChannelSlug) {
    headers["X-Release-Channel"] = normalizedChannelSlug;
  }
  if (normalizedFrontendVersion) {
    headers["X-Frontend-Version"] = normalizedFrontendVersion;
  }
  return headers;
};

const TRACE_STORAGE_KEY = RELEASE_TRACE_STORAGE_KEY;
const MAX_QUEUE_SIZE = 50;
const MAX_FRONTEND_FAILURE_BUFFER_SIZE = 50;
const FRONTEND_FAILURE_EVENT_TYPES = /* @__PURE__ */ new Set([
  "vue_component_error",
  "vue_component_warning",
  "window_error",
  "unhandled_rejection"
]);
const RELEASE_RUNTIME_SOURCES = /* @__PURE__ */ new Set(["local", "deployment"]);
const RELEASE_RUNTIME_REQUESTED_SOURCES = /* @__PURE__ */ new Set(["local", "deployment", "auto"]);
const normalizeRuntimeSource = (value) => {
  const source = String(value || "").trim().toLowerCase();
  return RELEASE_RUNTIME_SOURCES.has(source) ? source : "";
};
const normalizeRuntimeRequestedSource = (value) => {
  const source = String(value || "").trim().toLowerCase();
  return RELEASE_RUNTIME_REQUESTED_SOURCES.has(source) ? source : "";
};
const createTraceId = () => {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID().replace(/-/g, "");
  }
  return `${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`.slice(0, 32);
};
const readTraceId = () => {
  if (typeof window === "undefined") {
    return createTraceId();
  }
  try {
    const stored = window.localStorage.getItem(TRACE_STORAGE_KEY);
    if (stored) {
      return stored;
    }
    const next = createTraceId();
    window.localStorage.setItem(TRACE_STORAGE_KEY, next);
    return next;
  } catch {
    return createTraceId();
  }
};
const releaseRuntimeStateMutable = reactive({
  source: null,
  requestedSource: null,
  traceId: readTraceId(),
  channel: null,
  availableChannels: [],
  versions: {
    frontend: null,
    api: null,
    service_set: null,
    bundle_id: null,
    bundle: null
  },
  frontendBaseUrl: null,
  apiBaseUrl: null,
  availability: {
    configured: true,
    missing: [],
    status: "ready",
    explicit: false
  },
  capturePolicy: {
    enabled: false,
    capture_level: "metadata",
    all_failure_metadata: true,
    retention_days: 14
  },
  generatedAt: null
});
let pendingEvents = [];
let recentFrontendFailureEvents = [];
let flushTimer = null;
let customTransport = null;
const releaseRuntimeState = readonly(releaseRuntimeStateMutable);
const hasOwn$1 = (value, key) => Boolean(value && Object.prototype.hasOwnProperty.call(value, key));
const normalizeReadinessMissingValues$1 = (missing = []) => Array.from(
  new Set(
    (Array.isArray(missing) ? missing : []).map((value) => String(value || "").trim()).filter(
      (value) => value && !["release_bundle", "frontend_version", "frontend_base_url", "frontend_entry"].includes(value)
    )
  )
);
const normalizeRuntimeBaseUrl = (value, { allowRelative = true } = {}) => {
  const raw = String(value || "").trim().replace(/\/+$/, "");
  if (!raw || !isTrustedReleaseUrl(raw, { allowRelative })) {
    return null;
  }
  if (raw.startsWith("/") && !raw.startsWith("//")) {
    return raw;
  }
  if (/^https?:\/\//i.test(raw)) {
    return raw;
  }
  return null;
};
const runtimeUrls = (runtime = {}) => {
  const urls = runtime?.urls && typeof runtime.urls === "object" ? runtime.urls : {};
  return {
    frontendBaseUrl: normalizeRuntimeBaseUrl(runtime.frontend_base_url ?? urls.frontend_base_url, {
      allowRelative: false
    }),
    apiBaseUrl: normalizeRuntimeBaseUrl(runtime.api_base_url ?? urls.api_base_url)
  };
};
const hasExplicitReleaseRuntime$1 = (runtime) => Boolean(
  runtime?.availability && typeof runtime.availability === "object" && runtime.availability.explicit !== false
) || hasOwn$1(runtime, "versions");
const configureReleaseRuntime = (runtime = {}) => {
  if (!runtime || typeof runtime !== "object") {
    return releaseRuntimeStateMutable;
  }
  const runtimeSource = normalizeRuntimeSource(runtime.source);
  if (runtimeSource) {
    releaseRuntimeStateMutable.source = runtimeSource;
  }
  const requestedSource = normalizeRuntimeRequestedSource(runtime.requested_source || runtime.requestedSource);
  if (requestedSource) {
    releaseRuntimeStateMutable.requestedSource = requestedSource;
  } else if (runtimeSource) {
    releaseRuntimeStateMutable.requestedSource = runtimeSource;
  }
  if (runtime.trace_id) {
    releaseRuntimeStateMutable.traceId = String(runtime.trace_id);
    try {
      window.localStorage.setItem(TRACE_STORAGE_KEY, releaseRuntimeStateMutable.traceId);
    } catch {
    }
  }
  releaseRuntimeStateMutable.channel = runtime.channel || null;
  releaseRuntimeStateMutable.availableChannels = Array.isArray(runtime.available_channels) ? runtime.available_channels : Array.isArray(runtime.availableChannels) ? runtime.availableChannels : [];
  releaseRuntimeStateMutable.versions = {
    frontend: runtime?.versions?.frontend || null,
    api: runtime?.versions?.api || null,
    service_set: runtime?.versions?.service_set || null,
    bundle_id: runtime?.versions?.bundle_id || null,
    bundle: runtime?.versions?.bundle || null
  };
  const urls = runtimeUrls(runtime);
  releaseRuntimeStateMutable.frontendBaseUrl = urls.frontendBaseUrl;
  releaseRuntimeStateMutable.apiBaseUrl = urls.apiBaseUrl;
  const channel = runtime.channel || null;
  const isDefaultChannel = channel?.default_channel === true || channel?.default_channel === 1 || String(channel?.slug || "") === "stable";
  const missingReleaseContent = [];
  if (!isDefaultChannel && hasOwn$1(runtime, "versions")) {
    if (!runtime?.versions?.api) {
      missingReleaseContent.push("api_version");
    } else if (!urls.apiBaseUrl) {
      missingReleaseContent.push("api_base_url");
    }
  }
  releaseRuntimeStateMutable.availability = runtime.availability ? (() => {
    const missing = normalizeReadinessMissingValues$1(runtime.availability.missing);
    let configured = missing.length === 0;
    if (!configured) {
      configured = runtime.availability.configured !== false && runtime.availability.status !== "unconfigured";
    }
    const status = configured && ["", "unconfigured", "missing_target"].includes(String(runtime.availability.status || "")) ? "ready" : runtime.availability.status || (configured ? "ready" : "unconfigured");
    return {
      ...runtime.availability,
      configured,
      missing,
      status,
      explicit: true
    };
  })() : hasExplicitReleaseRuntime$1(runtime) ? {
    configured: missingReleaseContent.length === 0,
    missing: missingReleaseContent,
    status: missingReleaseContent.length === 0 ? "ready" : "unconfigured",
    explicit: true
  } : {
    configured: true,
    missing: [],
    status: "ready",
    explicit: false
  };
  releaseRuntimeStateMutable.capturePolicy = {
    enabled: Boolean(runtime?.capture_policy?.enabled),
    capture_level: runtime?.capture_policy?.capture_level || "metadata",
    all_failure_metadata: runtime?.capture_policy?.all_failure_metadata !== false,
    retention_days: Number(runtime?.capture_policy?.retention_days || 14)
  };
  releaseRuntimeStateMutable.generatedAt = runtime.generated_at || (/* @__PURE__ */ new Date()).toISOString();
  return releaseRuntimeStateMutable;
};
const getReleaseRuntimeApiBaseUrl = () => releaseRuntimeStateMutable.apiBaseUrl || API_URL;
const resolveReleaseApiUrl = (url = "") => {
  const value = String(url || "");
  if (/^https?:\/\//i.test(value)) {
    return rewriteReleaseApiUrl(value);
  }
  return `${getReleaseRuntimeApiBaseUrl().replace(/\/+$/, "")}/${value.replace(/^\/+/, "")}`;
};
const rewriteReleaseApiUrl = (url = "") => {
  const value = String(url || "");
  const runtimeApiUrl = releaseRuntimeStateMutable.apiBaseUrl;
  const defaultApiUrl = API_URL.replace(/\/+$/, "");
  if (!runtimeApiUrl || runtimeApiUrl === defaultApiUrl || !value) {
    return value;
  }
  if (value === defaultApiUrl) {
    return runtimeApiUrl;
  }
  if (value.startsWith(`${defaultApiUrl}/`)) {
    return `${runtimeApiUrl}${value.slice(defaultApiUrl.length)}`;
  }
  return value;
};
const SENSITIVE_PAYLOAD_KEY_PATTERN = /authorization|cookie|password|passwd|secret|token|api[_-]?key|session|credential|card|cpr|ssn|recaptcha/i;
const CAPTURE_DISABLED_BODY_PLACEHOLDER = "[capture-disabled]";
const truncateReleasePayloadString = (value) => value.length > 4e3 ? `${value.slice(0, 4e3)}
... [truncated]` : value;
const redactSerializedReleasePayload = (value, depth) => {
  const trimmed = value.trim();
  if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
    try {
      return truncateReleasePayloadString(JSON.stringify(redactReleasePayload(JSON.parse(value), depth + 1)));
    } catch {
    }
  }
  if (trimmed.includes("=") && !trimmed.includes("\n")) {
    const params = new URLSearchParams(trimmed);
    const entries = Array.from(params.entries());
    if (entries.length > 0) {
      let changed = false;
      const redactedParams = new URLSearchParams();
      for (const [key, item] of entries.slice(0, 80)) {
        if (SENSITIVE_PAYLOAD_KEY_PATTERN.test(key)) {
          redactedParams.append(key, "[redacted]");
          changed = true;
        } else {
          redactedParams.append(key, truncateReleasePayloadString(item));
        }
      }
      if (changed) {
        return truncateReleasePayloadString(redactedParams.toString());
      }
    }
  }
  return truncateReleasePayloadString(value);
};
const redactReleasePayload = (value, depth = 0) => {
  if (depth > 8) {
    return "[depth-limit]";
  }
  if (Array.isArray(value)) {
    return value.slice(0, 80).map((item) => redactReleasePayload(item, depth + 1));
  }
  if (value && typeof value === "object") {
    return Object.fromEntries(
      Object.entries(value).slice(0, 80).map(([key, item]) => {
        if (SENSITIVE_PAYLOAD_KEY_PATTERN.test(key)) {
          return [key, "[redacted]"];
        }
        return [key, redactReleasePayload(item, depth + 1)];
      })
    );
  }
  if (typeof value === "string") {
    return redactSerializedReleasePayload(value, depth);
  }
  return value;
};
const isFailureEvent = (type, severity) => {
  const normalizedType = String(type || "").toLowerCase();
  const normalizedSeverity = String(severity || "").toLowerCase();
  return normalizedSeverity === "error" || normalizedSeverity === "warning" || normalizedType.includes("error") || normalizedType.includes("failed") || normalizedType.includes("failure");
};
const shouldSendEvent = (type, severity) => {
  if (isFailureEvent(type, severity)) {
    return true;
  }
  return releaseRuntimeStateMutable.capturePolicy.enabled === true;
};
const omitCapturedBodiesWhenDisabled = (payload) => {
  if (!payload || typeof payload !== "object") {
    return payload;
  }
  const nextPayload = { ...payload };
  for (const key of ["request", "response"]) {
    if (nextPayload[key] && typeof nextPayload[key] === "object" && hasOwn$1(nextPayload[key], "data")) {
      nextPayload[key] = {
        ...nextPayload[key],
        data: CAPTURE_DISABLED_BODY_PLACEHOLDER
      };
    }
  }
  return nextPayload;
};
const sanitizeReleaseTimelinePayload = (type, severity, payload) => {
  if (isFailureEvent(type, severity) && !releaseRuntimeStateMutable.capturePolicy.enabled) {
    return omitCapturedBodiesWhenDisabled(payload);
  }
  return payload;
};
const recordReleaseTimelineEvent = (type, payload = {}, options = {}) => {
  const severity = options.severity || payload?.severity || "info";
  if (!shouldSendEvent(type, severity)) {
    return false;
  }
  const event = {
    type,
    severity,
    module_key: options.moduleKey || payload?.module_key || null,
    route: options.route || payload?.route || (typeof window !== "undefined" ? window.location.pathname : null),
    component: options.component || payload?.component || null,
    request_id: options.requestId || payload?.request_id || null,
    occurred_at: (/* @__PURE__ */ new Date()).toISOString(),
    payload: redactReleasePayload(sanitizeReleaseTimelinePayload(type, severity, payload))
  };
  if (FRONTEND_FAILURE_EVENT_TYPES.has(type)) {
    recentFrontendFailureEvents = [event, ...recentFrontendFailureEvents].slice(0, MAX_FRONTEND_FAILURE_BUFFER_SIZE);
  }
  pendingEvents = [...pendingEvents, event].slice(-MAX_QUEUE_SIZE);
  scheduleReleaseTimelineFlush();
  return true;
};
const getRecentFrontendFailureEvents = () => recentFrontendFailureEvents.map((event) => ({
  ...event,
  payload: redactReleasePayload(event.payload)
}));
const browserInfoFromUserAgent = (userAgent = "") => {
  const ua = String(userAgent || "");
  const matchers = [
    ["Edge", /Edg\/([\d.]+)/],
    ["Chrome", /Chrome\/([\d.]+)/],
    ["Firefox", /Firefox\/([\d.]+)/],
    ["Safari", /Version\/([\d.]+).*Safari/]
  ];
  for (const [name, pattern] of matchers) {
    const match = ua.match(pattern);
    if (match) {
      return { name, version: match[1] || null };
    }
  }
  return { name: "Unknown", version: null };
};
const osInfoFromUserAgent = (userAgent = "") => {
  const ua = String(userAgent || "");
  const matchers = [
    ["Windows", /Windows NT ([\d.]+)/],
    ["Android", /Android ([\d.]+)/],
    ["iOS", /(?:iPhone|iPad).*OS ([\d_]+)/],
    ["macOS", /Mac OS X ([\d_]+)/],
    ["Linux", /Linux/]
  ];
  for (const [name, pattern] of matchers) {
    const match = ua.match(pattern);
    if (match) {
      return { name, version: match[1] ? String(match[1]).replace(/_/g, ".") : null };
    }
  }
  return { name: "Unknown", version: null };
};
const currentDeviceType = () => {
  if (typeof window === "undefined") {
    return null;
  }
  const width = Number(window.innerWidth || 0);
  if (width > 0 && width < 769) {
    return "mobile";
  }
  if (width >= 769 && width < 1024) {
    return "tablet";
  }
  return "desktop";
};
const versionLabel = (version) => version?.version_label || version?.label || null;
const commitSha = (version) => version?.commit_sha || version?.commit || null;
const RELEASE_SERVICE_DEFINITIONS = Object.freeze([
  { key: "frontend", label: "Frontend", kind: "app" },
  { key: "api", label: "API", kind: "app" },
  { key: "database", label: "Database", kind: "data" },
  { key: "redis", label: "Redis", kind: "data" },
  { key: "minio", label: "MinIO", kind: "data" }
]);
const RELEASE_MISSING_LABELS = Object.freeze({
  release_bundle: "Release bundle",
  frontend_version: "Frontend version",
  frontend_base_url: "Frontend URL",
  api_version: "API version",
  api_base_url: "API URL",
  database_service: "Database service",
  redis_service: "Redis service",
  minio_service: "MinIO service"
});
const isPlainRecord = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value));
const firstFilledString = (...values) => {
  for (const value of values) {
    const normalized = String(value ?? "").trim();
    if (normalized) {
      return normalized;
    }
  }
  return "";
};
const releaseRuntimeUrlsForDisplay = (runtime = {}) => {
  const urls = isPlainRecord(runtime?.urls) ? runtime.urls : {};
  return {
    frontend: normalizeRuntimeBaseUrl(runtime.frontendBaseUrl ?? runtime.frontend_base_url ?? urls.frontend_base_url, {
      allowRelative: false
    }),
    api: normalizeRuntimeBaseUrl(runtime.apiBaseUrl ?? runtime.api_base_url ?? urls.api_base_url)
  };
};
const releaseRuntimeTraceId = (runtime = {}) => firstFilledString(runtime.traceId, runtime.trace_id);
const releaseRuntimeGeneratedAt = (runtime = {}) => firstFilledString(runtime.generatedAt, runtime.generated_at);
const releaseShortText = (value, length = 12) => {
  const normalized = firstFilledString(value);
  if (!normalized) {
    return "";
  }
  return normalized.length > length ? normalized.slice(0, length) : normalized;
};
const releaseCommitValue = (version = null) => {
  if (!isPlainRecord(version)) {
    return "";
  }
  const commit = version.commit;
  if (isPlainRecord(commit)) {
    return firstFilledString(commit.sha, commit.commit_sha);
  }
  return firstFilledString(version.commit_sha, commit);
};
const releaseVersionPrimaryText = (version = null, fallback = "Missing version") => {
  if (!isPlainRecord(version)) {
    return fallback;
  }
  return firstFilledString(version.version_label, version.tag, releaseShortText(releaseCommitValue(version)), fallback);
};
const releaseVersionSecondaryText = (version = null) => {
  if (!isPlainRecord(version)) {
    return "";
  }
  const parts = [];
  const commit = releaseShortText(releaseCommitValue(version));
  const repository = firstFilledString(version.repository);
  const branch = firstFilledString(version.branch);
  if (commit && commit !== firstFilledString(version.version_label, version.tag)) {
    parts.push(commit);
  }
  if (repository || branch) {
    parts.push(branch ? `${repository || "repository"}#${branch}` : repository);
  }
  return parts.join(" - ");
};
const releaseStatusTone = (status = "") => {
  const normalized = String(status || "").trim().toLowerCase();
  if ([
    "failed",
    "error",
    "critical",
    "service_unhealthy",
    "unhealthy",
    "degraded",
    "reconcile_failed",
    "restart_failed",
    "provision_blocked"
  ].includes(normalized)) {
    return "danger";
  }
  if ([
    "missing",
    "missing_value",
    "not_configured",
    "unconfigured",
    "deployment_in_progress",
    "warning",
    "pending",
    "queued",
    "running",
    "deploying",
    "building",
    "provisioning",
    "unknown"
  ].includes(normalized)) {
    return "warning";
  }
  return "ok";
};
const releaseServiceStatus = (service = null, fallback = "connected") => firstFilledString(service?.deployment_status, service?.availability_state, service?.status, service?.state, fallback);
const releaseServicePrimaryText = (service = null) => {
  if (!isPlainRecord(service)) {
    return "";
  }
  const name = firstFilledString(
    service.resource_name,
    service.label,
    service.coolify_service_uuid,
    service.health_url,
    service.repository
  );
  const id = Number(service.id || service.target_id || 0);
  return [name, id > 0 ? `#${id}` : ""].filter(Boolean).join(" ");
};
const releaseServiceSecondaryText = (service = null) => {
  if (!isPlainRecord(service)) {
    return "";
  }
  const parts = [];
  const resourceUuid = firstFilledString(service.resource_uuid);
  const coolifyServiceUuid = firstFilledString(service.coolify_service_uuid);
  const instanceLabel = firstFilledString(service.instance_label, service.coolify_instance_label);
  const repository = firstFilledString(service.repository);
  const branch = firstFilledString(service.branch);
  const replication = isPlainRecord(service.replication) ? service.replication : null;
  const replicationStatus = firstFilledString(replication?.last_status?.status, replication?.status);
  if (resourceUuid) {
    parts.push(`resource ${releaseShortText(resourceUuid)}`);
  }
  if (coolifyServiceUuid && coolifyServiceUuid !== resourceUuid) {
    parts.push(`service ${releaseShortText(coolifyServiceUuid)}`);
  }
  if (repository || branch) {
    parts.push(branch ? `${repository || "repository"}#${branch}` : repository);
  }
  if (instanceLabel) {
    parts.push(instanceLabel);
  }
  if (replicationStatus) {
    parts.push(`replication ${replicationStatus}`);
  }
  return parts.join(" - ");
};
const releaseServiceForKey = (serviceSet = null, key = "") => {
  if (!isPlainRecord(serviceSet)) {
    return null;
  }
  const stack = isPlainRecord(serviceSet.stack) ? serviceSet.stack : {};
  const dataServices = isPlainRecord(serviceSet.data_services) ? serviceSet.data_services : {};
  const targets = isPlainRecord(serviceSet.targets) ? serviceSet.targets : {};
  const service = stack[key] || dataServices[key] || targets[key] || null;
  return isPlainRecord(service) ? service : null;
};
const buildReleaseSessionSummary = (runtime = releaseRuntimeStateMutable, options = {}) => {
  const versions = isPlainRecord(runtime?.versions) ? runtime.versions : {};
  const channel = isPlainRecord(runtime?.channel) ? runtime.channel : null;
  const availability = isPlainRecord(runtime?.availability) ? runtime.availability : {};
  const missing = normalizeReadinessMissingValues$1(availability.missing);
  const missingLookup = new Set(missing);
  const isDefaultChannel = channel?.default_channel === true || channel?.default_channel === 1 || String(channel?.slug || "").toLowerCase() === "stable";
  const includeInfrastructureDetails = options?.includeInfrastructureDetails === true;
  const urls = includeInfrastructureDetails ? releaseRuntimeUrlsForDisplay(runtime) : { frontend: "", api: "" };
  const frontendVersion = isPlainRecord(versions.frontend) ? versions.frontend : null;
  const apiVersion = isPlainRecord(versions.api) ? versions.api : null;
  const bundle = isPlainRecord(versions.bundle) ? versions.bundle : null;
  const bundleId = versions.bundle_id || bundle?.id || null;
  const rawServiceSet = isPlainRecord(versions.service_set) ? versions.service_set : isPlainRecord(bundle?.service_set) ? bundle.service_set : null;
  const serviceSet = includeInfrastructureDetails ? rawServiceSet : null;
  const defaultSharedLabel = "Default/shared runtime";
  const missingLabels = missing.map((key) => RELEASE_MISSING_LABELS[key] || key.replace(/_/g, " "));
  const availabilityConfigured = missing.length === 0 ? true : availability.configured !== false && availability.status !== "unconfigured";
  const availabilityStatus = availabilityConfigured && ["", "unconfigured", "missing_target"].includes(String(availability.status || "")) ? "ready" : firstFilledString(availability.status, availabilityConfigured ? "ready" : "unconfigured");
  const buildAppRow = (key, label, version, url) => {
    const missingVersionKey = `${key}_version`;
    const missingUrlKey = `${key}_base_url`;
    const missingKey = missingLookup.has(missingVersionKey) ? missingVersionKey : missingLookup.has(missingUrlKey) ? missingUrlKey : "";
    const usesRegularFrontend = key === "frontend" && !missingKey && !version && !url && !isDefaultChannel;
    const fallback = isDefaultChannel ? defaultSharedLabel : usesRegularFrontend ? "Regular frontend" : `Missing ${label} version`;
    const status = missingKey ? "missing value" : usesRegularFrontend ? "regular" : isDefaultChannel && !version && !url ? "shared" : firstFilledString(version?.status, url ? "active" : "unknown");
    const primaryText = releaseVersionPrimaryText(version, fallback);
    const secondaryText = includeInfrastructureDetails ? releaseVersionSecondaryText(version) : "";
    const displayUrl = includeInfrastructureDetails ? url || "" : "";
    return {
      key,
      label,
      status,
      tone: missingKey ? "warning" : releaseStatusTone(status),
      primaryText,
      secondaryText,
      url: displayUrl,
      title: [primaryText, secondaryText, displayUrl].filter(Boolean).join(" - "),
      missingLabel: missingKey ? RELEASE_MISSING_LABELS[missingKey] || missingKey : ""
    };
  };
  const buildServiceRow = ({ key, label }) => {
    const service = releaseServiceForKey(serviceSet, key);
    const missingKey = missingLookup.has(`${key}_service`) ? `${key}_service` : "";
    if (service) {
      const status2 = releaseServiceStatus(service);
      return {
        key,
        label,
        status: status2,
        tone: releaseStatusTone(status2),
        primaryText: releaseServicePrimaryText(service) || "Connected service",
        secondaryText: releaseServiceSecondaryText(service),
        title: [
          releaseServicePrimaryText(service),
          releaseServiceSecondaryText(service),
          firstFilledString(service.health_url)
        ].filter(Boolean).join(" - "),
        missingLabel: ""
      };
    }
    const fallbackText = missingKey ? `Missing ${label} service` : defaultSharedLabel;
    const status = missingKey ? "missing" : "shared";
    return {
      key,
      label,
      status,
      tone: missingKey ? "warning" : "ok",
      primaryText: fallbackText,
      secondaryText: "",
      title: fallbackText,
      missingLabel: missingKey ? RELEASE_MISSING_LABELS[missingKey] || missingKey : ""
    };
  };
  return {
    channelLabel: firstFilledString(channel?.name, channel?.slug, isDefaultChannel ? "Stable" : "Unknown channel"),
    channelSlug: firstFilledString(channel?.slug),
    traceId: releaseRuntimeTraceId(runtime) || "unknown",
    generatedAt: releaseRuntimeGeneratedAt(runtime) || "unknown",
    availabilityStatus,
    availabilityTone: !availabilityConfigured || missing.length > 0 ? "warning" : releaseStatusTone(availabilityStatus),
    bundleLabel: bundleId ? `#${bundleId}${firstFilledString(bundle?.version_label) ? ` ${bundle.version_label}` : ""}` : defaultSharedLabel,
    bundleStatus: firstFilledString(bundle?.status, bundleId ? "active" : "shared"),
    serviceSetLabel: serviceSet ? firstFilledString(serviceSet.name, serviceSet.slug, serviceSet.id ? `#${serviceSet.id}` : "Connected") : rawServiceSet ? "Restricted to release operators" : defaultSharedLabel,
    missingLabels,
    appRows: [
      buildAppRow("frontend", "Frontend", frontendVersion, urls.frontend),
      buildAppRow("api", "API", apiVersion, urls.api)
    ],
    serviceRows: includeInfrastructureDetails || !rawServiceSet ? RELEASE_SERVICE_DEFINITIONS.map(buildServiceRow) : []
  };
};
const buildCurrentReleaseHeaders = () => {
  const frontendVersion = releaseRuntimeStateMutable.versions?.frontend || {};
  const fallbackFrontendVersion = undefined                                 || undefined                                 || "unknown";
  return buildReleaseHeaders({
    traceId: releaseRuntimeStateMutable.traceId,
    channelSlug: releaseRuntimeStateMutable.channel?.slug || "",
    frontendVersion: commitSha(frontendVersion) || versionLabel(frontendVersion) || fallbackFrontendVersion
  });
};
const buildReleaseTimelineContext = () => {
  const userAgent = typeof navigator !== "undefined" ? navigator.userAgent : "";
  const browser = browserInfoFromUserAgent(userAgent);
  const os = osInfoFromUserAgent(userAgent);
  const frontendVersion = releaseRuntimeStateMutable.versions?.frontend || {};
  const apiVersion = releaseRuntimeStateMutable.versions?.api || {};
  const fallbackFrontendVersion = undefined                                 || "unknown";
  return {
    trace_id: releaseRuntimeStateMutable.traceId,
    source: releaseRuntimeStateMutable.source,
    requested_source: releaseRuntimeStateMutable.requestedSource,
    channel_slug: releaseRuntimeStateMutable.channel?.slug || null,
    route_path: typeof window !== "undefined" ? window.location.pathname : null,
    device: {
      type: currentDeviceType()
    },
    browser,
    os,
    viewport: typeof window !== "undefined" ? {
      width: window.innerWidth,
      height: window.innerHeight,
      device_pixel_ratio: window.devicePixelRatio || 1
    } : null,
    frontend: {
      version_label: versionLabel(frontendVersion) || fallbackFrontendVersion,
      commit_sha: commitSha(frontendVersion) || fallbackFrontendVersion
    },
    api: {
      version_label: versionLabel(apiVersion),
      commit_sha: commitSha(apiVersion)
    },
    frontend_version: versionLabel(frontendVersion) || fallbackFrontendVersion,
    frontend_commit_sha: commitSha(frontendVersion) || fallbackFrontendVersion,
    api_version: versionLabel(apiVersion),
    api_commit_sha: commitSha(apiVersion)
  };
};
const scheduleReleaseTimelineFlush = () => {
  if (flushTimer !== null || typeof window === "undefined") {
    return;
  }
  flushTimer = window.setTimeout(() => {
    flushTimer = null;
    void flushReleaseTimelineEvents();
  }, 250);
};
const flushReleaseTimelineEvents = async () => {
  if (pendingEvents.length === 0) {
    return { accepted: 0 };
  }
  const events = pendingEvents;
  pendingEvents = [];
  const body = {
    events,
    context: buildReleaseTimelineContext()
  };
  try {
    if (typeof customTransport === "function") {
      return await customTransport(body);
    }
    const headers = {
      "Content-Type": "application/json",
      ...buildCurrentReleaseHeaders()
    };
    const token = typeof window !== "undefined" ? window.localStorage.getItem("token") : null;
    if (token) {
      headers.Authorization = `Bearer ${token}`;
    }
    const response = await fetch(resolveReleaseApiUrl("/release/timeline/events"), {
      method: "POST",
      headers,
      body: JSON.stringify(body),
      keepalive: true
    });
    return response.ok ? response.json().catch(() => ({ accepted: events.length })) : { accepted: 0 };
  } catch {
    pendingEvents = [...events, ...pendingEvents].slice(-MAX_QUEUE_SIZE);
    return { accepted: 0 };
  }
};
const installReleaseErrorInstrumentation = (app, router) => {
  const previousErrorHandler = app?.config?.errorHandler;
  const previousWarnHandler = app?.config?.warnHandler;
  const invalidateCachesAfterError = (context) => {
    invalidateFrontendCachesAfterError().catch((error) => {
      console.warn(`Failed to invalidate frontend caches after ${context}:`, error);
    });
  };
  if (app?.config) {
    app.config.errorHandler = (error, instance, info) => {
      invalidateCachesAfterError("Vue component error");
      recordReleaseTimelineEvent(
        "vue_component_error",
        {
          message: error?.message || String(error),
          stack: error?.stack || null,
          info,
          component: instance?.type?.name || instance?.type?.__name || null
        },
        {
          severity: "error",
          moduleKey: "frontend",
          component: instance?.type?.name || instance?.type?.__name || null
        }
      );
      if (typeof previousErrorHandler === "function") {
        previousErrorHandler(error, instance, info);
      } else {
        console.error(error);
      }
    };
    app.config.warnHandler = (message, instance, trace) => {
      if (releaseRuntimeStateMutable.capturePolicy.enabled) {
        recordReleaseTimelineEvent(
          "vue_component_warning",
          {
            message,
            trace,
            component: instance?.type?.name || instance?.type?.__name || null
          },
          {
            severity: "warning",
            moduleKey: "frontend",
            component: instance?.type?.name || instance?.type?.__name || null
          }
        );
      }
      if (typeof previousWarnHandler === "function") {
        previousWarnHandler(message, instance, trace);
      }
    };
  }
  if (typeof window !== "undefined") {
    window.addEventListener("error", (event) => {
      invalidateCachesAfterError("window error");
      recordReleaseTimelineEvent(
        "window_error",
        {
          message: event.message,
          filename: event.filename,
          lineno: event.lineno,
          colno: event.colno,
          stack: event.error?.stack || null
        },
        { severity: "error", moduleKey: "frontend" }
      );
    });
    window.addEventListener("unhandledrejection", (event) => {
      invalidateCachesAfterError("unhandled rejection");
      recordReleaseTimelineEvent(
        "unhandled_rejection",
        {
          message: event.reason?.message || String(event.reason),
          stack: event.reason?.stack || null
        },
        { severity: "error", moduleKey: "frontend" }
      );
    });
  }
  if (router?.afterEach) {
    router.afterEach((to, from) => {
      if (!releaseRuntimeStateMutable.capturePolicy.enabled) {
        return;
      }
      recordReleaseTimelineEvent(
        "route_change",
        {
          from: from?.fullPath || null,
          to: to?.fullPath || null
        },
        { severity: "info", moduleKey: "frontend", route: to?.fullPath || null }
      );
    });
  }
};
const __resetReleaseTimelineForTests = () => {
  pendingEvents = [];
  recentFrontendFailureEvents = [];
  if (flushTimer !== null && typeof window !== "undefined") {
    window.clearTimeout(flushTimer);
  }
  flushTimer = null;
  customTransport = null;
  releaseRuntimeStateMutable.source = null;
  releaseRuntimeStateMutable.requestedSource = null;
  releaseRuntimeStateMutable.traceId = "test-trace";
  releaseRuntimeStateMutable.channel = null;
  releaseRuntimeStateMutable.availableChannels = [];
  releaseRuntimeStateMutable.versions = { frontend: null, api: null, service_set: null, bundle_id: null, bundle: null };
  releaseRuntimeStateMutable.frontendBaseUrl = null;
  releaseRuntimeStateMutable.apiBaseUrl = null;
  releaseRuntimeStateMutable.availability = {
    configured: true,
    missing: [],
    status: "ready",
    explicit: false
  };
  releaseRuntimeStateMutable.capturePolicy = {
    enabled: false,
    capture_level: "metadata",
    all_failure_metadata: true,
    retention_days: 14
  };
  releaseRuntimeStateMutable.generatedAt = null;
};
const __setReleaseTimelineTransportForTests = (transport) => {
  customTransport = transport;
};

const cloneObject = (value) => ({ ...(value || {}) });

const queueConfig = {
  concurrencyByMethod: cloneObject(REQUEST_QUEUE_CONFIG.concurrency),
  spacingMs: REQUEST_QUEUE_CONFIG.spacingMs,
  retryByStatusCode: cloneObject(REQUEST_QUEUE_CONFIG.retryByStatusCode),
  retryDelayBaseMs: REQUEST_QUEUE_CONFIG.retryDelay.baseMs,
  retryDelayMaxMs: REQUEST_QUEUE_CONFIG.retryDelay.maxMs,
  retryDelayJitterMs: REQUEST_QUEUE_CONFIG.retryDelay.jitterMs,
  recentRequestsLimit: REQUEST_QUEUE_CONFIG.inspector.recentRequestsLimit,
  errorHistoryLimit: REQUEST_QUEUE_CONFIG.inspector.errorHistoryLimit,
  missingPermissionsLimit: REQUEST_QUEUE_CONFIG.inspector.missingPermissionsLimit,
  componentPermissionReportWindowMs: REQUEST_QUEUE_CONFIG.inspector.componentPermissionReportWindowMs,
  payloadMaxChars: REQUEST_QUEUE_CONFIG.inspector.payloadMaxChars,
};

const requestQueueStateMutable = reactive({
  batchId: 0,
  pending: 0,
  active: 0,
  batchTotal: 0,
  batchCompleted: 0,
  batchFailed: 0,
  activeRequests: [],
  recentRequests: [],
  requestInsights: {},
  errorRequests: [],
  missingPermissions: [],
  networkTotals: {
    outgoingRequests: 0,
    ingoingResponses: 0,
    outgoingBytes: 0,
    ingoingBytes: 0,
  },
});

const requestQueue = [];
const activeWorkersByKey = {};
let activeWorkers = 0;
let trackedActiveWorkers = 0;
let trackedPendingJobs = 0;
let requestIdCounter = 0;
let drainTimer = null;
let lastRequestStartedAt = 0;
const recentComponentPermissionReports = {};

const isQueueIdle = () => requestQueue.length === 0 && activeWorkers === 0;

const startBatchIfNeeded = () => {
  if (!isQueueIdle()) {
    return;
  }

  requestQueueStateMutable.batchId += 1;
  requestQueueStateMutable.batchTotal = 0;
  requestQueueStateMutable.batchCompleted = 0;
  requestQueueStateMutable.batchFailed = 0;
  requestQueueStateMutable.recentRequests = [];
};

const syncQueueCounters = () => {
  requestQueueStateMutable.pending = trackedPendingJobs;
  requestQueueStateMutable.active = trackedActiveWorkers;
};

const normalizeMethod = (value) => {
  if (typeof value !== "string" || value.trim().length === 0) {
    return "GET";
  }
  return value.trim().toUpperCase();
};

const normalizeQueueGroup = (value) => {
  if (typeof value !== "string") {
    return "";
  }

  return value.trim().toUpperCase();
};

const normalizeInsightKey = (value) => {
  if (typeof value !== "string") {
    return "";
  }

  return value.trim().toLowerCase();
};

const normalizeTraceContext = (value) => {
  if (typeof value === "string") {
    return { component: value.trim(), trace: null };
  }

  if (!value || typeof value !== "object") {
    return null;
  }

  const component = String(value.component || value.owner || value.source || "").trim();
  const trace = String(value.trace || value.componentTrace || value.stack || "").trim();
  if (!component && !trace) {
    return null;
  }

  return {
    component: component || null,
    trace: trace || null,
  };
};

const normalizeUrl = (value) => {
  if (typeof value !== "string" || value.trim().length === 0) {
    return "(unknown endpoint)";
  }
  return value.trim();
};

const redactHeaders = (headers) => {
  if (!headers || typeof headers !== "object") {
    return headers ?? null;
  }

  const normalized = {};
  Object.entries(headers).forEach(([key, value]) => {
    if (/authorization|x-api-key|token/i.test(String(key))) {
      normalized[key] = "***";
      return;
    }
    normalized[key] = value;
  });
  return normalized;
};

const toSafeText = (value) => {
  if (value === null || value === undefined) {
    return "";
  }

  let text;
  if (typeof value === "string") {
    text = value;
  } else {
    try {
      text = JSON.stringify(value, null, 2);
    } catch (_error) {
      text = String(value);
    }
  }

  const maxChars = Math.max(200, Number(queueConfig.payloadMaxChars) || 4000);
  if (text.length <= maxChars) {
    return text;
  }

  return `${text.slice(0, maxChars)}\n... [truncated]`;
};

const toRedactedPayload = (value) => redactReleasePayload(value);

const measureTextBytes = (value) => {
  const text = toSafeText(value);
  if (!text) {
    return 0;
  }

  if (typeof TextEncoder === "function") {
    return new TextEncoder().encode(text).length;
  }

  return text.length;
};

const estimateRequestBytes = (job, method, url) => measureTextBytes({
  method,
  url,
  params: job?.requestData?.params ?? null,
  data: job?.requestData?.data ?? null,
  headers: redactHeaders(job?.requestData?.headers ?? null),
});

const estimateResponseBytes = (response, fallbackMessage = null) => measureTextBytes({
  status: response?.status ?? null,
  statusText: response?.statusText ?? null,
  data: response?.data ?? fallbackMessage,
  headers: redactHeaders(response?.headers ?? null),
});

const addNetworkTotals = ({
  outgoingRequests = 0,
  ingoingResponses = 0,
  outgoingBytes = 0,
  ingoingBytes = 0,
} = {}) => {
  requestQueueStateMutable.networkTotals = {
    outgoingRequests: Number(requestQueueStateMutable.networkTotals?.outgoingRequests || 0)
      + Math.max(0, Number(outgoingRequests) || 0),
    ingoingResponses: Number(requestQueueStateMutable.networkTotals?.ingoingResponses || 0)
      + Math.max(0, Number(ingoingResponses) || 0),
    outgoingBytes: Number(requestQueueStateMutable.networkTotals?.outgoingBytes || 0)
      + Math.max(0, Number(outgoingBytes) || 0),
    ingoingBytes: Number(requestQueueStateMutable.networkTotals?.ingoingBytes || 0)
      + Math.max(0, Number(ingoingBytes) || 0),
  };
};

const parseJsonIfString = (value) => {
  if (typeof value !== "string") {
    return value;
  }

  const trimmedValue = value.trim();
  if (!trimmedValue.startsWith("{") && !trimmedValue.startsWith("[")) {
    return value;
  }

  try {
    return JSON.parse(trimmedValue);
  } catch (_error) {
    return value;
  }
};

const normalizeResponseData = (value) => {
  const parsed = parseJsonIfString(value);
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
    return parsed;
  }

  const parsedData = parseJsonIfString(parsed.data);
  if (parsedData === parsed.data) {
    return parsed;
  }

  return {
    ...parsed,
    data: parsedData,
  };
};

const extractMissingPermissions = (error) => {
  const responseData = normalizeResponseData(error?.response?.data);
  const messageCandidates = [
    responseData?.data?.message,
    responseData?.message,
    error?.message,
  ];
  const hasMissingPermissionMessage = messageCandidates.some((message) =>
    typeof message === "string" && message.toLowerCase().includes("missing permission")
  );

  if (!hasMissingPermissionMessage) {
    return [];
  }

  const permissions = responseData?.data?.permissions ?? responseData?.permissions ?? [];
  if (!Array.isArray(permissions)) {
    return [];
  }

  return permissions
    .map((permission) => String(permission || "").trim())
    .filter((permission) => permission.length > 0);
};

const getMethodConcurrencyLimit = (method) => {
  const normalizedMethod = normalizeMethod(method);
  const configuredLimit = queueConfig.concurrencyByMethod[normalizedMethod]
    ?? queueConfig.concurrencyByMethod.DEFAULT
    ?? 1;
  return Math.max(1, Number(configuredLimit) || 1);
};

const getJobConcurrencyKey = (job) => {
  const queueGroup = normalizeQueueGroup(job.queueGroup);
  if (queueGroup) {
    return `GROUP:${queueGroup}`;
  }

  return `METHOD:${normalizeMethod(job.method)}`;
};

const getJobConcurrencyLimit = (job) => {
  const configuredLimit = Number.parseInt(String(job.concurrencyLimit ?? ""), 10);
  if (Number.isInteger(configuredLimit) && configuredLimit > 0) {
    return configuredLimit;
  }

  return getMethodConcurrencyLimit(job.method);
};

const canRunJob = (job) => {
  const concurrencyKey = getJobConcurrencyKey(job);
  const activeForKey = Number(activeWorkersByKey[concurrencyKey] || 0);
  return activeForKey < getJobConcurrencyLimit(job);
};

const getNextRunnableJobIndex = () => {
  for (let index = 0; index < requestQueue.length; index += 1) {
    if (canRunJob(requestQueue[index])) {
      return index;
    }
  }
  return -1;
};

const clearDrainTimer = () => {
  if (drainTimer !== null) {
    clearTimeout(drainTimer);
    drainTimer = null;
  }
};

const scheduleDrain = (delayMs = 0) => {
  if (delayMs > 0) {
    if (drainTimer !== null) {
      return;
    }

    drainTimer = setTimeout(() => {
      drainTimer = null;
      void drainQueue();
    }, delayMs);
    return;
  }

  Promise.resolve().then(() => {
    void drainQueue();
  });
};

const wait$2 = (durationMs) => new Promise((resolve) => {
  setTimeout(resolve, Math.max(0, durationMs || 0));
});

const isAbortSignal = (signal) =>
  signal && typeof signal === "object" && typeof signal.aborted === "boolean";

const isRequestAbortError = (error) =>
  error?.name === "AbortError" || error?.name === "CanceledError" || error?.code === "ERR_CANCELED";

const createAbortError = () => {
  if (typeof DOMException === "function") {
    return new DOMException("Request aborted.", "AbortError");
  }

  const error = new Error("Request aborted.");
  error.name = "AbortError";
  error.code = "ERR_CANCELED";
  return error;
};

const isJobAborted = (job) => isAbortSignal(job?.signal) && job.signal.aborted === true;

const decrementBatchTotalForCanceledJob = () => {
  const completedOrFailed = Number(requestQueueStateMutable.batchCompleted || 0)
    + Number(requestQueueStateMutable.batchFailed || 0);
  requestQueueStateMutable.batchTotal = Math.max(
    completedOrFailed,
    Number(requestQueueStateMutable.batchTotal || 0) - 1
  );
};

const getErrorStatusCode = (error) => {
  const code = Number.parseInt(error?.response?.status, 10);
  return Number.isFinite(code) ? code : null;
};

const getResponseStatusCode = (response) => {
  const code = Number.parseInt(response?.status, 10);
  return Number.isFinite(code) ? code : null;
};

const getHeaderValue = (headers, name) => {
  if (!headers || typeof name !== "string") {
    return null;
  }

  if (typeof headers.get === "function") {
    const value = headers.get(name);
    return typeof value === "string" && value.length > 0 ? value : null;
  }

  const normalizedName = name.toLowerCase();
  const matchingKey = Object.keys(headers).find((key) => String(key).toLowerCase() === normalizedName);
  if (!matchingKey) {
    return null;
  }

  const value = headers[matchingKey];
  return typeof value === "string" && value.length > 0 ? value : null;
};

const getServerTimingHeader = (response) => getHeaderValue(response?.headers, "server-timing");

const getRetriesForStatusCode = (statusCode, retryByStatusCode) => {
  if (statusCode === null) {
    return 0;
  }

  const retries = Number(retryByStatusCode?.[statusCode] ?? 0);
  return Number.isFinite(retries) && retries > 0 ? Math.floor(retries) : 0;
};

const computeRetryDelayMs = (attemptNumber) => {
  const exponentialDelay = queueConfig.retryDelayBaseMs * (2 ** Math.max(0, attemptNumber));
  const cappedDelay = Math.min(queueConfig.retryDelayMaxMs, exponentialDelay);
  const jitter = queueConfig.retryDelayJitterMs > 0
    ? Math.floor(Math.random() * (queueConfig.retryDelayJitterMs + 1))
    : 0;
  return Math.max(0, cappedDelay + jitter);
};

const shouldRetryAttempt = (error, job, attemptNumber) => {
  if (isRequestAbortError(error) || isJobAborted(job)) {
    return false;
  }

  const statusCode = getErrorStatusCode(error);
  const retryByStatusCode = job.retryByStatusCode ?? queueConfig.retryByStatusCode;
  const retriesForCode = getRetriesForStatusCode(statusCode, retryByStatusCode);
  if (attemptNumber >= retriesForCode) {
    return false;
  }

  if (typeof job.shouldRetry === "function") {
    return job.shouldRetry(error, { attemptNumber, statusCode }) === true;
  }

  return true;
};

const executeJobWithRetries = async (job) => {
  let attemptCount = 0;
  const shouldRecordNetworkTotals = job.skipNetworkTotals !== true;

  while (true) {
    if (isJobAborted(job)) {
      throw createAbortError();
    }

    attemptCount += 1;
    const method = normalizeMethod(job.method);
    const url = normalizeUrl(job.url);
    if (shouldRecordNetworkTotals) {
      addNetworkTotals({
        outgoingRequests: 1,
        outgoingBytes: job.skipRequestByteAccounting ? 0 : estimateRequestBytes(job, method, url),
      });
    }
    try {
      const response = await job.requestFactory();
      if (shouldRecordNetworkTotals) {
        addNetworkTotals({
          ingoingResponses: 1,
          ingoingBytes: job.skipResponseByteAccounting ? 0 : estimateResponseBytes(response),
        });
      }
      return { response, attemptCount };
    } catch (error) {
      if (shouldRecordNetworkTotals && error?.response) {
        addNetworkTotals({
          ingoingResponses: 1,
          ingoingBytes: job.skipResponseByteAccounting
            ? 0
            : estimateResponseBytes(error.response, error?.message ?? "Request failed"),
        });
      }
      const attemptNumber = attemptCount - 1;
      if (!shouldRetryAttempt(error, job, attemptNumber)) {
        error.__queueAttemptCount = attemptCount;
        throw error;
      }

      const retryDelayMs = computeRetryDelayMs(attemptNumber);
      if (retryDelayMs > 0) {
        await wait$2(retryDelayMs);
      }
    }
  }
};

const upsertActiveRequest = (job, startedAt) => {
  const nextActive = [...requestQueueStateMutable.activeRequests, {
    id: job.id,
    method: normalizeMethod(job.method),
    queueGroup: normalizeQueueGroup(job.queueGroup) || null,
    url: job.url,
    queuedAt: job.enqueuedAt,
    startedAt,
  }];
  requestQueueStateMutable.activeRequests = nextActive;
};

const removeActiveRequest = (requestId) => {
  requestQueueStateMutable.activeRequests = requestQueueStateMutable.activeRequests.filter((item) => item.id !== requestId);
};

const pushRecentRequest = (entry) => {
  const limit = Math.max(1, Number(queueConfig.recentRequestsLimit) || 8);
  const next = [entry, ...requestQueueStateMutable.recentRequests];
  requestQueueStateMutable.recentRequests = next.slice(0, limit);
};

const upsertRequestInsight = (key, entry) => {
  const normalizedKey = normalizeInsightKey(key);
  if (!normalizedKey) {
    return;
  }

  requestQueueStateMutable.requestInsights[normalizedKey] = entry;
};

const pushErrorRequest = (entry) => {
  const limit = Math.max(1, Number(queueConfig.errorHistoryLimit) || 10);
  const next = [entry, ...requestQueueStateMutable.errorRequests];
  requestQueueStateMutable.errorRequests = next.slice(0, limit);
};

const pushMissingPermissions = (permissionEntries) => {
  if (!Array.isArray(permissionEntries) || permissionEntries.length === 0) {
    return;
  }

  const now = Date.now();
  const existing = [...requestQueueStateMutable.missingPermissions];
  permissionEntries.forEach((entry) => {
    const permission = String(entry?.permission || "").trim();
    const method = normalizeMethod(entry?.method);
    const url = normalizeUrl(entry?.url);
    const statusCode = entry?.statusCode ?? null;
    const source = entry?.source ?? null;
    if (!permission) {
      return;
    }

    const isComponentEntry = method === "COMPONENT";
    const index = existing.findIndex((item) => {
      if (item.permission !== permission) {
        return false;
      }
      if (isComponentEntry) {
        return normalizeMethod(item.method) === "COMPONENT";
      }
      return normalizeMethod(item.method) !== "COMPONENT";
    });
    if (index >= 0) {
      existing[index] = {
        ...existing[index],
        method,
        url,
        statusCode,
        source,
        count: Number(existing[index].count || 0) + 1,
        lastSeenAt: now,
      };
      return;
    }

    existing.push({
      permission,
      method,
      url,
      statusCode,
      source,
      count: 1,
      lastSeenAt: now,
    });
  });

  existing.sort((a, b) => {
    const aPriority = normalizeMethod(a?.method) === "COMPONENT" ? 1 : 0;
    const bPriority = normalizeMethod(b?.method) === "COMPONENT" ? 1 : 0;
    if (aPriority !== bPriority) {
      return aPriority - bPriority;
    }
    return Number(b.lastSeenAt || 0) - Number(a.lastSeenAt || 0);
  });
  const limit = Math.max(1, Number(queueConfig.missingPermissionsLimit) || 20);
  requestQueueStateMutable.missingPermissions = existing.slice(0, limit);
};

const reportComponentMissingPermission = (permission, options = {}) => {
  const normalizedPermission = String(permission || "").trim();
  if (!normalizedPermission) {
    return;
  }

  const source = String(options?.source || "").trim() || "Component";
  const now = Date.now();
  const reportWindowMs = Math.max(0, Number(queueConfig.componentPermissionReportWindowMs) || 0);
  const reportKey = `${normalizedPermission}::${source}`;
  const lastReportedAt = Number(recentComponentPermissionReports[reportKey] || 0);
  if (reportWindowMs > 0 && now - lastReportedAt < reportWindowMs) {
    return;
  }

  recentComponentPermissionReports[reportKey] = now;
  pushMissingPermissions([{
    permission: normalizedPermission,
    method: "COMPONENT",
    url: source,
    statusCode: null,
    source,
  }]);
};

const removePendingAbortListener = (job) => {
  if (
    job?.abortPendingListener
    && isAbortSignal(job.signal)
    && typeof job.signal.removeEventListener === "function"
  ) {
    job.signal.removeEventListener("abort", job.abortPendingListener);
  }
  if (job) {
    job.abortPendingListener = null;
  }
};

const rejectCanceledQueuedJob = (job) => {
  removePendingAbortListener(job);
  if (job.trackProgressCounters !== false) {
    trackedPendingJobs = Math.max(0, trackedPendingJobs - 1);
    decrementBatchTotalForCanceledJob();
    syncQueueCounters();
  }
  job.reject(createAbortError());
};

const runJob = (job) => {
  const method = normalizeMethod(job.method);
  const concurrencyKey = getJobConcurrencyKey(job);
  const queueGroup = normalizeQueueGroup(job.queueGroup) || null;
  const startedAt = Date.now();

  removePendingAbortListener(job);

  activeWorkers += 1;
  activeWorkersByKey[concurrencyKey] = Number(activeWorkersByKey[concurrencyKey] || 0) + 1;
  if (job.trackProgressCounters !== false) {
    trackedActiveWorkers += 1;
  }
  lastRequestStartedAt = startedAt;
  if (job.trackActiveRequest !== false) {
    upsertActiveRequest(job, startedAt);
  }
  if (job.trackProgressCounters !== false) {
    syncQueueCounters();
  }

  Promise.resolve()
    .then(() => executeJobWithRetries(job))
    .then(({ response, attemptCount }) => {
      const completedAt = Date.now();
      if (job.trackProgressCounters !== false) {
        requestQueueStateMutable.batchCompleted += 1;
      }
      const completedEntry = {
        id: job.id,
        method,
        queueGroup,
        url: job.url,
        success: true,
        statusCode: getResponseStatusCode(response),
        attemptCount,
        queuedAt: job.enqueuedAt,
        startedAt,
        completedAt,
        queueDurationMs: Math.max(0, startedAt - job.enqueuedAt),
        requestDurationMs: Math.max(0, completedAt - startedAt),
        serverTiming: getServerTimingHeader(response),
      };
      upsertRequestInsight(job.insightKey, completedEntry);
      if (job.recordRecentOnSuccess !== false) {
        pushRecentRequest(completedEntry);
      }
      job.resolve(response);
    })
    .catch((error) => {
      const completedAt = Date.now();
      if (isRequestAbortError(error)) {
        if (job.trackProgressCounters !== false) {
          decrementBatchTotalForCanceledJob();
        }
        job.reject(error);
        return;
      }

      const statusCode = getErrorStatusCode(error);
      const attemptCount = Math.max(1, Number(error?.__queueAttemptCount) || 1);
      const requestSnapshot = toRedactedPayload({
        method,
        url: job.url,
        params: job.requestData?.params ?? null,
        data: job.requestData?.data ?? null,
        headers: redactHeaders(job.requestData?.headers ?? null),
      });
      const responseSnapshot = toRedactedPayload({
        status: statusCode,
        statusText: error?.response?.statusText ?? null,
        code: error?.code ?? null,
        message: error?.message ?? "Request failed",
        data: error?.response?.data ?? null,
        headers: redactHeaders(error?.response?.headers ?? null),
      });
      if (job.trackProgressCounters !== false) {
        requestQueueStateMutable.batchFailed += 1;
      }
      const failedEntry = {
        id: job.id,
        method,
        queueGroup,
        url: job.url,
        success: false,
        statusCode,
        attemptCount,
        queuedAt: job.enqueuedAt,
        startedAt,
        completedAt,
        queueDurationMs: Math.max(0, startedAt - job.enqueuedAt),
        requestDurationMs: Math.max(0, completedAt - startedAt),
        serverTiming: getServerTimingHeader(error?.response),
      };
      upsertRequestInsight(job.insightKey, failedEntry);
      pushRecentRequest(failedEntry);
      pushErrorRequest({
        id: job.id,
        method,
        queueGroup,
        url: job.url,
        statusCode,
        attemptCount,
        requestDurationMs: Math.max(0, completedAt - startedAt),
        serverTiming: getServerTimingHeader(error?.response),
        request: requestSnapshot,
        response: responseSnapshot,
        traceContext: job.traceContext,
        requestText: toSafeText(requestSnapshot),
        responseText: toSafeText(responseSnapshot),
      });
      recordReleaseTimelineEvent("request_failed", {
        request_id: String(job.id),
        method,
        url: job.url,
        statusCode,
        attemptCount,
        requestDurationMs: Math.max(0, completedAt - startedAt),
        request: requestSnapshot,
        response: responseSnapshot,
        trace_context: job.traceContext,
      }, {
        severity: "error",
        moduleKey: "requestqueue",
        requestId: String(job.id),
        route: job.url,
        component: job.traceContext?.component || null,
      });

      const missingPermissions = extractMissingPermissions(error);
      pushMissingPermissions(
        missingPermissions.map((permission) => ({
          permission,
          method,
          url: job.url,
          statusCode,
        }))
      );
      job.reject(error);
    })
    .finally(() => {
      activeWorkers -= 1;
      if (job.trackProgressCounters !== false) {
        trackedActiveWorkers = Math.max(0, trackedActiveWorkers - 1);
      }
      activeWorkersByKey[concurrencyKey] = Math.max(0, Number(activeWorkersByKey[concurrencyKey] || 1) - 1);
      if (activeWorkersByKey[concurrencyKey] === 0) {
        delete activeWorkersByKey[concurrencyKey];
      }
      if (job.trackActiveRequest !== false) {
        removeActiveRequest(job.id);
      }
      if (job.trackProgressCounters !== false) {
        syncQueueCounters();
      }
      scheduleDrain();
    });
};

const drainQueue = async () => {
  while (requestQueue.length > 0) {
    const nextRunnableJobIndex = getNextRunnableJobIndex();
    if (nextRunnableJobIndex < 0) {
      return;
    }

    const elapsedSinceLastStart = Date.now() - lastRequestStartedAt;
    const waitMs = Math.max(0, queueConfig.spacingMs - elapsedSinceLastStart);

    if (waitMs > 0) {
      scheduleDrain(waitMs);
      return;
    }

    const [nextJob] = requestQueue.splice(nextRunnableJobIndex, 1);
    if (isJobAborted(nextJob)) {
      rejectCanceledQueuedJob(nextJob);
      continue;
    }

    if (nextJob.trackProgressCounters !== false) {
      trackedPendingJobs = Math.max(0, trackedPendingJobs - 1);
      syncQueueCounters();
    }
    runJob(nextJob);
  }
};

const enqueueRequest = (requestFactory, options = {}) => {
  if (typeof requestFactory !== "function") {
    throw new Error("enqueueRequest requires a function");
  }

  const method = normalizeMethod(options.method);
  const url = normalizeUrl(options.url);
  const signal = isAbortSignal(options.signal) ? options.signal : null;
  if (signal?.aborted) {
    return Promise.reject(createAbortError());
  }

  const trackProgressCounters = options.trackProgressCounters !== false;
  if (trackProgressCounters) {
    startBatchIfNeeded();
  }

  return new Promise((resolve, reject) => {
    const job = {
      id: ++requestIdCounter,
      requestFactory,
      resolve,
      reject,
      method,
      url,
      enqueuedAt: Date.now(),
      requestData: options.requestData || null,
      traceContext: normalizeTraceContext(options.traceContext),
      retryByStatusCode: options.retryByStatusCode || null,
      shouldRetry: typeof options.shouldRetry === "function" ? options.shouldRetry : null,
      queueGroup: normalizeQueueGroup(options.queueGroup),
      concurrencyLimit: options.concurrencyLimit || null,
      skipRequestByteAccounting: options.skipRequestByteAccounting === true,
      skipResponseByteAccounting: options.skipResponseByteAccounting === true,
      skipNetworkTotals: options.skipNetworkTotals === true,
      insightKey: normalizeInsightKey(options.insightKey),
      recordRecentOnSuccess: options.recordRecentOnSuccess !== false,
      trackActiveRequest: options.trackActiveRequest !== false,
      trackProgressCounters,
      signal,
      abortPendingListener: null,
    };

    if (signal && typeof signal.addEventListener === "function") {
      job.abortPendingListener = () => {
        const pendingIndex = requestQueue.findIndex((pendingJob) => pendingJob.id === job.id);
        if (pendingIndex < 0) {
          return;
        }

        requestQueue.splice(pendingIndex, 1);
        rejectCanceledQueuedJob(job);
        scheduleDrain();
      };
      signal.addEventListener("abort", job.abortPendingListener, { once: true });
    }

    requestQueue.push(job);
    if (job.trackProgressCounters !== false) {
      trackedPendingJobs += 1;
      requestQueueStateMutable.batchTotal += 1;
      syncQueueCounters();
    }
    scheduleDrain();
  });
};

const requestQueueState = readonly(requestQueueStateMutable);

const clearErrorRequests = () => {
  requestQueueStateMutable.errorRequests = [];
};

const clearMissingPermissions = () => {
  requestQueueStateMutable.missingPermissions = [];
  Object.keys(recentComponentPermissionReports).forEach((key) => {
    delete recentComponentPermissionReports[key];
  });
};

const __resetRequestQueueForTests = () => {
  requestQueue.forEach(removePendingAbortListener);
  requestQueue.length = 0;
  activeWorkers = 0;
  trackedActiveWorkers = 0;
  trackedPendingJobs = 0;
  requestIdCounter = 0;
  Object.keys(activeWorkersByKey).forEach((key) => delete activeWorkersByKey[key]);
  lastRequestStartedAt = 0;
  clearDrainTimer();

  requestQueueStateMutable.batchId = 0;
  requestQueueStateMutable.pending = 0;
  requestQueueStateMutable.active = 0;
  requestQueueStateMutable.batchTotal = 0;
  requestQueueStateMutable.batchCompleted = 0;
  requestQueueStateMutable.batchFailed = 0;
  requestQueueStateMutable.activeRequests = [];
  requestQueueStateMutable.recentRequests = [];
  requestQueueStateMutable.requestInsights = {};
  requestQueueStateMutable.errorRequests = [];
  requestQueueStateMutable.missingPermissions = [];
  requestQueueStateMutable.networkTotals = {
    outgoingRequests: 0,
    ingoingResponses: 0,
    outgoingBytes: 0,
    ingoingBytes: 0,
  };

  queueConfig.concurrencyByMethod = cloneObject(REQUEST_QUEUE_CONFIG.concurrency);
  queueConfig.spacingMs = 0;
  queueConfig.retryByStatusCode = cloneObject(REQUEST_QUEUE_CONFIG.retryByStatusCode);
  queueConfig.retryDelayBaseMs = 0;
  queueConfig.retryDelayMaxMs = 0;
  queueConfig.retryDelayJitterMs = 0;
  queueConfig.recentRequestsLimit = REQUEST_QUEUE_CONFIG.inspector.recentRequestsLimit;
  queueConfig.errorHistoryLimit = REQUEST_QUEUE_CONFIG.inspector.errorHistoryLimit;
  queueConfig.missingPermissionsLimit = REQUEST_QUEUE_CONFIG.inspector.missingPermissionsLimit;
  queueConfig.componentPermissionReportWindowMs = REQUEST_QUEUE_CONFIG.inspector.componentPermissionReportWindowMs;
  queueConfig.payloadMaxChars = REQUEST_QUEUE_CONFIG.inspector.payloadMaxChars;
  Object.keys(recentComponentPermissionReports).forEach((key) => {
    delete recentComponentPermissionReports[key];
  });
};

const __configureRequestQueueForTests = ({
  concurrencyByMethod,
  maxConcurrentGet,
  maxConcurrentOther,
  spacingMs,
  retryByStatusCode,
  retryDelayBaseMs,
  retryDelayMaxMs,
  retryDelayJitterMs,
  recentRequestsLimit,
  errorHistoryLimit,
  missingPermissionsLimit,
  componentPermissionReportWindowMs,
  payloadMaxChars,
} = {}) => {
  if (concurrencyByMethod && typeof concurrencyByMethod === "object") {
    queueConfig.concurrencyByMethod = {
      ...queueConfig.concurrencyByMethod,
      ...concurrencyByMethod,
    };
  }

  if (typeof maxConcurrentOther === "number" && maxConcurrentOther > 0) {
    const normalized = Math.max(1, Math.floor(maxConcurrentOther));
    queueConfig.concurrencyByMethod.DEFAULT = normalized;
    queueConfig.concurrencyByMethod.POST = normalized;
    queueConfig.concurrencyByMethod.PATCH = normalized;
    queueConfig.concurrencyByMethod.PUT = normalized;
    queueConfig.concurrencyByMethod.DELETE = normalized;
  }

  if (typeof maxConcurrentGet === "number" && maxConcurrentGet > 0) {
    queueConfig.concurrencyByMethod.GET = Math.max(1, Math.floor(maxConcurrentGet));
  }

  if (typeof spacingMs === "number" && spacingMs >= 0) {
    queueConfig.spacingMs = Math.floor(spacingMs);
  }

  if (retryByStatusCode && typeof retryByStatusCode === "object") {
    queueConfig.retryByStatusCode = cloneObject(retryByStatusCode);
  }

  if (typeof retryDelayBaseMs === "number" && retryDelayBaseMs >= 0) {
    queueConfig.retryDelayBaseMs = Math.floor(retryDelayBaseMs);
  }

  if (typeof retryDelayMaxMs === "number" && retryDelayMaxMs >= 0) {
    queueConfig.retryDelayMaxMs = Math.floor(retryDelayMaxMs);
  }

  if (typeof retryDelayJitterMs === "number" && retryDelayJitterMs >= 0) {
    queueConfig.retryDelayJitterMs = Math.floor(retryDelayJitterMs);
  }

  if (typeof recentRequestsLimit === "number" && recentRequestsLimit > 0) {
    queueConfig.recentRequestsLimit = Math.max(1, Math.floor(recentRequestsLimit));
  }

  if (typeof errorHistoryLimit === "number" && errorHistoryLimit > 0) {
    queueConfig.errorHistoryLimit = Math.max(1, Math.floor(errorHistoryLimit));
  }

  if (typeof missingPermissionsLimit === "number" && missingPermissionsLimit > 0) {
    queueConfig.missingPermissionsLimit = Math.max(1, Math.floor(missingPermissionsLimit));
  }

  if (typeof componentPermissionReportWindowMs === "number" && componentPermissionReportWindowMs >= 0) {
    queueConfig.componentPermissionReportWindowMs = Math.floor(componentPermissionReportWindowMs);
  }

  if (typeof payloadMaxChars === "number" && payloadMaxChars >= 200) {
    queueConfig.payloadMaxChars = Math.floor(payloadMaxChars);
  }
};

const _export_sfc = (sfc, props) => {
  const target = sfc.__vccOpts || sfc;
  for (const [key, val] of props) {
    target[key] = val;
  }
  return target;
};

/**
 * Get the selected customer number for X-Customer-Number header (used by subusers)
 * @returns {number|null}
 */
const getSelectedCustomerNumber$2 = () => {
  const stored = localStorage.getItem('selected_customer_number');
  return stored ? parseInt(stored) : null;
};

const MY_ACTIVE_WASH_ENDPOINT = '/modules/self-serve/lane/wash/my-active-wash';
const ACTIVE_WASH_STARTED_STATUSES = new Set(['MACHINE_RELAY_ENABLED', 'MACHINE_STARTED']);
const SELF_SERVE_HARDWARE_QUEUE_GROUP = 'SELF_SERVE_HARDWARE';
const POS_SCANNER_QUEUE_GROUP = 'POS_SCANNER';
const POS_STRIPE_QUEUE_GROUP = 'POS_STRIPE';
const FETCH_TRANSPORT = 'fetch';
const SELF_SERVE_HARDWARE_ENDPOINTS = [
  '/modules/self-serve/lane/command',
  '/modules/self-serve/lane/relay/',
  '/modules/self-serve/lane/gate/open',
  '/modules/self-serve/lane/force/machine',
];
const POS_LATENCY_QUEUE_RULES = [
  {
    endpoints: ['/modules/scanner/lpr'],
    queueGroup: POS_SCANNER_QUEUE_GROUP,
    concurrencyLimit: 1,
    retryByStatusCode: {},
    skipRequestByteAccounting: true,
    skipResponseByteAccounting: true,
    skipNetworkTotals: true,
    insightKey: 'scanner',
    recordRecentOnSuccess: false,
    trackActiveRequest: false,
    trackProgressCounters: false,
  },
  {
    endpoints: ['/modules/stripe/invoice'],
    queueGroup: POS_STRIPE_QUEUE_GROUP,
    concurrencyLimit: 2,
    retryByStatusCode: {},
  },
];

const normalizeStatus = (status) => String(status || '').trim().toUpperCase();

const parseDateTimeMs = (value) => {
  if (!value) {
    return null;
  }

  const timestamp = Date.parse(String(value));
  return Number.isFinite(timestamp) ? timestamp : null;
};

const hasActiveWashStartEvidence = (details) => {
  const session = details?.session || {};
  const status = normalizeStatus(session?.status ?? details?.status);

  return (
    ACTIVE_WASH_STARTED_STATUSES.has(status) ||
    session?.machine_relay_enabled === true ||
    session?.machine_start_triggered === true ||
    details?.machine_relay_enabled === true ||
    details?.machine_start_triggered === true ||
    parseDateTimeMs(session?.wash_started_at) !== null ||
    parseDateTimeMs(session?.machine_start_triggered_at) !== null ||
    parseDateTimeMs(session?.machine_relay_enabled_at) !== null
  );
};

const normalizeActiveWashResponse = (url, method, response) => {
  if (String(method || '').toUpperCase() !== 'GET' || !String(url || '').includes(MY_ACTIVE_WASH_ENDPOINT)) {
    return response;
  }

  const details = response?.data?.data;
  if (!details?.in_progress || hasActiveWashStartEvidence(details)) {
    return response;
  }

  return {
    ...response,
    data: {
      ...response.data,
      data: {
        ...details,
        in_progress: false,
      },
    },
  };
};

const isSelfServeHardwareMutation = (url, method) => {
  const normalizedMethod = String(method || '').trim().toUpperCase();
  if (normalizedMethod === 'GET') {
    return false;
  }

  const normalizedUrl = String(url || '');
  return SELF_SERVE_HARDWARE_ENDPOINTS.some((endpoint) => normalizedUrl.includes(endpoint));
};

const findPosLatencyQueueRule = (url, method) => {
  const normalizedMethod = String(method || '').trim().toUpperCase();
  if (normalizedMethod === 'GET') {
    return null;
  }

  const normalizedUrl = String(url || '');
  return POS_LATENCY_QUEUE_RULES.find((rule) =>
    rule.endpoints.some((endpoint) => normalizedUrl.includes(endpoint))
  ) || null;
};

const hasHeader = (headers, name) => {
  const normalizedName = String(name || '').trim().toLowerCase();
  if (!normalizedName || !headers || typeof headers !== 'object') {
    return false;
  }

  return Object.keys(headers).some((headerName) => String(headerName).toLowerCase() === normalizedName);
};

const parseFetchResponseData = async (response) => {
  const text = await response.text();
  if (!text) {
    return null;
  }

  const contentType = response.headers?.get?.('content-type') || '';
  if (
    contentType.toLowerCase().includes('application/json') ||
    text.trim().startsWith('{') ||
    text.trim().startsWith('[')
  ) {
    try {
      return JSON.parse(text);
    } catch (_error) {
      return text;
    }
  }

  return text;
};

const buildFetchBody = (method, data, headers) => {
  if (String(method || '').trim().toUpperCase() === 'GET' || data === undefined || data === null) {
    return undefined;
  }

  if (
    typeof Blob !== 'undefined' && data instanceof Blob ||
    typeof FormData !== 'undefined' && data instanceof FormData ||
    typeof URLSearchParams !== 'undefined' && data instanceof URLSearchParams ||
    typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer ||
    typeof ReadableStream !== 'undefined' && data instanceof ReadableStream ||
    typeof data === 'string'
  ) {
    return data;
  }

  if (!hasHeader(headers, 'Content-Type')) {
    headers['Content-Type'] = 'application/json';
  }
  return JSON.stringify(data);
};

const executeFetchRequest = async ({ method, url, data, signal, headers }) => {
  const fetchHeaders = { ...headers };
  const body = buildFetchBody(method, data, fetchHeaders);
  const response = await fetch(url, {
    method,
    headers: fetchHeaders,
    ...(body !== undefined ? { body } : {}),
    ...(signal ? { signal } : {}),
  });
  const responseData = await parseFetchResponseData(response);
  const axiosLikeResponse = {
    data: responseData,
    status: response.status,
    statusText: response.statusText,
    headers: response.headers,
    config: {
      data,
      headers: fetchHeaders,
      method,
      url,
    },
    request: null,
  };

  if (response.ok) {
    return axiosLikeResponse;
  }

  const error = new Error(`Request failed with status code ${response.status}`);
  error.name = 'AxiosError';
  error.response = axiosLikeResponse;
  throw error;
};

const buildRequestQueueOptions = (url, method, options = {}) => {
  const queueOptions = {
    retryByStatusCode: options?.retryByStatusCode,
    shouldRetry: options?.shouldRetry,
    queueGroup: options?.queueGroup,
    concurrencyLimit: options?.concurrencyLimit,
    skipRequestByteAccounting: options?.skipRequestByteAccounting,
    skipResponseByteAccounting: options?.skipResponseByteAccounting,
    skipNetworkTotals: options?.skipNetworkTotals,
    insightKey: options?.insightKey,
    recordRecentOnSuccess: options?.recordRecentOnSuccess,
    trackActiveRequest: options?.trackActiveRequest,
    trackProgressCounters: options?.trackProgressCounters,
    traceContext: options?.traceContext,
  };

  if (isSelfServeHardwareMutation(url, method)) {
    queueOptions.retryByStatusCode ??= {};
    queueOptions.queueGroup ??= SELF_SERVE_HARDWARE_QUEUE_GROUP;
    queueOptions.concurrencyLimit ??= 1;
  }

  const posQueueRule = findPosLatencyQueueRule(url, method);
  if (posQueueRule) {
    queueOptions.retryByStatusCode ??= posQueueRule.retryByStatusCode;
    queueOptions.queueGroup ??= posQueueRule.queueGroup;
    queueOptions.concurrencyLimit ??= posQueueRule.concurrencyLimit;
    queueOptions.skipRequestByteAccounting ??= posQueueRule.skipRequestByteAccounting;
    queueOptions.skipResponseByteAccounting ??= posQueueRule.skipResponseByteAccounting;
    queueOptions.skipNetworkTotals ??= posQueueRule.skipNetworkTotals;
    queueOptions.insightKey ??= posQueueRule.insightKey;
    queueOptions.recordRecentOnSuccess ??= posQueueRule.recordRecentOnSuccess;
    queueOptions.trackActiveRequest ??= posQueueRule.trackActiveRequest;
    queueOptions.trackProgressCounters ??= posQueueRule.trackProgressCounters;
  }

  return queueOptions;
};

const authenticatedRequest = (url, method, data, catchCallable = null, thenCallable = null, options = {}) => {
  const token = localStorage.getItem('token');
  if (!token) {
    //throw new Error('No token was found, unable to make authenticated request');
  }
  
  const requestUrl = resolveReleaseApiUrl(url);
  const canSendCredentials = isTrustedReleaseUrl(requestUrl);

  // Build headers
  const headers = {
    ...buildCurrentReleaseHeaders(),
    ...(options?.headers || {}),
  };
  if (canSendCredentials && token && token.length > 0) {
    headers.Authorization = `Bearer ${token}`;
  }
  
  // Add X-Customer-Number header if subuser has selected a grant
  const isSubuser = localStorage.getItem('is_subuser') === 'true';
  const selectedCustomerNumber = getSelectedCustomerNumber$2();
  if (canSendCredentials && isSubuser && selectedCustomerNumber) {
    headers['X-Customer-Number'] = selectedCustomerNumber;
  }
  
  const useFetchTransport = options?.transport === FETCH_TRANSPORT;

  return enqueueRequest(
    () => useFetchTransport
      ? executeFetchRequest({
        method,
        url: requestUrl,
        data,
        signal: options?.signal,
        headers,
      })
      : axios({
      method,
      url: requestUrl,
      ...(method === 'GET' ? { params: data } : { data }),
      ...(options?.signal ? { signal: options.signal } : {}),
      __skipRequestQueue: true,
      headers
    }),
    {
      method,
      url: requestUrl,
      requestData: {
        params: method === 'GET' ? data : null,
        data: method === 'GET' ? null : data,
        headers,
      },
      signal: options?.signal,
      ...buildRequestQueueOptions(requestUrl, method, options),
    }
  )
    .catch((error) => {
      if (catchCallable) {
        // Call the catch callable
        catchCallable(error);
      }
      throw error;
    })
    .then((response) => {
      response = normalizeActiveWashResponse(url, method, response);
      if (thenCallable) {
        // Call the then callable
        thenCallable(response);
      }
      return response;
    });
};

const unauthenticatedRequest$1 = (url, method, data, catchCallable = null, thenCallable = null) => {
  return axios({
    method,
    url: resolveReleaseApiUrl(url),
    ...(method === 'GET' ? { params: data } : { data }),
    headers: buildCurrentReleaseHeaders(),
  }).catch((error) => {
    if (catchCallable) {
      // Call the catch callable
      catchCallable(error);
    }
    throw error;
  }).then((response) => {
    if (thenCallable) {
      // Call the then callable
      thenCallable(response);
    }
    return response;
  });
};

const paginatedGetRequest$1 = (url, currentPage, itemsPerPage) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  const requestUrl = resolveReleaseApiUrl(url);
  const canSendCredentials = isTrustedReleaseUrl(requestUrl);
  
  // Build headers
  const headers = {
    ...buildCurrentReleaseHeaders(),
  };
  if (canSendCredentials) {
    headers.Authorization = `Bearer ${token}`;
  }
  
  // Add X-Customer-Number header if subuser has selected a grant
  const isSubuser = localStorage.getItem('is_subuser') === 'true';
  const selectedCustomerNumber = getSelectedCustomerNumber$2();
  if (canSendCredentials && isSubuser && selectedCustomerNumber) {
    headers['X-Customer-Number'] = selectedCustomerNumber;
  }
  
  return axios.get(requestUrl, {
    params: {
      page: currentPage,
      limit: itemsPerPage
    },
    headers
  });
};

const _sfc_main$3r = {};
const authenticatedRequest_default = /*#__PURE__*/_export_sfc(_sfc_main$3r, [['__file',"authenticatedRequest.vue"]]);

/** Define the errors ref */
const errors = ref([]);

/** Define the getError function */
const getError = (name = null) => {
  if (name) {
    const result = errors.value.find(error => error.name === name);
    return result ? result.error : null;
  }
  return errors.value;
};

/** Define the hasError function */
const hasError = (name = null) => {
  if (name) {
    return errors.value.some(error => error.name === name);
  }
  return errors.value.length > 0;
};

/** Define the removeError function */
const removeError = (name = null) => {
  if (name) {
    errors.value = errors.value.filter(error => error.name !== name);
    return;
  }
  // If no name is provided, clear all errors
  errors.value = [];
};

/** Define the clearErrors function */
const clearErrors = () => {
  // Clear all errors if no specific error is provided
  errors.value = [];
};

/** Define the addError function */
const addError = (error, name = null) => {
  if (name) {
    errors.value.push({name, error});
    return;
  }
  errors.value.push(error);
};

/** Define the parseError function */

const parseError = (error, name = null) => {
  if (error.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    /** If the response has the custom error message */
    if (error.response.data.data.message) {
      addError(error.response.data.data.message, name);
    } else {
      /** Fall back to the default error message */
      addError(error.response.data.message, name);
    }
  } else if (error.request) {
    // The request was made but no response was received
    addError('No response was received', name);
  } else {
    // Something happened in setting up the request that triggered an Error
    addError(error, name);
  }
};

const _sfc_main$3q = {};
const HandleGlobalError = /*#__PURE__*/_export_sfc(_sfc_main$3q, [['__file',"HandleGlobalError.vue"]]);

const EDGE_GATEWAY_WORKSPACE_CACHE_KEY = "truckwash.edgeGatewayWorkspace.cache.v1";
const EDGE_GATEWAY_WORKSPACE_CACHE_TTL_MS = 15 * 60 * 1000;

const EDGE_GATEWAY_BASE = "/edge-gateways";
const EDGE_GATEWAY_CONFIG_BASE = "/edgegateway/config";

const listRequestsInFlight = new Map();
const detailRequestsInFlight = new Map();
let departmentsRequestInFlight = null;
let edgeGatewayWorkspaceCache = null;
let edgeGatewayWorkspaceCacheStorageKey = null;

const cloneJson = (value) => (value === null || value === undefined ? value : JSON.parse(JSON.stringify(value)));
const getDataPayload = (response) => (response && response.data ? response.data.data : undefined);
const getMetaPayload = (response) => (response && response.data ? response.data.meta : undefined);
const normalizeDepartmentId = (departmentId) =>
  departmentId === null || departmentId === undefined || departmentId === "" ? null : Number(departmentId);
const normalizeGatewayId = (gatewayId) =>
  gatewayId === null || gatewayId === undefined || gatewayId === "" ? null : String(gatewayId);
const listCacheKey = ({ departmentId = null, view = "summary" } = {}) =>
  JSON.stringify({ departmentId: normalizeDepartmentId(departmentId), view: String(view || "summary") });

const normalizeEntries$2 = (entries) => {
  if (Array.isArray(entries)) {
    return entries;
  }

  if (entries && typeof entries === "object") {
    return Object.values(entries);
  }

  return [];
};

const parseJsonObject = (value) => {
  if (typeof value !== "string" || !value.trim()) {
    return null;
  }

  try {
    const parsed = JSON.parse(value);
    return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
  } catch (_error) {
    return null;
  }
};

const normalizeRotateCredentialBundle = (bundle) => {
  if (!bundle || typeof bundle !== "object" || Array.isArray(bundle)) {
    return bundle;
  }

  const config = parseJsonObject(bundle.config_json);
  const agentToken =
    bundle.agent_token || bundle.token || (config && (config.agentToken || config.agent_token)) || null;
  const stackServiceName =
    bundle.stackServiceName ||
    bundle.stack_service_name ||
    (config && config.stackServiceName) ||
    (config && config.stack_service_name) ||
    (config && config.serviceName) ||
    (config && config.service_name) ||
    null;
  const composeFileName =
    bundle.composeFileName ||
    bundle.compose_file_name ||
    (config && (config.composeFileName || config.compose_file_name)) ||
    null;

  return {
    ...bundle,
    token: bundle.token || agentToken,
    agent_token: agentToken,
    stackServiceName,
    stack_service_name: bundle.stack_service_name || stackServiceName,
    composeFileName,
    compose_file_name: bundle.compose_file_name || composeFileName,
  };
};

const normalizeRotateCredentialResponse = (response) => {
  const bundle = getDataPayload(response);
  if (bundle && typeof bundle === "object" && !Array.isArray(bundle)) {
    response.data.data = normalizeRotateCredentialBundle(bundle);
  }
  return response;
};

const toConfigPayload$2 = (entries) => {
  const payload = {};
  normalizeEntries$2(entries).forEach((entry) => {
    if (!entry || !entry.variable) {
      return;
    }
    payload[entry.variable] = entry.value;
  });
  return payload;
};

const createEmptyWorkspaceCache = (scope = null) => ({
  scope,
  cachedAt: Date.now(),
  departments: null,
  lists: {},
  details: {},
});

const storage = () => {
  if (typeof window === "undefined" || !window.sessionStorage) {
    return null;
  }

  return window.sessionStorage;
};

const removeLegacyWorkspaceCache = () => {
  if (typeof window === "undefined" || !window.localStorage) {
    return;
  }

  try {
    window.localStorage.removeItem(EDGE_GATEWAY_WORKSPACE_CACHE_KEY);
  } catch (_error) {
    // Browser storage can be unavailable in private browsing or tests.
  }
};

const getStoredValue = (key) => {
  if (typeof window === "undefined" || !window.localStorage) {
    return null;
  }

  try {
    return window.localStorage.getItem(key);
  } catch (_error) {
    return null;
  }
};

const hashScopePart = (value) => {
  let hash = 0;
  const input = String(value || "");
  for (let index = 0; index < input.length; index += 1) {
    hash = (hash << 5) - hash + input.charCodeAt(index);
    hash |= 0;
  }
  return hash.toString(36);
};

const currentWorkspaceCacheScope = () => {
  const token = getStoredValue("token");
  if (!token) {
    return null;
  }

  return JSON.stringify({
    token: hashScopePart(token),
    isSubuser: getStoredValue("is_subuser") === "true",
    selectedCustomerNumber: getStoredValue("selected_customer_number") || null,
    hasSuperuserToken: Boolean(getStoredValue("superuser_token")),
  });
};

const isFreshCachedAt = (cachedAt) => Date.now() - Number(cachedAt || 0) <= EDGE_GATEWAY_WORKSPACE_CACHE_TTL_MS;
const isFreshCacheEntry$1 = (entry) => Boolean(entry && typeof entry === "object" && isFreshCachedAt(entry.cachedAt));
const isSensitiveCacheField = (fieldName) =>
  /(^|[_-])(token|secret|password|credential|authorization|api[_-]?key|private[_-]?key)($|[_-])/i.test(
    String(fieldName || "")
  ) || String(fieldName || "").toLowerCase() === "config_json";

const sanitizeCacheValue = (value) => {
  if (Array.isArray(value)) {
    return value.map((item) => sanitizeCacheValue(item));
  }

  if (!value || typeof value !== "object") {
    return value;
  }

  return Object.entries(value).reduce((sanitized, [key, childValue]) => {
    if (!isSensitiveCacheField(key)) {
      sanitized[key] = sanitizeCacheValue(childValue);
    }
    return sanitized;
  }, {});
};

const sanitizeGatewayCachePayload = (value) => cloneJson(sanitizeCacheValue(value));

const resetWorkspaceCacheMemory = (scope = currentWorkspaceCacheScope()) => {
  edgeGatewayWorkspaceCache = createEmptyWorkspaceCache(scope);
  edgeGatewayWorkspaceCacheStorageKey = EDGE_GATEWAY_WORKSPACE_CACHE_KEY;
  return edgeGatewayWorkspaceCache;
};

const loadWorkspaceCache = () => {
  removeLegacyWorkspaceCache();
  const scope = currentWorkspaceCacheScope();
  if (!scope) {
    return resetWorkspaceCacheMemory(null);
  }

  if (
    edgeGatewayWorkspaceCache !== null &&
    edgeGatewayWorkspaceCache.scope === scope &&
    isFreshCachedAt(edgeGatewayWorkspaceCache.cachedAt)
  ) {
    return edgeGatewayWorkspaceCache;
  }

  const storageHandle = storage();
  if (!storageHandle) {
    return resetWorkspaceCacheMemory(scope);
  }

  try {
    const decoded = JSON.parse(storageHandle.getItem(EDGE_GATEWAY_WORKSPACE_CACHE_KEY) || "null");
    if (!decoded || typeof decoded !== "object" || decoded.scope !== scope || !isFreshCachedAt(decoded.cachedAt)) {
      storageHandle.removeItem(EDGE_GATEWAY_WORKSPACE_CACHE_KEY);
      return resetWorkspaceCacheMemory(scope);
    }

    edgeGatewayWorkspaceCache = {
      ...createEmptyWorkspaceCache(scope),
      cachedAt: Number(decoded.cachedAt || Date.now()),
      departments: isFreshCacheEntry$1(decoded.departments) ? decoded.departments : null,
      lists:
        decoded && decoded.lists && typeof decoded.lists === "object"
          ? Object.fromEntries(Object.entries(decoded.lists).filter(([, entry]) => isFreshCacheEntry$1(entry)))
          : {},
      details:
        decoded && decoded.details && typeof decoded.details === "object"
          ? Object.fromEntries(Object.entries(decoded.details).filter(([, entry]) => isFreshCacheEntry$1(entry)))
          : {},
    };
    edgeGatewayWorkspaceCacheStorageKey = EDGE_GATEWAY_WORKSPACE_CACHE_KEY;
  } catch (_error) {
    storageHandle.removeItem(EDGE_GATEWAY_WORKSPACE_CACHE_KEY);
    resetWorkspaceCacheMemory(scope);
  }

  return edgeGatewayWorkspaceCache;
};

const persistWorkspaceCache = () => {
  const storageHandle = storage();
  const scope = currentWorkspaceCacheScope();
  if (!storageHandle || edgeGatewayWorkspaceCache === null || !scope || edgeGatewayWorkspaceCache.scope !== scope) {
    return;
  }

  edgeGatewayWorkspaceCache.cachedAt = Date.now();
  edgeGatewayWorkspaceCacheStorageKey = EDGE_GATEWAY_WORKSPACE_CACHE_KEY;
  storageHandle.setItem(EDGE_GATEWAY_WORKSPACE_CACHE_KEY, JSON.stringify(edgeGatewayWorkspaceCache));
};

const clearEdgeGatewayWorkspaceCache = () => {
  edgeGatewayWorkspaceCache = null;
  edgeGatewayWorkspaceCacheStorageKey = null;
  removeLegacyWorkspaceCache();
  const storageHandle = storage();
  if (!storageHandle) {
    return;
  }

  storageHandle.removeItem(EDGE_GATEWAY_WORKSPACE_CACHE_KEY);
};
const mergeGatewaySnapshots = (currentGateway, nextGateway) => {
  if (!currentGateway) {
    return cloneJson(nextGateway);
  }

  return {
    ...cloneJson(currentGateway),
    ...cloneJson(nextGateway),
    metadata: {
      ...((currentGateway && currentGateway.metadata) || {}),
      ...((nextGateway && nextGateway.metadata) || {}),
    },
    inventory: Array.isArray(nextGateway && nextGateway.inventory)
      ? cloneJson(nextGateway.inventory)
      : Array.isArray(currentGateway && currentGateway.inventory)
      ? cloneJson(currentGateway.inventory)
      : undefined,
    bindings: Array.isArray(nextGateway && nextGateway.bindings)
      ? cloneJson(nextGateway.bindings)
      : Array.isArray(currentGateway && currentGateway.bindings)
      ? cloneJson(currentGateway.bindings)
      : undefined,
    operations: Array.isArray(nextGateway && nextGateway.operations)
      ? cloneJson(nextGateway.operations)
      : Array.isArray(currentGateway && currentGateway.operations)
      ? cloneJson(currentGateway.operations)
      : undefined,
    audit_logs: Array.isArray(nextGateway && nextGateway.audit_logs)
      ? cloneJson(nextGateway.audit_logs)
      : Array.isArray(currentGateway && currentGateway.audit_logs)
      ? cloneJson(currentGateway.audit_logs)
      : undefined,
  };
};

const cacheGatewaySnapshot = (gateway) => {
  if (!gateway || !gateway.id) {
    return null;
  }

  const cache = loadWorkspaceCache();
  const sanitizedGateway = sanitizeGatewayCachePayload(gateway);
  const gatewayId = String(sanitizedGateway.id);
  const mergedGateway = mergeGatewaySnapshots(
    (cache.details[gatewayId] && cache.details[gatewayId].data) || null,
    sanitizedGateway
  );
  cache.details[gatewayId] = {
    cachedAt: Date.now(),
    data: mergedGateway,
  };

  Object.entries(cache.lists || {}).forEach(([cacheKey, entry]) => {
    const listEntry = entry && typeof entry === "object" ? entry : { params: null, rows: [] };
    const params = listEntry.params && typeof listEntry.params === "object" ? listEntry.params : {};
    const rows = Array.isArray(listEntry.rows) ? [...listEntry.rows] : [];
    const matchesDepartment =
      normalizeDepartmentId(params.departmentId) === null ||
      Number(params.departmentId) === Number(gateway.department_id);
    const existingIndex = rows.findIndex((item) => Number((item && item.id) || 0) === Number(gateway.id));

    if (existingIndex >= 0) {
      rows[existingIndex] = mergeGatewaySnapshots(rows[existingIndex], sanitizedGateway);
    } else if (matchesDepartment) {
      rows.unshift(cloneJson(sanitizedGateway));
    }

    cache.lists[cacheKey] = {
      ...listEntry,
      rows,
      cachedAt: Date.now(),
    };
  });

  persistWorkspaceCache();
  return cloneJson(mergedGateway);
};

const cacheFleetSnapshot = ({ departmentId = null, view = "summary", rows = [], meta = {} } = {}) => {
  const cache = loadWorkspaceCache();
  const sanitizedRows = sanitizeGatewayCachePayload(Array.isArray(rows) ? rows : []);
  const key = listCacheKey({ departmentId, view });
  cache.lists[key] = {
    params: {
      departmentId: normalizeDepartmentId(departmentId),
      view: String(view || "summary"),
    },
    rows: sanitizedRows,
    meta: sanitizeGatewayCachePayload(meta || {}),
    cachedAt: Date.now(),
  };

  sanitizedRows.forEach((gateway) => {
    if (!gateway || !gateway.id) {
      return;
    }

    const gatewayId = String(gateway.id);
    if (!cache.details[gatewayId]) {
      cache.details[gatewayId] = {
        cachedAt: Date.now(),
        data: sanitizeGatewayCachePayload(gateway),
      };
      return;
    }

    cache.details[gatewayId] = {
      cachedAt: Date.now(),
      data: mergeGatewaySnapshots(cache.details[gatewayId].data, gateway),
    };
  });

  persistWorkspaceCache();
};

const cacheDepartmentsSnapshot = (departments) => {
  const cache = loadWorkspaceCache();
  cache.departments = {
    cachedAt: Date.now(),
    data: sanitizeGatewayCachePayload(Array.isArray(departments) ? departments : []),
  };
  persistWorkspaceCache();
};

const cacheGatewayFromResponse = (response) => {
  const gateway = getDataPayload(response);
  if (gateway && gateway.id) {
    cacheGatewaySnapshot(gateway);
  }
  return response;
};

const cacheGatewayFromNestedResponse = (response) => {
  const payload = getDataPayload(response);
  const gateway = payload && payload.gateway;
  if (gateway && gateway.id) {
    cacheGatewaySnapshot(gateway);
  }
  return response;
};

const buildOperationPayload = (typeOrPayload, request = {}) => {
  if (typeOrPayload && typeof typeOrPayload === "object" && !Array.isArray(typeOrPayload)) {
    return {
      ...typeOrPayload,
      request:
        typeOrPayload.request && typeof typeOrPayload.request === "object" && !Array.isArray(typeOrPayload.request)
          ? typeOrPayload.request
          : {},
    };
  }

  return {
    type: String(typeOrPayload || "").toUpperCase(),
    request: request && typeof request === "object" && !Array.isArray(request) ? request : {},
  };
};

const unwrapEdgeGatewayResponse = (response, fallback = null) => {
  const data = getDataPayload(response);
  return data === undefined || data === null ? fallback : data;
};
const unwrapEdgeGatewayMeta = (response) => getMetaPayload(response) || {};

const isEdgeGatewayAuthorizationError = (error) => {
  const status = Number(
    (error && error.response && error.response.status) ||
      (error && error.status) ||
      (error && error.response && error.response.data && error.response.data.status) ||
      0
  );
  return status === 401 || status === 403;
};

const peekCachedEdgeGatewayDepartments = () => {
  const entry = loadWorkspaceCache().departments;
  const departments = entry && entry.data;
  return isFreshCacheEntry$1(entry) && Array.isArray(departments) ? cloneJson(departments) : null;
};

const peekCachedEdgeGatewayList = ({ departmentId = null, view = "summary" } = {}) => {
  const entry = loadWorkspaceCache().lists[listCacheKey({ departmentId, view })];
  if (!isFreshCacheEntry$1(entry) || !Array.isArray(entry.rows)) {
    return null;
  }

  return {
    cachedAt: Number(entry.cachedAt || 0),
    rows: cloneJson(entry.rows),
    meta: cloneJson(entry.meta || {}),
  };
};

const peekCachedEdgeGateway = (gatewayId) => {
  const normalizedGatewayId = normalizeGatewayId(gatewayId);
  if (!normalizedGatewayId) {
    return null;
  }

  const entry = loadWorkspaceCache().details[normalizedGatewayId];
  return isFreshCacheEntry$1(entry) && entry && entry.data ? cloneJson(entry.data) : null;
};

const patchEdgeGatewayCache = (gatewayId, patch) => {
  const current = peekCachedEdgeGateway(gatewayId);
  if (!current) {
    return null;
  }

  return cacheGatewaySnapshot(mergeGatewaySnapshots(current, patch));
};

const removeEdgeGatewayCache = (gatewayId) => {
  const normalizedGatewayId = normalizeGatewayId(gatewayId);
  if (!normalizedGatewayId) {
    return;
  }

  const cache = loadWorkspaceCache();
  delete cache.details[normalizedGatewayId];
  Object.entries(cache.lists || {}).forEach(([cacheKey, entry]) => {
    const rows = Array.isArray(entry && entry.rows)
      ? entry.rows.filter((item) => String((item && item.id) || "") !== normalizedGatewayId)
      : [];
    cache.lists[cacheKey] = {
      ...(entry || {}),
      rows,
      cachedAt: Date.now(),
    };
  });
  persistWorkspaceCache();
};

const updateDepartmentGatewayCutoverCache = (departmentId, transportMode) => {
  const normalizedDepartmentId = normalizeDepartmentId(departmentId);
  if (normalizedDepartmentId === null) {
    return;
  }

  const cache = loadWorkspaceCache();
  Object.entries(cache.details || {}).forEach(([gatewayId, entry]) => {
    if (Number((entry && entry.data && entry.data.department_id) || 0) !== normalizedDepartmentId) {
      return;
    }

    cache.details[gatewayId] = {
      cachedAt: Date.now(),
      data: mergeGatewaySnapshots(entry.data, {
        department_transport_mode: transportMode,
      }),
    };
  });

  Object.entries(cache.lists || {}).forEach(([cacheKey, entry]) => {
    const rows = Array.isArray(entry && entry.rows)
      ? entry.rows.map((gateway) =>
          Number((gateway && gateway.department_id) || 0) === normalizedDepartmentId
            ? { ...gateway, department_transport_mode: transportMode }
            : gateway
        )
      : [];
    cache.lists[cacheKey] = {
      ...(entry || {}),
      rows,
      cachedAt: Date.now(),
    };
  });

  persistWorkspaceCache();
};

const listEdgeGatewayDepartments = async ({ forceRefresh = false } = {}) => {
  if (!forceRefresh && departmentsRequestInFlight) {
    return departmentsRequestInFlight;
  }

  const request = authenticatedRequest("/departments", "GET", {}).then((response) => {
    cacheDepartmentsSnapshot(getDataPayload(response) || []);
    return response;
  });

  departmentsRequestInFlight = request.finally(() => {
    if (departmentsRequestInFlight === request) {
      departmentsRequestInFlight = null;
    }
  });

  return departmentsRequestInFlight;
};

const listEdgeGatewayDepartmentWorkspaces = async () =>
  authenticatedRequest("/modules/edge-gateways/workspace/departments", "GET", {});

const getEdgeGatewayDepartmentWorkspace = async (departmentId) =>
  authenticatedRequest(
    `/modules/edge-gateways/workspace/departments/${encodeURIComponent(String(departmentId))}`,
    "GET",
    {}
  );

const listEdgeGateways = async ({ departmentId = null, view = "summary", forceRefresh = false } = {}) => {
  const requestKey = listCacheKey({ departmentId, view });
  if (!forceRefresh && listRequestsInFlight.has(requestKey)) {
    return listRequestsInFlight.get(requestKey);
  }

  const request = authenticatedRequest(EDGE_GATEWAY_BASE, "GET", {
    ...(departmentId ? { department_id: departmentId } : {}),
    ...(view ? { view } : {}),
  }).then((response) => {
    cacheFleetSnapshot({
      departmentId,
      view,
      rows: getDataPayload(response) || [],
      meta: getMetaPayload(response) || {},
    });
    return response;
  });

  const trackedRequest = request.finally(() => {
    if (listRequestsInFlight.get(requestKey) === trackedRequest) {
      listRequestsInFlight.delete(requestKey);
    }
  });
  listRequestsInFlight.set(requestKey, trackedRequest);
  return trackedRequest;
};

const getEdgeGateway = async (gatewayId, { forceRefresh = false } = {}) => {
  const normalizedGatewayId = normalizeGatewayId(gatewayId);
  if (!normalizedGatewayId) {
    throw new Error("A gatewayId is required");
  }

  if (!forceRefresh && detailRequestsInFlight.has(normalizedGatewayId)) {
    return detailRequestsInFlight.get(normalizedGatewayId);
  }

  const request = authenticatedRequest(`${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}`, "GET", {}).then(
    (response) => {
      const gateway = getDataPayload(response);
      if (gateway && gateway.id) {
        cacheGatewaySnapshot(gateway);
      }
      return response;
    }
  );

  const trackedRequest = request.finally(() => {
    if (detailRequestsInFlight.get(normalizedGatewayId) === trackedRequest) {
      detailRequestsInFlight.delete(normalizedGatewayId);
    }
  });
  detailRequestsInFlight.set(normalizedGatewayId, trackedRequest);
  return trackedRequest;
};

const listEdgeGatewayOperations = async (gatewayId) =>
  authenticatedRequest(`${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}/operations`, "GET", {});

const getEdgeGatewayTasks = async (gatewayId) =>
  authenticatedRequest(`${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}/tasks`, "GET", {}).then(
    cacheGatewayFromNestedResponse
  );

const getEdgeGatewayLogs = async (gatewayId) =>
  authenticatedRequest(`${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}/logs`, "GET", {}).then(
    cacheGatewayFromNestedResponse
  );

const getEdgeGatewayStatistics = async (gatewayId) =>
  authenticatedRequest(`${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}/statistics`, "GET", {}).then(
    cacheGatewayFromNestedResponse
  );

const createEdgeGatewayOperation = async (gatewayId, typeOrPayload, request = {}) =>
  authenticatedRequest(
    `${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}/operations`,
    "POST",
    buildOperationPayload(typeOrPayload, request)
  ).then(cacheGatewayFromNestedResponse);

const cancelEdgeGatewayOperation = async (gatewayId, operationId) =>
  authenticatedRequest(
    `${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}/operations/${encodeURIComponent(
      String(operationId)
    )}/cancel`,
    "POST",
    {}
  ).then(cacheGatewayFromNestedResponse);

const getEdgeGatewayOperationEvents = async (gatewayId, operationId) =>
  authenticatedRequest(
    `${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}/operations/${encodeURIComponent(
      String(operationId)
    )}/events`,
    "GET",
    {}
  );

const listEdgeGatewayOperationEvents = getEdgeGatewayOperationEvents;

const rotateEdgeGatewayCredentials = async (gatewayId) =>
  authenticatedRequest(`${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}/rotate-credentials`, "POST", {}).then(
    normalizeRotateCredentialResponse
  );

const createEdgeGatewayInstallToken = async ({ department_id, label }) =>
  authenticatedRequest(`${EDGE_GATEWAY_BASE}/install-token`, "POST", { department_id, label });

const getEdgeGatewayInstallTokenStatus = async (claimTokenId) =>
  authenticatedRequest(
    `${EDGE_GATEWAY_BASE}/install-token/${encodeURIComponent(String(claimTokenId))}/status`,
    "GET",
    {}
  );

const updateEdgeGateway = async (gatewayId, payload) =>
  authenticatedRequest(`${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}`, "PUT", payload).then(
    cacheGatewayFromResponse
  );

const triggerEdgeGatewayDiscovery = async (gatewayId) =>
  authenticatedRequest(`${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}/discovery`, "POST", {}).then(
    cacheGatewayFromResponse
  );

const saveEdgeGatewayBindings = async (gatewayId, bindings) =>
  authenticatedRequest(`${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}/bindings`, "PUT", { bindings }).then(
    cacheGatewayFromResponse
  );

const deleteEdgeGateway = async (gatewayId) =>
  authenticatedRequest(`${EDGE_GATEWAY_BASE}/${encodeURIComponent(gatewayId)}`, "DELETE", {}).then((response) => {
    removeEdgeGatewayCache(gatewayId);
    return response;
  });

const setDepartmentGatewayCutover = async (departmentId, transport_mode) =>
  authenticatedRequest(`/departments/${encodeURIComponent(departmentId)}/gateway-cutover`, "POST", {
    transport_mode,
  }).then((response) => {
    updateDepartmentGatewayCutoverCache(departmentId, transport_mode);
    return response;
  });

const updateDepartmentLaneBindings = async (laneId, payload = {}) =>
  authenticatedRequest("/department/lanes", "PUT", {
    id: Number(laneId),
    ...payload,
  });

const SELF_SERVE_RELAY_TEST_ENDPOINTS = Object.freeze({
  MACHINE: "/modules/self-serve/lane/relay/machine/set",
  PROGRAM_PICKER: "/modules/self-serve/lane/relay/machine_program_picker/set",
  CLEANER: "/modules/self-serve/lane/relay/machine_cleaner/set",
});

const normalizeRelayTestTransport = (transport) => {
  const normalizedTransport = String(transport || "")
    .trim()
    .toLowerCase();
  return normalizedTransport === "cloud" ? "cloud" : "local";
};

const normalizeRelayTestTimer = (seconds) => {
  const normalizedSeconds = Number.parseInt(String(seconds === null || seconds === undefined ? "" : seconds), 10);
  return Number.isInteger(normalizedSeconds) && normalizedSeconds > 0 ? normalizedSeconds : 1;
};

const runDepartmentLaneGateTest = async (laneId, gate, { transport = "local", toggleAfter = 1 } = {}) =>
  authenticatedRequest("/modules/self-serve/lane/gate/open", "POST", {
    lane_id: Number(laneId),
    gate: String(gate || "").toUpperCase(),
    transport: normalizeRelayTestTransport(transport),
    toggle_after: normalizeRelayTestTimer(toggleAfter),
  });

const runDepartmentSelfServeRelayTest = async (laneId, relay, on, { transport = "local" } = {}) => {
  const endpoint = SELF_SERVE_RELAY_TEST_ENDPOINTS[String(relay || "").toUpperCase()];
  if (!endpoint) {
    throw new Error(`Unsupported self-serve relay test: ${relay}`);
  }

  return authenticatedRequest(endpoint, "POST", {
    lane_id: Number(laneId),
    on: Boolean(on),
    transport: normalizeRelayTestTransport(transport),
  });
};

const updateNumberPlateScanner = async (scannerId, payload = {}) =>
  authenticatedRequest("/numberplatescanners", "PUT", {
    id: Number(scannerId),
    ...payload,
  });

const rotateNumberPlateScannerKey = async (scannerId) =>
  authenticatedRequest(`/numberplatescanners/${encodeURIComponent(String(scannerId))}/rotate-key`, "POST", {});

const getEdgeGatewayModuleConfig = async (variable = null) => {
  const endpoint = variable
    ? `${EDGE_GATEWAY_CONFIG_BASE}?variable=${encodeURIComponent(String(variable))}`
    : EDGE_GATEWAY_CONFIG_BASE;

  return authenticatedRequest(endpoint, "GET", {}).then((response) => {
    const entries = normalizeEntries$2(unwrapEdgeGatewayResponse(response, []));
    response.data.data = entries;
    response.data.config = toConfigPayload$2(entries);
    return response;
  });
};

const setEdgeGatewayModuleConfig = async (payload) =>
  authenticatedRequest(EDGE_GATEWAY_CONFIG_BASE, "POST", payload);

const testEdgeGatewayBrokerConfig = async (payload = {}) =>
  authenticatedRequest(`${EDGE_GATEWAY_CONFIG_BASE}/broker-diagnostics`, "POST", payload);

const EDGE_GATEWAY_OPERATIONS = {
  discovery(request = {}) {
    return {
      type: "DISCOVERY",
      request,
    };
  },
  update(targetVersion, releaseChannel = "stable") {
    return {
      type: "UPDATE",
      request: {
        target_version: targetVersion,
        release_channel: releaseChannel,
      },
    };
  },
  uninstall() {
    return {
      type: "UNINSTALL",
      request: {},
    };
  },
};

const pendingRequest = ref(null);

const SuperUserSystemStatusObject = {
  snapshot: ref(null),
  loading: ref(false),
  error: ref(null),
  lastLoadedAt: ref(null),
  overallStatus: computed(() => SuperUserSystemStatusObject.snapshot.value?.overall_status ?? "down"),
  runtime: computed(() => SuperUserSystemStatusObject.snapshot.value?.runtime ?? {}),
  dependencies: computed(() => SuperUserSystemStatusObject.snapshot.value?.dependencies ?? {}),
  modules: computed(() => SuperUserSystemStatusObject.snapshot.value?.modules ?? []),
  sessions: computed(
    () =>
      SuperUserSystemStatusObject.snapshot.value?.sessions ?? {
        active_window_minutes: 15,
        active_users: 0,
        active_sessions: 0,
        recent_sessions: [],
      }
  ),
  warnings: computed(() => SuperUserSystemStatusObject.snapshot.value?.warnings ?? []),
  refreshAfterSeconds: computed(() => Number(SuperUserSystemStatusObject.snapshot.value?.refresh_after_seconds ?? 30)),
};

const getSuperuserSystemStatus = async ({ force = false } = {}) => {
  if (pendingRequest.value) {
    return pendingRequest.value;
  }

  SuperUserSystemStatusObject.loading.value = true;

  pendingRequest.value = authenticatedRequest("/superuser/system/status", "GET", force ? { force: 1 } : {})
    .then((response) => {
      SuperUserSystemStatusObject.snapshot.value = response.data.data;
      SuperUserSystemStatusObject.error.value = null;
      SuperUserSystemStatusObject.lastLoadedAt.value = new Date();
      return SuperUserSystemStatusObject.snapshot.value;
    })
    .catch((error) => {
      SuperUserSystemStatusObject.error.value = error;
      throw error;
    })
    .finally(() => {
      SuperUserSystemStatusObject.loading.value = false;
      pendingRequest.value = null;
    });

  return pendingRequest.value;
};

const createDependencySystemObject = (key) => ({
  status: computed(() => SuperUserSystemStatusObject.dependencies.value?.[key] ?? null),
  loading: computed(() => SuperUserSystemStatusObject.loading.value),
  error: computed(() => SuperUserSystemStatusObject.error.value),
  lastLoadedAt: computed(() => SuperUserSystemStatusObject.lastLoadedAt.value),
});

const DatabaseSystemObject = createDependencySystemObject("database");
const RedisSystemObject = createDependencySystemObject("redis");
const MinioSystemObject = createDependencySystemObject("minio");

const getSystemDependencyStatus = async (key, { force = false } = {}) => {
  const snapshot = await getSuperuserSystemStatus({ force });
  return snapshot?.dependencies?.[key] ?? null;
};

const getSystemDatabaseStatus = (options = {}) => getSystemDependencyStatus("database", options);
const getSystemRedisStatus = (options = {}) => getSystemDependencyStatus("redis", options);
const getSystemMinioStatus = (options = {}) => getSystemDependencyStatus("minio", options);

const _sfc_main$3p = {};
const systemStatus = /*#__PURE__*/_export_sfc(_sfc_main$3p, [['__file',"systemStatus.vue"]]);

const _sfc_main$3o = {};
const systemDatabase = /*#__PURE__*/_export_sfc(_sfc_main$3o, [['__file',"systemDatabase.vue"]]);

/*!
* sweetalert2 v11.22.4
* Released under the MIT License.
*/
function _assertClassBrand(e, t, n) {
  if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
  throw new TypeError("Private element is not present on this object");
}
function _checkPrivateRedeclaration(e, t) {
  if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
}
function _classPrivateFieldGet2(s, a) {
  return s.get(_assertClassBrand(s, a));
}
function _classPrivateFieldInitSpec(e, t, a) {
  _checkPrivateRedeclaration(e, t), t.set(e, a);
}
function _classPrivateFieldSet2(s, a, r) {
  return s.set(_assertClassBrand(s, a), r), r;
}

const RESTORE_FOCUS_TIMEOUT = 100;

/** @type {GlobalState} */
const globalState = {};
const focusPreviousActiveElement = () => {
  if (globalState.previousActiveElement instanceof HTMLElement) {
    globalState.previousActiveElement.focus();
    globalState.previousActiveElement = null;
  } else if (document.body) {
    document.body.focus();
  }
};

/**
 * Restore previous active (focused) element
 *
 * @param {boolean} returnFocus
 * @returns {Promise<void>}
 */
const restoreActiveElement = returnFocus => {
  return new Promise(resolve => {
    if (!returnFocus) {
      return resolve();
    }
    const x = window.scrollX;
    const y = window.scrollY;
    globalState.restoreFocusTimeout = setTimeout(() => {
      focusPreviousActiveElement();
      resolve();
    }, RESTORE_FOCUS_TIMEOUT); // issues/900

    window.scrollTo(x, y);
  });
};

const swalPrefix = 'swal2-';

/**
 * @typedef {Record<SwalClass, string>} SwalClasses
 */

/**
 * @typedef {'success' | 'warning' | 'info' | 'question' | 'error'} SwalIcon
 * @typedef {Record<SwalIcon, string>} SwalIcons
 */

/** @type {SwalClass[]} */
const classNames = ['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', 'footer', 'icon', 'icon-content', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'input-label', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loader', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl', 'timer-progress-bar', 'timer-progress-bar-container', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error', 'draggable', 'dragging'];
const swalClasses = classNames.reduce((acc, className) => {
  acc[className] = swalPrefix + className;
  return acc;
}, /** @type {SwalClasses} */{});

/** @type {SwalIcon[]} */
const icons = ['success', 'warning', 'info', 'question', 'error'];
const iconTypes = icons.reduce((acc, icon) => {
  acc[icon] = swalPrefix + icon;
  return acc;
}, /** @type {SwalIcons} */{});

const consolePrefix = 'SweetAlert2:';

/**
 * Capitalize the first letter of a string
 *
 * @param {string} str
 * @returns {string}
 */
const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);

/**
 * Standardize console warnings
 *
 * @param {string | string[]} message
 */
const warn = message => {
  console.warn(`${consolePrefix} ${typeof message === 'object' ? message.join(' ') : message}`);
};

/**
 * Standardize console errors
 *
 * @param {string} message
 */
const error = message => {
  console.error(`${consolePrefix} ${message}`);
};

/**
 * Private global state for `warnOnce`
 *
 * @type {string[]}
 * @private
 */
const previousWarnOnceMessages = [];

/**
 * Show a console warning, but only if it hasn't already been shown
 *
 * @param {string} message
 */
const warnOnce = message => {
  if (!previousWarnOnceMessages.includes(message)) {
    previousWarnOnceMessages.push(message);
    warn(message);
  }
};

/**
 * Show a one-time console warning about deprecated params/methods
 *
 * @param {string} deprecatedParam
 * @param {string?} useInstead
 */
const warnAboutDeprecation = (deprecatedParam, useInstead = null) => {
  warnOnce(`"${deprecatedParam}" is deprecated and will be removed in the next major release.${useInstead ? ` Use "${useInstead}" instead.` : ''}`);
};

/**
 * If `arg` is a function, call it (with no arguments or context) and return the result.
 * Otherwise, just pass the value through
 *
 * @param {Function | any} arg
 * @returns {any}
 */
const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;

/**
 * @param {any} arg
 * @returns {boolean}
 */
const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';

/**
 * @param {any} arg
 * @returns {Promise<any>}
 */
const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);

/**
 * @param {any} arg
 * @returns {boolean}
 */
const isPromise = arg => arg && Promise.resolve(arg) === arg;

/**
 * Gets the popup container which contains the backdrop and the popup itself.
 *
 * @returns {HTMLElement | null}
 */
const getContainer = () => document.body.querySelector(`.${swalClasses.container}`);

/**
 * @param {string} selectorString
 * @returns {HTMLElement | null}
 */
const elementBySelector = selectorString => {
  const container = getContainer();
  return container ? container.querySelector(selectorString) : null;
};

/**
 * @param {string} className
 * @returns {HTMLElement | null}
 */
const elementByClass = className => {
  return elementBySelector(`.${className}`);
};

/**
 * @returns {HTMLElement | null}
 */
const getPopup = () => elementByClass(swalClasses.popup);

/**
 * @returns {HTMLElement | null}
 */
const getIcon = () => elementByClass(swalClasses.icon);

/**
 * @returns {HTMLElement | null}
 */
const getIconContent = () => elementByClass(swalClasses['icon-content']);

/**
 * @returns {HTMLElement | null}
 */
const getTitle$1 = () => elementByClass(swalClasses.title);

/**
 * @returns {HTMLElement | null}
 */
const getHtmlContainer = () => elementByClass(swalClasses['html-container']);

/**
 * @returns {HTMLElement | null}
 */
const getImage = () => elementByClass(swalClasses.image);

/**
 * @returns {HTMLElement | null}
 */
const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);

/**
 * @returns {HTMLElement | null}
 */
const getValidationMessage = () => elementByClass(swalClasses['validation-message']);

/**
 * @returns {HTMLButtonElement | null}
 */
const getConfirmButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.confirm}`));

/**
 * @returns {HTMLButtonElement | null}
 */
const getCancelButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.cancel}`));

/**
 * @returns {HTMLButtonElement | null}
 */
const getDenyButton = () => (/** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.deny}`));

/**
 * @returns {HTMLElement | null}
 */
const getInputLabel = () => elementByClass(swalClasses['input-label']);

/**
 * @returns {HTMLElement | null}
 */
const getLoader = () => elementBySelector(`.${swalClasses.loader}`);

/**
 * @returns {HTMLElement | null}
 */
const getActions = () => elementByClass(swalClasses.actions);

/**
 * @returns {HTMLElement | null}
 */
const getFooter = () => elementByClass(swalClasses.footer);

/**
 * @returns {HTMLElement | null}
 */
const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);

/**
 * @returns {HTMLElement | null}
 */
const getCloseButton = () => elementByClass(swalClasses.close);

// https://github.com/jkup/focusable/blob/master/index.js
const focusable = `
  a[href],
  area[href],
  input:not([disabled]),
  select:not([disabled]),
  textarea:not([disabled]),
  button:not([disabled]),
  iframe,
  object,
  embed,
  [tabindex="0"],
  [contenteditable],
  audio[controls],
  video[controls],
  summary
`;
/**
 * @returns {HTMLElement[]}
 */
const getFocusableElements = () => {
  const popup = getPopup();
  if (!popup) {
    return [];
  }
  /** @type {NodeListOf<HTMLElement>} */
  const focusableElementsWithTabindex = popup.querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])');
  const focusableElementsWithTabindexSorted = Array.from(focusableElementsWithTabindex)
  // sort according to tabindex
  .sort((a, b) => {
    const tabindexA = parseInt(a.getAttribute('tabindex') || '0');
    const tabindexB = parseInt(b.getAttribute('tabindex') || '0');
    if (tabindexA > tabindexB) {
      return 1;
    } else if (tabindexA < tabindexB) {
      return -1;
    }
    return 0;
  });

  /** @type {NodeListOf<HTMLElement>} */
  const otherFocusableElements = popup.querySelectorAll(focusable);
  const otherFocusableElementsFiltered = Array.from(otherFocusableElements).filter(el => el.getAttribute('tabindex') !== '-1');
  return [...new Set(focusableElementsWithTabindexSorted.concat(otherFocusableElementsFiltered))].filter(el => isVisible$1(el));
};

/**
 * @returns {boolean}
 */
const isModal = () => {
  return hasClass(document.body, swalClasses.shown) && !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);
};

/**
 * @returns {boolean}
 */
const isToast = () => {
  const popup = getPopup();
  if (!popup) {
    return false;
  }
  return hasClass(popup, swalClasses.toast);
};

/**
 * @returns {boolean}
 */
const isLoading$2 = () => {
  const popup = getPopup();
  if (!popup) {
    return false;
  }
  return popup.hasAttribute('data-loading');
};

/**
 * Securely set innerHTML of an element
 * https://github.com/sweetalert2/sweetalert2/issues/1926
 *
 * @param {HTMLElement} elem
 * @param {string} html
 */
const setInnerHtml = (elem, html) => {
  elem.textContent = '';
  if (html) {
    const parser = new DOMParser();
    const parsed = parser.parseFromString(html, `text/html`);
    const head = parsed.querySelector('head');
    if (head) {
      Array.from(head.childNodes).forEach(child => {
        elem.appendChild(child);
      });
    }
    const body = parsed.querySelector('body');
    if (body) {
      Array.from(body.childNodes).forEach(child => {
        if (child instanceof HTMLVideoElement || child instanceof HTMLAudioElement) {
          elem.appendChild(child.cloneNode(true)); // https://github.com/sweetalert2/sweetalert2/issues/2507
        } else {
          elem.appendChild(child);
        }
      });
    }
  }
};

/**
 * @param {HTMLElement} elem
 * @param {string} className
 * @returns {boolean}
 */
const hasClass = (elem, className) => {
  if (!className) {
    return false;
  }
  const classList = className.split(/\s+/);
  for (let i = 0; i < classList.length; i++) {
    if (!elem.classList.contains(classList[i])) {
      return false;
    }
  }
  return true;
};

/**
 * @param {HTMLElement} elem
 * @param {SweetAlertOptions} params
 */
const removeCustomClasses = (elem, params) => {
  Array.from(elem.classList).forEach(className => {
    if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass || {}).includes(className)) {
      elem.classList.remove(className);
    }
  });
};

/**
 * @param {HTMLElement} elem
 * @param {SweetAlertOptions} params
 * @param {string} className
 */
const applyCustomClass = (elem, params, className) => {
  removeCustomClasses(elem, params);
  if (!params.customClass) {
    return;
  }
  const customClass = params.customClass[(/** @type {keyof SweetAlertCustomClass} */className)];
  if (!customClass) {
    return;
  }
  if (typeof customClass !== 'string' && !customClass.forEach) {
    warn(`Invalid type of customClass.${className}! Expected string or iterable object, got "${typeof customClass}"`);
    return;
  }
  addClass(elem, customClass);
};

/**
 * @param {HTMLElement} popup
 * @param {import('./renderers/renderInput').InputClass | SweetAlertInput} inputClass
 * @returns {HTMLInputElement | null}
 */
const getInput$1 = (popup, inputClass) => {
  if (!inputClass) {
    return null;
  }
  switch (inputClass) {
    case 'select':
    case 'textarea':
    case 'file':
      return popup.querySelector(`.${swalClasses.popup} > .${swalClasses[inputClass]}`);
    case 'checkbox':
      return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.checkbox} input`);
    case 'radio':
      return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:checked`) || popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:first-child`);
    case 'range':
      return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.range} input`);
    default:
      return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.input}`);
  }
};

/**
 * @param {HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement} input
 */
const focusInput = input => {
  input.focus();

  // place cursor at end of text in text input
  if (input.type !== 'file') {
    // http://stackoverflow.com/a/2345915
    const val = input.value;
    input.value = '';
    input.value = val;
  }
};

/**
 * @param {HTMLElement | HTMLElement[] | null} target
 * @param {string | string[] | readonly string[] | undefined} classList
 * @param {boolean} condition
 */
const toggleClass = (target, classList, condition) => {
  if (!target || !classList) {
    return;
  }
  if (typeof classList === 'string') {
    classList = classList.split(/\s+/).filter(Boolean);
  }
  classList.forEach(className => {
    if (Array.isArray(target)) {
      target.forEach(elem => {
        if (condition) {
          elem.classList.add(className);
        } else {
          elem.classList.remove(className);
        }
      });
    } else {
      if (condition) {
        target.classList.add(className);
      } else {
        target.classList.remove(className);
      }
    }
  });
};

/**
 * @param {HTMLElement | HTMLElement[] | null} target
 * @param {string | string[] | readonly string[] | undefined} classList
 */
const addClass = (target, classList) => {
  toggleClass(target, classList, true);
};

/**
 * @param {HTMLElement | HTMLElement[] | null} target
 * @param {string | string[] | readonly string[] | undefined} classList
 */
const removeClass = (target, classList) => {
  toggleClass(target, classList, false);
};

/**
 * Get direct child of an element by class name
 *
 * @param {HTMLElement} elem
 * @param {string} className
 * @returns {HTMLElement | undefined}
 */
const getDirectChildByClass = (elem, className) => {
  const children = Array.from(elem.children);
  for (let i = 0; i < children.length; i++) {
    const child = children[i];
    if (child instanceof HTMLElement && hasClass(child, className)) {
      return child;
    }
  }
};

/**
 * @param {HTMLElement} elem
 * @param {string} property
 * @param {*} value
 */
const applyNumericalStyle = (elem, property, value) => {
  if (value === `${parseInt(value)}`) {
    value = parseInt(value);
  }
  if (value || parseInt(value) === 0) {
    elem.style.setProperty(property, typeof value === 'number' ? `${value}px` : value);
  } else {
    elem.style.removeProperty(property);
  }
};

/**
 * @param {HTMLElement | null} elem
 * @param {string} display
 */
const show = (elem, display = 'flex') => {
  if (!elem) {
    return;
  }
  elem.style.display = display;
};

/**
 * @param {HTMLElement | null} elem
 */
const hide$2 = elem => {
  if (!elem) {
    return;
  }
  elem.style.display = 'none';
};

/**
 * @param {HTMLElement | null} elem
 * @param {string} display
 */
const showWhenInnerHtmlPresent = (elem, display = 'block') => {
  if (!elem) {
    return;
  }
  new MutationObserver(() => {
    toggle(elem, elem.innerHTML, display);
  }).observe(elem, {
    childList: true,
    subtree: true
  });
};

/**
 * @param {HTMLElement} parent
 * @param {string} selector
 * @param {string} property
 * @param {string} value
 */
const setStyle$1 = (parent, selector, property, value) => {
  /** @type {HTMLElement | null} */
  const el = parent.querySelector(selector);
  if (el) {
    el.style.setProperty(property, value);
  }
};

/**
 * @param {HTMLElement} elem
 * @param {any} condition
 * @param {string} display
 */
const toggle = (elem, condition, display = 'flex') => {
  if (condition) {
    show(elem, display);
  } else {
    hide$2(elem);
  }
};

/**
 * borrowed from jquery $(elem).is(':visible') implementation
 *
 * @param {HTMLElement | null} elem
 * @returns {boolean}
 */
const isVisible$1 = elem => !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));

/**
 * @returns {boolean}
 */
const allButtonsAreHidden = () => !isVisible$1(getConfirmButton()) && !isVisible$1(getDenyButton()) && !isVisible$1(getCancelButton());

/**
 * @param {HTMLElement} elem
 * @returns {boolean}
 */
const isScrollable = elem => !!(elem.scrollHeight > elem.clientHeight);

/**
 * @param {HTMLElement} element
 * @param {HTMLElement} stopElement
 * @returns {boolean}
 */
const selfOrParentIsScrollable = (element, stopElement) => {
  let parent = element;
  while (parent && parent !== stopElement) {
    if (isScrollable(parent)) {
      return true;
    }
    parent = parent.parentElement;
  }
  return false;
};

/**
 * borrowed from https://stackoverflow.com/a/46352119
 *
 * @param {HTMLElement} elem
 * @returns {boolean}
 */
const hasCssAnimation = elem => {
  const style = window.getComputedStyle(elem);
  const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
  const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
  return animDuration > 0 || transDuration > 0;
};

/**
 * @param {number} timer
 * @param {boolean} reset
 */
const animateTimerProgressBar = (timer, reset = false) => {
  const timerProgressBar = getTimerProgressBar();
  if (!timerProgressBar) {
    return;
  }
  if (isVisible$1(timerProgressBar)) {
    if (reset) {
      timerProgressBar.style.transition = 'none';
      timerProgressBar.style.width = '100%';
    }
    setTimeout(() => {
      timerProgressBar.style.transition = `width ${timer / 1000}s linear`;
      timerProgressBar.style.width = '0%';
    }, 10);
  }
};
const stopTimerProgressBar = () => {
  const timerProgressBar = getTimerProgressBar();
  if (!timerProgressBar) {
    return;
  }
  const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
  timerProgressBar.style.removeProperty('transition');
  timerProgressBar.style.width = '100%';
  const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
  const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;
  timerProgressBar.style.width = `${timerProgressBarPercent}%`;
};

/**
 * Detect Node env
 *
 * @returns {boolean}
 */
const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';

const sweetHTML = `
 <div aria-labelledby="${swalClasses.title}" aria-describedby="${swalClasses['html-container']}" class="${swalClasses.popup}" tabindex="-1">
   <button type="button" class="${swalClasses.close}"></button>
   <ul class="${swalClasses['progress-steps']}"></ul>
   <div class="${swalClasses.icon}"></div>
   <img class="${swalClasses.image}" />
   <h2 class="${swalClasses.title}" id="${swalClasses.title}"></h2>
   <div class="${swalClasses['html-container']}" id="${swalClasses['html-container']}"></div>
   <input class="${swalClasses.input}" id="${swalClasses.input}" />
   <input type="file" class="${swalClasses.file}" />
   <div class="${swalClasses.range}">
     <input type="range" />
     <output></output>
   </div>
   <select class="${swalClasses.select}" id="${swalClasses.select}"></select>
   <div class="${swalClasses.radio}"></div>
   <label class="${swalClasses.checkbox}">
     <input type="checkbox" id="${swalClasses.checkbox}" />
     <span class="${swalClasses.label}"></span>
   </label>
   <textarea class="${swalClasses.textarea}" id="${swalClasses.textarea}"></textarea>
   <div class="${swalClasses['validation-message']}" id="${swalClasses['validation-message']}"></div>
   <div class="${swalClasses.actions}">
     <div class="${swalClasses.loader}"></div>
     <button type="button" class="${swalClasses.confirm}"></button>
     <button type="button" class="${swalClasses.deny}"></button>
     <button type="button" class="${swalClasses.cancel}"></button>
   </div>
   <div class="${swalClasses.footer}"></div>
   <div class="${swalClasses['timer-progress-bar-container']}">
     <div class="${swalClasses['timer-progress-bar']}"></div>
   </div>
 </div>
`.replace(/(^|\n)\s*/g, '');

/**
 * @returns {boolean}
 */
const resetOldContainer = () => {
  const oldContainer = getContainer();
  if (!oldContainer) {
    return false;
  }
  oldContainer.remove();
  removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);
  return true;
};
const resetValidationMessage$1 = () => {
  globalState.currentInstance.resetValidationMessage();
};
const addInputChangeListeners = () => {
  const popup = getPopup();
  const input = getDirectChildByClass(popup, swalClasses.input);
  const file = getDirectChildByClass(popup, swalClasses.file);
  /** @type {HTMLInputElement} */
  const range = popup.querySelector(`.${swalClasses.range} input`);
  /** @type {HTMLOutputElement} */
  const rangeOutput = popup.querySelector(`.${swalClasses.range} output`);
  const select = getDirectChildByClass(popup, swalClasses.select);
  /** @type {HTMLInputElement} */
  const checkbox = popup.querySelector(`.${swalClasses.checkbox} input`);
  const textarea = getDirectChildByClass(popup, swalClasses.textarea);
  input.oninput = resetValidationMessage$1;
  file.onchange = resetValidationMessage$1;
  select.onchange = resetValidationMessage$1;
  checkbox.onchange = resetValidationMessage$1;
  textarea.oninput = resetValidationMessage$1;
  range.oninput = () => {
    resetValidationMessage$1();
    rangeOutput.value = range.value;
  };
  range.onchange = () => {
    resetValidationMessage$1();
    rangeOutput.value = range.value;
  };
};

/**
 * @param {string | HTMLElement} target
 * @returns {HTMLElement}
 */
const getTarget = target => typeof target === 'string' ? document.querySelector(target) : target;

/**
 * @param {SweetAlertOptions} params
 */
const setupAccessibility = params => {
  const popup = getPopup();
  popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
  popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
  if (!params.toast) {
    popup.setAttribute('aria-modal', 'true');
  }
};

/**
 * @param {HTMLElement} targetElement
 */
const setupRTL = targetElement => {
  if (window.getComputedStyle(targetElement).direction === 'rtl') {
    addClass(getContainer(), swalClasses.rtl);
  }
};

/**
 * Add modal + backdrop + no-war message for Russians to DOM
 *
 * @param {SweetAlertOptions} params
 */
const init$1 = params => {
  // Clean up the old popup container if it exists
  const oldContainerExisted = resetOldContainer();
  if (isNodeEnv()) {
    error('SweetAlert2 requires document to initialize');
    return;
  }
  const container = document.createElement('div');
  container.className = swalClasses.container;
  if (oldContainerExisted) {
    addClass(container, swalClasses['no-transition']);
  }
  setInnerHtml(container, sweetHTML);
  container.dataset['swal2Theme'] = params.theme;
  const targetElement = getTarget(params.target);
  targetElement.appendChild(container);
  if (params.topLayer) {
    container.setAttribute('popover', '');
    container.showPopover();
  }
  setupAccessibility(params);
  setupRTL(targetElement);
  addInputChangeListeners();
};

/**
 * @param {HTMLElement | object | string} param
 * @param {HTMLElement} target
 */
const parseHtmlToContainer = (param, target) => {
  // DOM element
  if (param instanceof HTMLElement) {
    target.appendChild(param);
  }

  // Object
  else if (typeof param === 'object') {
    handleObject(param, target);
  }

  // Plain string
  else if (param) {
    setInnerHtml(target, param);
  }
};

/**
 * @param {any} param
 * @param {HTMLElement} target
 */
const handleObject = (param, target) => {
  // JQuery element(s)
  if (param.jquery) {
    handleJqueryElem(target, param);
  }

  // For other objects use their string representation
  else {
    setInnerHtml(target, param.toString());
  }
};

/**
 * @param {HTMLElement} target
 * @param {any} elem
 */
const handleJqueryElem = (target, elem) => {
  target.textContent = '';
  if (0 in elem) {
    for (let i = 0; i in elem; i++) {
      target.appendChild(elem[i].cloneNode(true));
    }
  } else {
    target.appendChild(elem.cloneNode(true));
  }
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const renderActions = (instance, params) => {
  const actions = getActions();
  const loader = getLoader();
  if (!actions || !loader) {
    return;
  }

  // Actions (buttons) wrapper
  if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
    hide$2(actions);
  } else {
    show(actions);
  }

  // Custom class
  applyCustomClass(actions, params, 'actions');

  // Render all the buttons
  renderButtons(actions, loader, params);

  // Loader
  setInnerHtml(loader, params.loaderHtml || '');
  applyCustomClass(loader, params, 'loader');
};

/**
 * @param {HTMLElement} actions
 * @param {HTMLElement} loader
 * @param {SweetAlertOptions} params
 */
function renderButtons(actions, loader, params) {
  const confirmButton = getConfirmButton();
  const denyButton = getDenyButton();
  const cancelButton = getCancelButton();
  if (!confirmButton || !denyButton || !cancelButton) {
    return;
  }

  // Render buttons
  renderButton(confirmButton, 'confirm', params);
  renderButton(denyButton, 'deny', params);
  renderButton(cancelButton, 'cancel', params);
  handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
  if (params.reverseButtons) {
    if (params.toast) {
      actions.insertBefore(cancelButton, confirmButton);
      actions.insertBefore(denyButton, confirmButton);
    } else {
      actions.insertBefore(cancelButton, loader);
      actions.insertBefore(denyButton, loader);
      actions.insertBefore(confirmButton, loader);
    }
  }
}

/**
 * @param {HTMLElement} confirmButton
 * @param {HTMLElement} denyButton
 * @param {HTMLElement} cancelButton
 * @param {SweetAlertOptions} params
 */
function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
  if (!params.buttonsStyling) {
    removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
    return;
  }
  addClass([confirmButton, denyButton, cancelButton], swalClasses.styled);

  // Apply custom background colors to action buttons
  if (params.confirmButtonColor) {
    confirmButton.style.setProperty('--swal2-confirm-button-background-color', params.confirmButtonColor);
  }
  if (params.denyButtonColor) {
    denyButton.style.setProperty('--swal2-deny-button-background-color', params.denyButtonColor);
  }
  if (params.cancelButtonColor) {
    cancelButton.style.setProperty('--swal2-cancel-button-background-color', params.cancelButtonColor);
  }

  // Apply the outline color to action buttons
  applyOutlineColor(confirmButton);
  applyOutlineColor(denyButton);
  applyOutlineColor(cancelButton);
}

/**
 * @param {HTMLElement} button
 */
function applyOutlineColor(button) {
  const buttonStyle = window.getComputedStyle(button);
  if (buttonStyle.getPropertyValue('--swal2-action-button-focus-box-shadow')) {
    // If the button already has a custom outline color, no need to change it
    return;
  }
  const outlineColor = buttonStyle.backgroundColor.replace(/rgba?\((\d+), (\d+), (\d+).*/, 'rgba($1, $2, $3, 0.5)');
  button.style.setProperty('--swal2-action-button-focus-box-shadow', buttonStyle.getPropertyValue('--swal2-outline').replace(/ rgba\(.*/, ` ${outlineColor}`));
}

/**
 * @param {HTMLElement} button
 * @param {'confirm' | 'deny' | 'cancel'} buttonType
 * @param {SweetAlertOptions} params
 */
function renderButton(button, buttonType, params) {
  const buttonName = /** @type {'Confirm' | 'Deny' | 'Cancel'} */capitalizeFirstLetter(buttonType);
  toggle(button, params[`show${buttonName}Button`], 'inline-block');
  setInnerHtml(button, params[`${buttonType}ButtonText`] || ''); // Set caption text
  button.setAttribute('aria-label', params[`${buttonType}ButtonAriaLabel`] || ''); // ARIA label

  // Add buttons custom classes
  button.className = swalClasses[buttonType];
  applyCustomClass(button, params, `${buttonType}Button`);
}

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const renderCloseButton = (instance, params) => {
  const closeButton = getCloseButton();
  if (!closeButton) {
    return;
  }
  setInnerHtml(closeButton, params.closeButtonHtml || '');

  // Custom class
  applyCustomClass(closeButton, params, 'closeButton');
  toggle(closeButton, params.showCloseButton);
  closeButton.setAttribute('aria-label', params.closeButtonAriaLabel || '');
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const renderContainer = (instance, params) => {
  const container = getContainer();
  if (!container) {
    return;
  }
  handleBackdropParam(container, params.backdrop);
  handlePositionParam(container, params.position);
  handleGrowParam(container, params.grow);

  // Custom class
  applyCustomClass(container, params, 'container');
};

/**
 * @param {HTMLElement} container
 * @param {SweetAlertOptions['backdrop']} backdrop
 */
function handleBackdropParam(container, backdrop) {
  if (typeof backdrop === 'string') {
    container.style.background = backdrop;
  } else if (!backdrop) {
    addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
  }
}

/**
 * @param {HTMLElement} container
 * @param {SweetAlertOptions['position']} position
 */
function handlePositionParam(container, position) {
  if (!position) {
    return;
  }
  if (position in swalClasses) {
    addClass(container, swalClasses[position]);
  } else {
    warn('The "position" parameter is not valid, defaulting to "center"');
    addClass(container, swalClasses.center);
  }
}

/**
 * @param {HTMLElement} container
 * @param {SweetAlertOptions['grow']} grow
 */
function handleGrowParam(container, grow) {
  if (!grow) {
    return;
  }
  addClass(container, swalClasses[`grow-${grow}`]);
}

/**
 * This module contains `WeakMap`s for each effectively-"private  property" that a `Swal` has.
 * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
 * This is the approach that Babel will probably take to implement private methods/fields
 *   https://github.com/tc39/proposal-private-methods
 *   https://github.com/babel/babel/pull/7555
 * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
 *   then we can use that language feature.
 */

var privateProps = {
  innerParams: new WeakMap(),
  domCache: new WeakMap()
};

/// <reference path="../../../../sweetalert2.d.ts"/>


/** @type {InputClass[]} */
const inputClasses = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const renderInput = (instance, params) => {
  const popup = getPopup();
  if (!popup) {
    return;
  }
  const innerParams = privateProps.innerParams.get(instance);
  const rerender = !innerParams || params.input !== innerParams.input;
  inputClasses.forEach(inputClass => {
    const inputContainer = getDirectChildByClass(popup, swalClasses[inputClass]);
    if (!inputContainer) {
      return;
    }

    // set attributes
    setAttributes(inputClass, params.inputAttributes);

    // set class
    inputContainer.className = swalClasses[inputClass];
    if (rerender) {
      hide$2(inputContainer);
    }
  });
  if (params.input) {
    if (rerender) {
      showInput(params);
    }
    // set custom class
    setCustomClass(params);
  }
};

/**
 * @param {SweetAlertOptions} params
 */
const showInput = params => {
  if (!params.input) {
    return;
  }
  if (!renderInputType[params.input]) {
    error(`Unexpected type of input! Expected ${Object.keys(renderInputType).join(' | ')}, got "${params.input}"`);
    return;
  }
  const inputContainer = getInputContainer(params.input);
  if (!inputContainer) {
    return;
  }
  const input = renderInputType[params.input](inputContainer, params);
  show(inputContainer);

  // input autofocus
  if (params.inputAutoFocus) {
    setTimeout(() => {
      focusInput(input);
    });
  }
};

/**
 * @param {HTMLInputElement} input
 */
const removeAttributes = input => {
  for (let i = 0; i < input.attributes.length; i++) {
    const attrName = input.attributes[i].name;
    if (!['id', 'type', 'value', 'style'].includes(attrName)) {
      input.removeAttribute(attrName);
    }
  }
};

/**
 * @param {InputClass} inputClass
 * @param {SweetAlertOptions['inputAttributes']} inputAttributes
 */
const setAttributes = (inputClass, inputAttributes) => {
  const popup = getPopup();
  if (!popup) {
    return;
  }
  const input = getInput$1(popup, inputClass);
  if (!input) {
    return;
  }
  removeAttributes(input);
  for (const attr in inputAttributes) {
    input.setAttribute(attr, inputAttributes[attr]);
  }
};

/**
 * @param {SweetAlertOptions} params
 */
const setCustomClass = params => {
  if (!params.input) {
    return;
  }
  const inputContainer = getInputContainer(params.input);
  if (inputContainer) {
    applyCustomClass(inputContainer, params, 'input');
  }
};

/**
 * @param {HTMLInputElement | HTMLTextAreaElement} input
 * @param {SweetAlertOptions} params
 */
const setInputPlaceholder = (input, params) => {
  if (!input.placeholder && params.inputPlaceholder) {
    input.placeholder = params.inputPlaceholder;
  }
};

/**
 * @param {Input} input
 * @param {Input} prependTo
 * @param {SweetAlertOptions} params
 */
const setInputLabel = (input, prependTo, params) => {
  if (params.inputLabel) {
    const label = document.createElement('label');
    const labelClass = swalClasses['input-label'];
    label.setAttribute('for', input.id);
    label.className = labelClass;
    if (typeof params.customClass === 'object') {
      addClass(label, params.customClass.inputLabel);
    }
    label.innerText = params.inputLabel;
    prependTo.insertAdjacentElement('beforebegin', label);
  }
};

/**
 * @param {SweetAlertInput} inputType
 * @returns {HTMLElement | undefined}
 */
const getInputContainer = inputType => {
  const popup = getPopup();
  if (!popup) {
    return;
  }
  return getDirectChildByClass(popup, swalClasses[(/** @type {SwalClass} */inputType)] || swalClasses.input);
};

/**
 * @param {HTMLInputElement | HTMLOutputElement | HTMLTextAreaElement} input
 * @param {SweetAlertOptions['inputValue']} inputValue
 */
const checkAndSetInputValue = (input, inputValue) => {
  if (['string', 'number'].includes(typeof inputValue)) {
    input.value = `${inputValue}`;
  } else if (!isPromise(inputValue)) {
    warn(`Unexpected type of inputValue! Expected "string", "number" or "Promise", got "${typeof inputValue}"`);
  }
};

/** @type {Record<SweetAlertInput, (input: Input | HTMLElement, params: SweetAlertOptions) => Input>} */
const renderInputType = {};

/**
 * @param {HTMLInputElement} input
 * @param {SweetAlertOptions} params
 * @returns {HTMLInputElement}
 */
renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = renderInputType.search = renderInputType.date = renderInputType['datetime-local'] = renderInputType.time = renderInputType.week = renderInputType.month = /** @type {(input: Input | HTMLElement, params: SweetAlertOptions) => Input} */
(input, params) => {
  checkAndSetInputValue(input, params.inputValue);
  setInputLabel(input, input, params);
  setInputPlaceholder(input, params);
  input.type = params.input;
  return input;
};

/**
 * @param {HTMLInputElement} input
 * @param {SweetAlertOptions} params
 * @returns {HTMLInputElement}
 */
renderInputType.file = (input, params) => {
  setInputLabel(input, input, params);
  setInputPlaceholder(input, params);
  return input;
};

/**
 * @param {HTMLInputElement} range
 * @param {SweetAlertOptions} params
 * @returns {HTMLInputElement}
 */
renderInputType.range = (range, params) => {
  const rangeInput = range.querySelector('input');
  const rangeOutput = range.querySelector('output');
  checkAndSetInputValue(rangeInput, params.inputValue);
  rangeInput.type = params.input;
  checkAndSetInputValue(rangeOutput, params.inputValue);
  setInputLabel(rangeInput, range, params);
  return range;
};

/**
 * @param {HTMLSelectElement} select
 * @param {SweetAlertOptions} params
 * @returns {HTMLSelectElement}
 */
renderInputType.select = (select, params) => {
  select.textContent = '';
  if (params.inputPlaceholder) {
    const placeholder = document.createElement('option');
    setInnerHtml(placeholder, params.inputPlaceholder);
    placeholder.value = '';
    placeholder.disabled = true;
    placeholder.selected = true;
    select.appendChild(placeholder);
  }
  setInputLabel(select, select, params);
  return select;
};

/**
 * @param {HTMLInputElement} radio
 * @returns {HTMLInputElement}
 */
renderInputType.radio = radio => {
  radio.textContent = '';
  return radio;
};

/**
 * @param {HTMLLabelElement} checkboxContainer
 * @param {SweetAlertOptions} params
 * @returns {HTMLInputElement}
 */
renderInputType.checkbox = (checkboxContainer, params) => {
  const checkbox = getInput$1(getPopup(), 'checkbox');
  checkbox.value = '1';
  checkbox.checked = Boolean(params.inputValue);
  const label = checkboxContainer.querySelector('span');
  setInnerHtml(label, params.inputPlaceholder || params.inputLabel);
  return checkbox;
};

/**
 * @param {HTMLTextAreaElement} textarea
 * @param {SweetAlertOptions} params
 * @returns {HTMLTextAreaElement}
 */
renderInputType.textarea = (textarea, params) => {
  checkAndSetInputValue(textarea, params.inputValue);
  setInputPlaceholder(textarea, params);
  setInputLabel(textarea, textarea, params);

  /**
   * @param {HTMLElement} el
   * @returns {number}
   */
  const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight);

  // https://github.com/sweetalert2/sweetalert2/issues/2291
  setTimeout(() => {
    // https://github.com/sweetalert2/sweetalert2/issues/1699
    if ('MutationObserver' in window) {
      const initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
      const textareaResizeHandler = () => {
        // check if texarea is still in document (i.e. popup wasn't closed in the meantime)
        if (!document.body.contains(textarea)) {
          return;
        }
        const textareaWidth = textarea.offsetWidth + getMargin(textarea);
        if (textareaWidth > initialPopupWidth) {
          getPopup().style.width = `${textareaWidth}px`;
        } else {
          applyNumericalStyle(getPopup(), 'width', params.width);
        }
      };
      new MutationObserver(textareaResizeHandler).observe(textarea, {
        attributes: true,
        attributeFilter: ['style']
      });
    }
  });
  return textarea;
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const renderContent = (instance, params) => {
  const htmlContainer = getHtmlContainer();
  if (!htmlContainer) {
    return;
  }
  showWhenInnerHtmlPresent(htmlContainer);
  applyCustomClass(htmlContainer, params, 'htmlContainer');

  // Content as HTML
  if (params.html) {
    parseHtmlToContainer(params.html, htmlContainer);
    show(htmlContainer, 'block');
  }

  // Content as plain text
  else if (params.text) {
    htmlContainer.textContent = params.text;
    show(htmlContainer, 'block');
  }

  // No content
  else {
    hide$2(htmlContainer);
  }
  renderInput(instance, params);
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const renderFooter = (instance, params) => {
  const footer = getFooter();
  if (!footer) {
    return;
  }
  showWhenInnerHtmlPresent(footer);
  toggle(footer, params.footer, 'block');
  if (params.footer) {
    parseHtmlToContainer(params.footer, footer);
  }

  // Custom class
  applyCustomClass(footer, params, 'footer');
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const renderIcon = (instance, params) => {
  const innerParams = privateProps.innerParams.get(instance);
  const icon = getIcon();
  if (!icon) {
    return;
  }

  // if the given icon already rendered, apply the styling without re-rendering the icon
  if (innerParams && params.icon === innerParams.icon) {
    // Custom or default content
    setContent(icon, params);
    applyStyles$2(icon, params);
    return;
  }
  if (!params.icon && !params.iconHtml) {
    hide$2(icon);
    return;
  }
  if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {
    error(`Unknown icon! Expected "success", "error", "warning", "info" or "question", got "${params.icon}"`);
    hide$2(icon);
    return;
  }
  show(icon);

  // Custom or default content
  setContent(icon, params);
  applyStyles$2(icon, params);

  // Animate icon
  addClass(icon, params.showClass && params.showClass.icon);

  // Re-adjust the success icon on system theme change
  const colorSchemeQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  colorSchemeQueryList.addEventListener('change', adjustSuccessIconBackgroundColor);
};

/**
 * @param {HTMLElement} icon
 * @param {SweetAlertOptions} params
 */
const applyStyles$2 = (icon, params) => {
  for (const [iconType, iconClassName] of Object.entries(iconTypes)) {
    if (params.icon !== iconType) {
      removeClass(icon, iconClassName);
    }
  }
  addClass(icon, params.icon && iconTypes[params.icon]);

  // Icon color
  setColor(icon, params);

  // Success icon background color
  adjustSuccessIconBackgroundColor();

  // Custom class
  applyCustomClass(icon, params, 'icon');
};

// Adjust success icon background color to match the popup background color
const adjustSuccessIconBackgroundColor = () => {
  const popup = getPopup();
  if (!popup) {
    return;
  }
  const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
  /** @type {NodeListOf<HTMLElement>} */
  const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
  for (let i = 0; i < successIconParts.length; i++) {
    successIconParts[i].style.backgroundColor = popupBackgroundColor;
  }
};

/**
 *
 * @param {SweetAlertOptions} params
 * @returns {string}
 */
const successIconHtml = params => `
  ${params.animation ? '<div class="swal2-success-circular-line-left"></div>' : ''}
  <span class="swal2-success-line-tip"></span> <span class="swal2-success-line-long"></span>
  <div class="swal2-success-ring"></div>
  ${params.animation ? '<div class="swal2-success-fix"></div>' : ''}
  ${params.animation ? '<div class="swal2-success-circular-line-right"></div>' : ''}
`;
const errorIconHtml = `
  <span class="swal2-x-mark">
    <span class="swal2-x-mark-line-left"></span>
    <span class="swal2-x-mark-line-right"></span>
  </span>
`;

/**
 * @param {HTMLElement} icon
 * @param {SweetAlertOptions} params
 */
const setContent = (icon, params) => {
  if (!params.icon && !params.iconHtml) {
    return;
  }
  let oldContent = icon.innerHTML;
  let newContent = '';
  if (params.iconHtml) {
    newContent = iconContent(params.iconHtml);
  } else if (params.icon === 'success') {
    newContent = successIconHtml(params);
    oldContent = oldContent.replace(/ style=".*?"/g, ''); // undo adjustSuccessIconBackgroundColor()
  } else if (params.icon === 'error') {
    newContent = errorIconHtml;
  } else if (params.icon) {
    const defaultIconHtml = {
      question: '?',
      warning: '!',
      info: 'i'
    };
    newContent = iconContent(defaultIconHtml[params.icon]);
  }
  if (oldContent.trim() !== newContent.trim()) {
    setInnerHtml(icon, newContent);
  }
};

/**
 * @param {HTMLElement} icon
 * @param {SweetAlertOptions} params
 */
const setColor = (icon, params) => {
  if (!params.iconColor) {
    return;
  }
  icon.style.color = params.iconColor;
  icon.style.borderColor = params.iconColor;
  for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {
    setStyle$1(icon, sel, 'background-color', params.iconColor);
  }
  setStyle$1(icon, '.swal2-success-ring', 'border-color', params.iconColor);
};

/**
 * @param {string} content
 * @returns {string}
 */
const iconContent = content => `<div class="${swalClasses['icon-content']}">${content}</div>`;

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const renderImage = (instance, params) => {
  const image = getImage();
  if (!image) {
    return;
  }
  if (!params.imageUrl) {
    hide$2(image);
    return;
  }
  show(image, '');

  // Src, alt
  image.setAttribute('src', params.imageUrl);
  image.setAttribute('alt', params.imageAlt || '');

  // Width, height
  applyNumericalStyle(image, 'width', params.imageWidth);
  applyNumericalStyle(image, 'height', params.imageHeight);

  // Class
  image.className = swalClasses.image;
  applyCustomClass(image, params, 'image');
};

let dragging = false;
let mousedownX = 0;
let mousedownY = 0;
let initialX = 0;
let initialY = 0;

/**
 * @param {HTMLElement} popup
 */
const addDraggableListeners = popup => {
  popup.addEventListener('mousedown', down);
  document.body.addEventListener('mousemove', move);
  popup.addEventListener('mouseup', up);
  popup.addEventListener('touchstart', down);
  document.body.addEventListener('touchmove', move);
  popup.addEventListener('touchend', up);
};

/**
 * @param {HTMLElement} popup
 */
const removeDraggableListeners = popup => {
  popup.removeEventListener('mousedown', down);
  document.body.removeEventListener('mousemove', move);
  popup.removeEventListener('mouseup', up);
  popup.removeEventListener('touchstart', down);
  document.body.removeEventListener('touchmove', move);
  popup.removeEventListener('touchend', up);
};

/**
 * @param {MouseEvent | TouchEvent} event
 */
const down = event => {
  const popup = getPopup();
  if (event.target === popup || getIcon().contains(/** @type {HTMLElement} */event.target)) {
    dragging = true;
    const clientXY = getClientXY(event);
    mousedownX = clientXY.clientX;
    mousedownY = clientXY.clientY;
    initialX = parseInt(popup.style.insetInlineStart) || 0;
    initialY = parseInt(popup.style.insetBlockStart) || 0;
    addClass(popup, 'swal2-dragging');
  }
};

/**
 * @param {MouseEvent | TouchEvent} event
 */
const move = event => {
  const popup = getPopup();
  if (dragging) {
    let {
      clientX,
      clientY
    } = getClientXY(event);
    popup.style.insetInlineStart = `${initialX + (clientX - mousedownX)}px`;
    popup.style.insetBlockStart = `${initialY + (clientY - mousedownY)}px`;
  }
};
const up = () => {
  const popup = getPopup();
  dragging = false;
  removeClass(popup, 'swal2-dragging');
};

/**
 * @param {MouseEvent | TouchEvent} event
 * @returns {{ clientX: number, clientY: number }}
 */
const getClientXY = event => {
  let clientX = 0,
    clientY = 0;
  if (event.type.startsWith('mouse')) {
    clientX = /** @type {MouseEvent} */event.clientX;
    clientY = /** @type {MouseEvent} */event.clientY;
  } else if (event.type.startsWith('touch')) {
    clientX = /** @type {TouchEvent} */event.touches[0].clientX;
    clientY = /** @type {TouchEvent} */event.touches[0].clientY;
  }
  return {
    clientX,
    clientY
  };
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const renderPopup = (instance, params) => {
  const container = getContainer();
  const popup = getPopup();
  if (!container || !popup) {
    return;
  }

  // Width
  // https://github.com/sweetalert2/sweetalert2/issues/2170
  if (params.toast) {
    applyNumericalStyle(container, 'width', params.width);
    popup.style.width = '100%';
    const loader = getLoader();
    if (loader) {
      popup.insertBefore(loader, getIcon());
    }
  } else {
    applyNumericalStyle(popup, 'width', params.width);
  }

  // Padding
  applyNumericalStyle(popup, 'padding', params.padding);

  // Color
  if (params.color) {
    popup.style.color = params.color;
  }

  // Background
  if (params.background) {
    popup.style.background = params.background;
  }
  hide$2(getValidationMessage());

  // Classes
  addClasses$1(popup, params);
  if (params.draggable && !params.toast) {
    addClass(popup, swalClasses.draggable);
    addDraggableListeners(popup);
  } else {
    removeClass(popup, swalClasses.draggable);
    removeDraggableListeners(popup);
  }
};

/**
 * @param {HTMLElement} popup
 * @param {SweetAlertOptions} params
 */
const addClasses$1 = (popup, params) => {
  const showClass = params.showClass || {};
  // Default Class + showClass when updating Swal.update({})
  popup.className = `${swalClasses.popup} ${isVisible$1(popup) ? showClass.popup : ''}`;
  if (params.toast) {
    addClass([document.documentElement, document.body], swalClasses['toast-shown']);
    addClass(popup, swalClasses.toast);
  } else {
    addClass(popup, swalClasses.modal);
  }

  // Custom class
  applyCustomClass(popup, params, 'popup');
  // TODO: remove in the next major
  if (typeof params.customClass === 'string') {
    addClass(popup, params.customClass);
  }

  // Icon class (#1842)
  if (params.icon) {
    addClass(popup, swalClasses[`icon-${params.icon}`]);
  }
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const renderProgressSteps = (instance, params) => {
  const progressStepsContainer = getProgressSteps();
  if (!progressStepsContainer) {
    return;
  }
  const {
    progressSteps,
    currentProgressStep
  } = params;
  if (!progressSteps || progressSteps.length === 0 || currentProgressStep === undefined) {
    hide$2(progressStepsContainer);
    return;
  }
  show(progressStepsContainer);
  progressStepsContainer.textContent = '';
  if (currentProgressStep >= progressSteps.length) {
    warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
  }
  progressSteps.forEach((step, index) => {
    const stepEl = createStepElement(step);
    progressStepsContainer.appendChild(stepEl);
    if (index === currentProgressStep) {
      addClass(stepEl, swalClasses['active-progress-step']);
    }
    if (index !== progressSteps.length - 1) {
      const lineEl = createLineElement(params);
      progressStepsContainer.appendChild(lineEl);
    }
  });
};

/**
 * @param {string} step
 * @returns {HTMLLIElement}
 */
const createStepElement = step => {
  const stepEl = document.createElement('li');
  addClass(stepEl, swalClasses['progress-step']);
  setInnerHtml(stepEl, step);
  return stepEl;
};

/**
 * @param {SweetAlertOptions} params
 * @returns {HTMLLIElement}
 */
const createLineElement = params => {
  const lineEl = document.createElement('li');
  addClass(lineEl, swalClasses['progress-step-line']);
  if (params.progressStepsDistance) {
    applyNumericalStyle(lineEl, 'width', params.progressStepsDistance);
  }
  return lineEl;
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const renderTitle = (instance, params) => {
  const title = getTitle$1();
  if (!title) {
    return;
  }
  showWhenInnerHtmlPresent(title);
  toggle(title, params.title || params.titleText, 'block');
  if (params.title) {
    parseHtmlToContainer(params.title, title);
  }
  if (params.titleText) {
    title.innerText = params.titleText;
  }

  // Custom class
  applyCustomClass(title, params, 'title');
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const render = (instance, params) => {
  renderPopup(instance, params);
  renderContainer(instance, params);
  renderProgressSteps(instance, params);
  renderIcon(instance, params);
  renderImage(instance, params);
  renderTitle(instance, params);
  renderCloseButton(instance, params);
  renderContent(instance, params);
  renderActions(instance, params);
  renderFooter(instance, params);
  const popup = getPopup();
  if (typeof params.didRender === 'function' && popup) {
    params.didRender(popup);
  }
  globalState.eventEmitter.emit('didRender', popup);
};

/*
 * Global function to determine if SweetAlert2 popup is shown
 */
const isVisible = () => {
  return isVisible$1(getPopup());
};

/*
 * Global function to click 'Confirm' button
 */
const clickConfirm = () => {
  var _dom$getConfirmButton;
  return (_dom$getConfirmButton = getConfirmButton()) === null || _dom$getConfirmButton === void 0 ? void 0 : _dom$getConfirmButton.click();
};

/*
 * Global function to click 'Deny' button
 */
const clickDeny = () => {
  var _dom$getDenyButton;
  return (_dom$getDenyButton = getDenyButton()) === null || _dom$getDenyButton === void 0 ? void 0 : _dom$getDenyButton.click();
};

/*
 * Global function to click 'Cancel' button
 */
const clickCancel = () => {
  var _dom$getCancelButton;
  return (_dom$getCancelButton = getCancelButton()) === null || _dom$getCancelButton === void 0 ? void 0 : _dom$getCancelButton.click();
};

/** @typedef {'cancel' | 'backdrop' | 'close' | 'esc' | 'timer'} DismissReason */

/** @type {Record<DismissReason, DismissReason>} */
const DismissReason = Object.freeze({
  cancel: 'cancel',
  backdrop: 'backdrop',
  close: 'close',
  esc: 'esc',
  timer: 'timer'
});

/**
 * @param {GlobalState} globalState
 */
const removeKeydownHandler = globalState => {
  if (globalState.keydownTarget && globalState.keydownHandlerAdded) {
    globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
      capture: globalState.keydownListenerCapture
    });
    globalState.keydownHandlerAdded = false;
  }
};

/**
 * @param {GlobalState} globalState
 * @param {SweetAlertOptions} innerParams
 * @param {*} dismissWith
 */
const addKeydownHandler = (globalState, innerParams, dismissWith) => {
  removeKeydownHandler(globalState);
  if (!innerParams.toast) {
    globalState.keydownHandler = e => keydownHandler(innerParams, e, dismissWith);
    globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();
    globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
    globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {
      capture: globalState.keydownListenerCapture
    });
    globalState.keydownHandlerAdded = true;
  }
};

/**
 * @param {number} index
 * @param {number} increment
 */
const setFocus = (index, increment) => {
  var _dom$getPopup;
  const focusableElements = getFocusableElements();
  // search for visible elements and select the next possible match
  if (focusableElements.length) {
    index = index + increment;

    // shift + tab when .swal2-popup is focused
    if (index === -2) {
      index = focusableElements.length - 1;
    }

    // rollover to first item
    if (index === focusableElements.length) {
      index = 0;

      // go to last item
    } else if (index === -1) {
      index = focusableElements.length - 1;
    }
    focusableElements[index].focus();
    return;
  }
  // no visible focusable elements, focus the popup
  (_dom$getPopup = getPopup()) === null || _dom$getPopup === void 0 || _dom$getPopup.focus();
};
const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];
const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];

/**
 * @param {SweetAlertOptions} innerParams
 * @param {KeyboardEvent} event
 * @param {Function} dismissWith
 */
const keydownHandler = (innerParams, event, dismissWith) => {
  if (!innerParams) {
    return; // This instance has already been destroyed
  }

  // Ignore keydown during IME composition
  // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event#ignoring_keydown_during_ime_composition
  // https://github.com/sweetalert2/sweetalert2/issues/720
  // https://github.com/sweetalert2/sweetalert2/issues/2406
  if (event.isComposing || event.keyCode === 229) {
    return;
  }
  if (innerParams.stopKeydownPropagation) {
    event.stopPropagation();
  }

  // ENTER
  if (event.key === 'Enter') {
    handleEnter(event, innerParams);
  }

  // TAB
  else if (event.key === 'Tab') {
    handleTab(event);
  }

  // ARROWS - switch focus between buttons
  else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(event.key)) {
    handleArrows(event.key);
  }

  // ESC
  else if (event.key === 'Escape') {
    handleEsc(event, innerParams, dismissWith);
  }
};

/**
 * @param {KeyboardEvent} event
 * @param {SweetAlertOptions} innerParams
 */
const handleEnter = (event, innerParams) => {
  // https://github.com/sweetalert2/sweetalert2/issues/2386
  if (!callIfFunction(innerParams.allowEnterKey)) {
    return;
  }
  const input = getInput$1(getPopup(), innerParams.input);
  if (event.target && input && event.target instanceof HTMLElement && event.target.outerHTML === input.outerHTML) {
    if (['textarea', 'file'].includes(innerParams.input)) {
      return; // do not submit
    }
    clickConfirm();
    event.preventDefault();
  }
};

/**
 * @param {KeyboardEvent} event
 */
const handleTab = event => {
  const targetElement = event.target;
  const focusableElements = getFocusableElements();
  let btnIndex = -1;
  for (let i = 0; i < focusableElements.length; i++) {
    if (targetElement === focusableElements[i]) {
      btnIndex = i;
      break;
    }
  }

  // Cycle to the next button
  if (!event.shiftKey) {
    setFocus(btnIndex, 1);
  }

  // Cycle to the prev button
  else {
    setFocus(btnIndex, -1);
  }
  event.stopPropagation();
  event.preventDefault();
};

/**
 * @param {string} key
 */
const handleArrows = key => {
  const actions = getActions();
  const confirmButton = getConfirmButton();
  const denyButton = getDenyButton();
  const cancelButton = getCancelButton();
  if (!actions || !confirmButton || !denyButton || !cancelButton) {
    return;
  }
  /** @type HTMLElement[] */
  const buttons = [confirmButton, denyButton, cancelButton];
  if (document.activeElement instanceof HTMLElement && !buttons.includes(document.activeElement)) {
    return;
  }
  const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';
  let buttonToFocus = document.activeElement;
  if (!buttonToFocus) {
    return;
  }
  for (let i = 0; i < actions.children.length; i++) {
    buttonToFocus = buttonToFocus[sibling];
    if (!buttonToFocus) {
      return;
    }
    if (buttonToFocus instanceof HTMLButtonElement && isVisible$1(buttonToFocus)) {
      break;
    }
  }
  if (buttonToFocus instanceof HTMLButtonElement) {
    buttonToFocus.focus();
  }
};

/**
 * @param {KeyboardEvent} event
 * @param {SweetAlertOptions} innerParams
 * @param {Function} dismissWith
 */
const handleEsc = (event, innerParams, dismissWith) => {
  event.preventDefault();
  if (callIfFunction(innerParams.allowEscapeKey)) {
    dismissWith(DismissReason.esc);
  }
};

/**
 * This module contains `WeakMap`s for each effectively-"private  property" that a `Swal` has.
 * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
 * This is the approach that Babel will probably take to implement private methods/fields
 *   https://github.com/tc39/proposal-private-methods
 *   https://github.com/babel/babel/pull/7555
 * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
 *   then we can use that language feature.
 */

var privateMethods = {
  swalPromiseResolve: new WeakMap(),
  swalPromiseReject: new WeakMap()
};

// From https://developer.paciellogroup.com/blog/2018/06/the-current-state-of-modal-dialog-accessibility/
// Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
// elements not within the active modal dialog will not be surfaced if a user opens a screen
// reader’s list of elements (headings, form controls, landmarks, etc.) in the document.

const setAriaHidden = () => {
  const container = getContainer();
  const bodyChildren = Array.from(document.body.children);
  bodyChildren.forEach(el => {
    if (el.contains(container)) {
      return;
    }
    if (el.hasAttribute('aria-hidden')) {
      el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden') || '');
    }
    el.setAttribute('aria-hidden', 'true');
  });
};
const unsetAriaHidden = () => {
  const bodyChildren = Array.from(document.body.children);
  bodyChildren.forEach(el => {
    if (el.hasAttribute('data-previous-aria-hidden')) {
      el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden') || '');
      el.removeAttribute('data-previous-aria-hidden');
    } else {
      el.removeAttribute('aria-hidden');
    }
  });
};

// @ts-ignore
const isSafariOrIOS = typeof window !== 'undefined' && !!window.GestureEvent; // true for Safari desktop + all iOS browsers https://stackoverflow.com/a/70585394

/**
 * Fix iOS scrolling
 * http://stackoverflow.com/q/39626302
 */
const iOSfix = () => {
  if (isSafariOrIOS && !hasClass(document.body, swalClasses.iosfix)) {
    const offset = document.body.scrollTop;
    document.body.style.top = `${offset * -1}px`;
    addClass(document.body, swalClasses.iosfix);
    lockBodyScroll();
  }
};

/**
 * https://github.com/sweetalert2/sweetalert2/issues/1246
 */
const lockBodyScroll = () => {
  const container = getContainer();
  if (!container) {
    return;
  }
  /** @type {boolean} */
  let preventTouchMove;
  /**
   * @param {TouchEvent} event
   */
  container.ontouchstart = event => {
    preventTouchMove = shouldPreventTouchMove(event);
  };
  /**
   * @param {TouchEvent} event
   */
  container.ontouchmove = event => {
    if (preventTouchMove) {
      event.preventDefault();
      event.stopPropagation();
    }
  };
};

/**
 * @param {TouchEvent} event
 * @returns {boolean}
 */
const shouldPreventTouchMove = event => {
  const target = event.target;
  const container = getContainer();
  const htmlContainer = getHtmlContainer();
  if (!container || !htmlContainer) {
    return false;
  }
  if (isStylus(event) || isZoom(event)) {
    return false;
  }
  if (target === container) {
    return true;
  }
  if (!isScrollable(container) && target instanceof HTMLElement && !selfOrParentIsScrollable(target, htmlContainer) &&
  // #2823
  target.tagName !== 'INPUT' &&
  // #1603
  target.tagName !== 'TEXTAREA' &&
  // #2266
  !(isScrollable(htmlContainer) &&
  // #1944
  htmlContainer.contains(target))) {
    return true;
  }
  return false;
};

/**
 * https://github.com/sweetalert2/sweetalert2/issues/1786
 *
 * @param {*} event
 * @returns {boolean}
 */
const isStylus = event => {
  return event.touches && event.touches.length && event.touches[0].touchType === 'stylus';
};

/**
 * https://github.com/sweetalert2/sweetalert2/issues/1891
 *
 * @param {TouchEvent} event
 * @returns {boolean}
 */
const isZoom = event => {
  return event.touches && event.touches.length > 1;
};
const undoIOSfix = () => {
  if (hasClass(document.body, swalClasses.iosfix)) {
    const offset = parseInt(document.body.style.top, 10);
    removeClass(document.body, swalClasses.iosfix);
    document.body.style.top = '';
    document.body.scrollTop = offset * -1;
  }
};

/**
 * Measure scrollbar width for padding body during modal show/hide
 * https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
 *
 * @returns {number}
 */
const measureScrollbar = () => {
  const scrollDiv = document.createElement('div');
  scrollDiv.className = swalClasses['scrollbar-measure'];
  document.body.appendChild(scrollDiv);
  const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
  document.body.removeChild(scrollDiv);
  return scrollbarWidth;
};

/**
 * Remember state in cases where opening and handling a modal will fiddle with it.
 * @type {number | null}
 */
let previousBodyPadding = null;

/**
 * @param {string} initialBodyOverflow
 */
const replaceScrollbarWithPadding = initialBodyOverflow => {
  // for queues, do not do this more than once
  if (previousBodyPadding !== null) {
    return;
  }
  // if the body has overflow
  if (document.body.scrollHeight > window.innerHeight || initialBodyOverflow === 'scroll' // https://github.com/sweetalert2/sweetalert2/issues/2663
  ) {
    // add padding so the content doesn't shift after removal of scrollbar
    previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
    document.body.style.paddingRight = `${previousBodyPadding + measureScrollbar()}px`;
  }
};
const undoReplaceScrollbarWithPadding = () => {
  if (previousBodyPadding !== null) {
    document.body.style.paddingRight = `${previousBodyPadding}px`;
    previousBodyPadding = null;
  }
};

/**
 * @param {SweetAlert} instance
 * @param {HTMLElement} container
 * @param {boolean} returnFocus
 * @param {Function} didClose
 */
function removePopupAndResetState(instance, container, returnFocus, didClose) {
  if (isToast()) {
    triggerDidCloseAndDispose(instance, didClose);
  } else {
    restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));
    removeKeydownHandler(globalState);
  }

  // workaround for https://github.com/sweetalert2/sweetalert2/issues/2088
  // for some reason removing the container in Safari will scroll the document to bottom
  if (isSafariOrIOS) {
    container.setAttribute('style', 'display:none !important');
    container.removeAttribute('class');
    container.innerHTML = '';
  } else {
    container.remove();
  }
  if (isModal()) {
    undoReplaceScrollbarWithPadding();
    undoIOSfix();
    unsetAriaHidden();
  }
  removeBodyClasses();
}

/**
 * Remove SweetAlert2 classes from body
 */
function removeBodyClasses() {
  removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);
}

/**
 * Instance method to close sweetAlert
 *
 * @param {any} resolveValue
 */
function close(resolveValue) {
  resolveValue = prepareResolveValue(resolveValue);
  const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
  const didClose = triggerClosePopup(this);
  if (this.isAwaitingPromise) {
    // A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335
    if (!resolveValue.isDismissed) {
      handleAwaitingPromise(this);
      swalPromiseResolve(resolveValue);
    }
  } else if (didClose) {
    // Resolve Swal promise
    swalPromiseResolve(resolveValue);
  }
}
const triggerClosePopup = instance => {
  const popup = getPopup();
  if (!popup) {
    return false;
  }
  const innerParams = privateProps.innerParams.get(instance);
  if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
    return false;
  }
  removeClass(popup, innerParams.showClass.popup);
  addClass(popup, innerParams.hideClass.popup);
  const backdrop = getContainer();
  removeClass(backdrop, innerParams.showClass.backdrop);
  addClass(backdrop, innerParams.hideClass.backdrop);
  handlePopupAnimation(instance, popup, innerParams);
  return true;
};

/**
 * @param {any} error
 */
function rejectPromise(error) {
  const rejectPromise = privateMethods.swalPromiseReject.get(this);
  handleAwaitingPromise(this);
  if (rejectPromise) {
    // Reject Swal promise
    rejectPromise(error);
  }
}

/**
 * @param {SweetAlert} instance
 */
const handleAwaitingPromise = instance => {
  if (instance.isAwaitingPromise) {
    delete instance.isAwaitingPromise;
    // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335
    if (!privateProps.innerParams.get(instance)) {
      instance._destroy();
    }
  }
};

/**
 * @param {any} resolveValue
 * @returns {SweetAlertResult}
 */
const prepareResolveValue = resolveValue => {
  // When user calls Swal.close()
  if (typeof resolveValue === 'undefined') {
    return {
      isConfirmed: false,
      isDenied: false,
      isDismissed: true
    };
  }
  return Object.assign({
    isConfirmed: false,
    isDenied: false,
    isDismissed: false
  }, resolveValue);
};

/**
 * @param {SweetAlert} instance
 * @param {HTMLElement} popup
 * @param {SweetAlertOptions} innerParams
 */
const handlePopupAnimation = (instance, popup, innerParams) => {
  var _globalState$eventEmi;
  const container = getContainer();
  // If animation is supported, animate
  const animationIsSupported = hasCssAnimation(popup);
  if (typeof innerParams.willClose === 'function') {
    innerParams.willClose(popup);
  }
  (_globalState$eventEmi = globalState.eventEmitter) === null || _globalState$eventEmi === void 0 || _globalState$eventEmi.emit('willClose', popup);
  if (animationIsSupported) {
    animatePopup(instance, popup, container, innerParams.returnFocus, innerParams.didClose);
  } else {
    // Otherwise, remove immediately
    removePopupAndResetState(instance, container, innerParams.returnFocus, innerParams.didClose);
  }
};

/**
 * @param {SweetAlert} instance
 * @param {HTMLElement} popup
 * @param {HTMLElement} container
 * @param {boolean} returnFocus
 * @param {Function} didClose
 */
const animatePopup = (instance, popup, container, returnFocus, didClose) => {
  globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);
  /**
   * @param {AnimationEvent | TransitionEvent} e
   */
  const swalCloseAnimationFinished = function (e) {
    if (e.target === popup) {
      var _globalState$swalClos;
      (_globalState$swalClos = globalState.swalCloseEventFinishedCallback) === null || _globalState$swalClos === void 0 || _globalState$swalClos.call(globalState);
      delete globalState.swalCloseEventFinishedCallback;
      popup.removeEventListener('animationend', swalCloseAnimationFinished);
      popup.removeEventListener('transitionend', swalCloseAnimationFinished);
    }
  };
  popup.addEventListener('animationend', swalCloseAnimationFinished);
  popup.addEventListener('transitionend', swalCloseAnimationFinished);
};

/**
 * @param {SweetAlert} instance
 * @param {Function} didClose
 */
const triggerDidCloseAndDispose = (instance, didClose) => {
  setTimeout(() => {
    var _globalState$eventEmi2;
    if (typeof didClose === 'function') {
      didClose.bind(instance.params)();
    }
    (_globalState$eventEmi2 = globalState.eventEmitter) === null || _globalState$eventEmi2 === void 0 || _globalState$eventEmi2.emit('didClose');
    // instance might have been destroyed already
    if (instance._destroy) {
      instance._destroy();
    }
  });
};

/**
 * Shows loader (spinner), this is useful with AJAX requests.
 * By default the loader be shown instead of the "Confirm" button.
 *
 * @param {HTMLButtonElement | null} [buttonToReplace]
 */
const showLoading = buttonToReplace => {
  let popup = getPopup();
  if (!popup) {
    new Swal();
  }
  popup = getPopup();
  if (!popup) {
    return;
  }
  const loader = getLoader();
  if (isToast()) {
    hide$2(getIcon());
  } else {
    replaceButton(popup, buttonToReplace);
  }
  show(loader);
  popup.setAttribute('data-loading', 'true');
  popup.setAttribute('aria-busy', 'true');
  popup.focus();
};

/**
 * @param {HTMLElement} popup
 * @param {HTMLButtonElement | null} [buttonToReplace]
 */
const replaceButton = (popup, buttonToReplace) => {
  const actions = getActions();
  const loader = getLoader();
  if (!actions || !loader) {
    return;
  }
  if (!buttonToReplace && isVisible$1(getConfirmButton())) {
    buttonToReplace = getConfirmButton();
  }
  show(actions);
  if (buttonToReplace) {
    hide$2(buttonToReplace);
    loader.setAttribute('data-button-to-replace', buttonToReplace.className);
    actions.insertBefore(loader, buttonToReplace);
  }
  addClass([popup, actions], swalClasses.loading);
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const handleInputOptionsAndValue = (instance, params) => {
  if (params.input === 'select' || params.input === 'radio') {
    handleInputOptions(instance, params);
  } else if (['text', 'email', 'number', 'tel', 'textarea'].some(i => i === params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {
    showLoading(getConfirmButton());
    handleInputValue(instance, params);
  }
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} innerParams
 * @returns {SweetAlertInputValue}
 */
const getInputValue = (instance, innerParams) => {
  const input = instance.getInput();
  if (!input) {
    return null;
  }
  switch (innerParams.input) {
    case 'checkbox':
      return getCheckboxValue(input);
    case 'radio':
      return getRadioValue(input);
    case 'file':
      return getFileValue(input);
    default:
      return innerParams.inputAutoTrim ? input.value.trim() : input.value;
  }
};

/**
 * @param {HTMLInputElement} input
 * @returns {number}
 */
const getCheckboxValue = input => input.checked ? 1 : 0;

/**
 * @param {HTMLInputElement} input
 * @returns {string | null}
 */
const getRadioValue = input => input.checked ? input.value : null;

/**
 * @param {HTMLInputElement} input
 * @returns {FileList | File | null}
 */
const getFileValue = input => input.files && input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const handleInputOptions = (instance, params) => {
  const popup = getPopup();
  if (!popup) {
    return;
  }
  /**
   * @param {Record<string, any>} inputOptions
   */
  const processInputOptions = inputOptions => {
    if (params.input === 'select') {
      populateSelectOptions(popup, formatInputOptions(inputOptions), params);
    } else if (params.input === 'radio') {
      populateRadioOptions(popup, formatInputOptions(inputOptions), params);
    }
  };
  if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {
    showLoading(getConfirmButton());
    asPromise(params.inputOptions).then(inputOptions => {
      instance.hideLoading();
      processInputOptions(inputOptions);
    });
  } else if (typeof params.inputOptions === 'object') {
    processInputOptions(params.inputOptions);
  } else {
    error(`Unexpected type of inputOptions! Expected object, Map or Promise, got ${typeof params.inputOptions}`);
  }
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertOptions} params
 */
const handleInputValue = (instance, params) => {
  const input = instance.getInput();
  if (!input) {
    return;
  }
  hide$2(input);
  asPromise(params.inputValue).then(inputValue => {
    input.value = params.input === 'number' ? `${parseFloat(inputValue) || 0}` : `${inputValue}`;
    show(input);
    input.focus();
    instance.hideLoading();
  }).catch(err => {
    error(`Error in inputValue promise: ${err}`);
    input.value = '';
    show(input);
    input.focus();
    instance.hideLoading();
  });
};

/**
 * @param {HTMLElement} popup
 * @param {InputOptionFlattened[]} inputOptions
 * @param {SweetAlertOptions} params
 */
function populateSelectOptions(popup, inputOptions, params) {
  const select = getDirectChildByClass(popup, swalClasses.select);
  if (!select) {
    return;
  }
  /**
   * @param {HTMLElement} parent
   * @param {string} optionLabel
   * @param {string} optionValue
   */
  const renderOption = (parent, optionLabel, optionValue) => {
    const option = document.createElement('option');
    option.value = optionValue;
    setInnerHtml(option, optionLabel);
    option.selected = isSelected(optionValue, params.inputValue);
    parent.appendChild(option);
  };
  inputOptions.forEach(inputOption => {
    const optionValue = inputOption[0];
    const optionLabel = inputOption[1];
    // <optgroup> spec:
    // https://www.w3.org/TR/html401/interact/forms.html#h-17.6
    // "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..."
    // check whether this is a <optgroup>
    if (Array.isArray(optionLabel)) {
      // if it is an array, then it is an <optgroup>
      const optgroup = document.createElement('optgroup');
      optgroup.label = optionValue;
      optgroup.disabled = false; // not configurable for now
      select.appendChild(optgroup);
      optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));
    } else {
      // case of <option>
      renderOption(select, optionLabel, optionValue);
    }
  });
  select.focus();
}

/**
 * @param {HTMLElement} popup
 * @param {InputOptionFlattened[]} inputOptions
 * @param {SweetAlertOptions} params
 */
function populateRadioOptions(popup, inputOptions, params) {
  const radio = getDirectChildByClass(popup, swalClasses.radio);
  if (!radio) {
    return;
  }
  inputOptions.forEach(inputOption => {
    const radioValue = inputOption[0];
    const radioLabel = inputOption[1];
    const radioInput = document.createElement('input');
    const radioLabelElement = document.createElement('label');
    radioInput.type = 'radio';
    radioInput.name = swalClasses.radio;
    radioInput.value = radioValue;
    if (isSelected(radioValue, params.inputValue)) {
      radioInput.checked = true;
    }
    const label = document.createElement('span');
    setInnerHtml(label, radioLabel);
    label.className = swalClasses.label;
    radioLabelElement.appendChild(radioInput);
    radioLabelElement.appendChild(label);
    radio.appendChild(radioLabelElement);
  });
  const radios = radio.querySelectorAll('input');
  if (radios.length) {
    radios[0].focus();
  }
}

/**
 * Converts `inputOptions` into an array of `[value, label]`s
 *
 * @param {Record<string, any>} inputOptions
 * @typedef {string[]} InputOptionFlattened
 * @returns {InputOptionFlattened[]}
 */
const formatInputOptions = inputOptions => {
  /** @type {InputOptionFlattened[]} */
  const result = [];
  if (inputOptions instanceof Map) {
    inputOptions.forEach((value, key) => {
      let valueFormatted = value;
      if (typeof valueFormatted === 'object') {
        // case of <optgroup>
        valueFormatted = formatInputOptions(valueFormatted);
      }
      result.push([key, valueFormatted]);
    });
  } else {
    Object.keys(inputOptions).forEach(key => {
      let valueFormatted = inputOptions[key];
      if (typeof valueFormatted === 'object') {
        // case of <optgroup>
        valueFormatted = formatInputOptions(valueFormatted);
      }
      result.push([key, valueFormatted]);
    });
  }
  return result;
};

/**
 * @param {string} optionValue
 * @param {SweetAlertInputValue} inputValue
 * @returns {boolean}
 */
const isSelected = (optionValue, inputValue) => {
  return !!inputValue && inputValue.toString() === optionValue.toString();
};

/**
 * @param {SweetAlert} instance
 */
const handleConfirmButtonClick = instance => {
  const innerParams = privateProps.innerParams.get(instance);
  instance.disableButtons();
  if (innerParams.input) {
    handleConfirmOrDenyWithInput(instance, 'confirm');
  } else {
    confirm(instance, true);
  }
};

/**
 * @param {SweetAlert} instance
 */
const handleDenyButtonClick = instance => {
  const innerParams = privateProps.innerParams.get(instance);
  instance.disableButtons();
  if (innerParams.returnInputValueOnDeny) {
    handleConfirmOrDenyWithInput(instance, 'deny');
  } else {
    deny(instance, false);
  }
};

/**
 * @param {SweetAlert} instance
 * @param {Function} dismissWith
 */
const handleCancelButtonClick = (instance, dismissWith) => {
  instance.disableButtons();
  dismissWith(DismissReason.cancel);
};

/**
 * @param {SweetAlert} instance
 * @param {'confirm' | 'deny'} type
 */
const handleConfirmOrDenyWithInput = (instance, type) => {
  const innerParams = privateProps.innerParams.get(instance);
  if (!innerParams.input) {
    error(`The "input" parameter is needed to be set when using returnInputValueOn${capitalizeFirstLetter(type)}`);
    return;
  }
  const input = instance.getInput();
  const inputValue = getInputValue(instance, innerParams);
  if (innerParams.inputValidator) {
    handleInputValidator(instance, inputValue, type);
  } else if (input && !input.checkValidity()) {
    instance.enableButtons();
    instance.showValidationMessage(innerParams.validationMessage || input.validationMessage);
  } else if (type === 'deny') {
    deny(instance, inputValue);
  } else {
    confirm(instance, inputValue);
  }
};

/**
 * @param {SweetAlert} instance
 * @param {SweetAlertInputValue} inputValue
 * @param {'confirm' | 'deny'} type
 */
const handleInputValidator = (instance, inputValue, type) => {
  const innerParams = privateProps.innerParams.get(instance);
  instance.disableInput();
  const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));
  validationPromise.then(validationMessage => {
    instance.enableButtons();
    instance.enableInput();
    if (validationMessage) {
      instance.showValidationMessage(validationMessage);
    } else if (type === 'deny') {
      deny(instance, inputValue);
    } else {
      confirm(instance, inputValue);
    }
  });
};

/**
 * @param {SweetAlert} instance
 * @param {any} value
 */
const deny = (instance, value) => {
  const innerParams = privateProps.innerParams.get(instance || undefined);
  if (innerParams.showLoaderOnDeny) {
    showLoading(getDenyButton());
  }
  if (innerParams.preDeny) {
    instance.isAwaitingPromise = true; // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preDeny's promise is received
    const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));
    preDenyPromise.then(preDenyValue => {
      if (preDenyValue === false) {
        instance.hideLoading();
        handleAwaitingPromise(instance);
      } else {
        instance.close({
          isDenied: true,
          value: typeof preDenyValue === 'undefined' ? value : preDenyValue
        });
      }
    }).catch(error => rejectWith(instance || undefined, error));
  } else {
    instance.close({
      isDenied: true,
      value
    });
  }
};

/**
 * @param {SweetAlert} instance
 * @param {any} value
 */
const succeedWith = (instance, value) => {
  instance.close({
    isConfirmed: true,
    value
  });
};

/**
 *
 * @param {SweetAlert} instance
 * @param {string} error
 */
const rejectWith = (instance, error) => {
  instance.rejectPromise(error);
};

/**
 *
 * @param {SweetAlert} instance
 * @param {any} value
 */
const confirm = (instance, value) => {
  const innerParams = privateProps.innerParams.get(instance || undefined);
  if (innerParams.showLoaderOnConfirm) {
    showLoading();
  }
  if (innerParams.preConfirm) {
    instance.resetValidationMessage();
    instance.isAwaitingPromise = true; // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preConfirm's promise is received
    const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));
    preConfirmPromise.then(preConfirmValue => {
      if (isVisible$1(getValidationMessage()) || preConfirmValue === false) {
        instance.hideLoading();
        handleAwaitingPromise(instance);
      } else {
        succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
      }
    }).catch(error => rejectWith(instance || undefined, error));
  } else {
    succeedWith(instance, value);
  }
};

/**
 * Hides loader and shows back the button which was hidden by .showLoading()
 */
function hideLoading() {
  // do nothing if popup is closed
  const innerParams = privateProps.innerParams.get(this);
  if (!innerParams) {
    return;
  }
  const domCache = privateProps.domCache.get(this);
  hide$2(domCache.loader);
  if (isToast()) {
    if (innerParams.icon) {
      show(getIcon());
    }
  } else {
    showRelatedButton(domCache);
  }
  removeClass([domCache.popup, domCache.actions], swalClasses.loading);
  domCache.popup.removeAttribute('aria-busy');
  domCache.popup.removeAttribute('data-loading');
  domCache.confirmButton.disabled = false;
  domCache.denyButton.disabled = false;
  domCache.cancelButton.disabled = false;
}
const showRelatedButton = domCache => {
  const buttonToReplace = domCache.popup.getElementsByClassName(domCache.loader.getAttribute('data-button-to-replace'));
  if (buttonToReplace.length) {
    show(buttonToReplace[0], 'inline-block');
  } else if (allButtonsAreHidden()) {
    hide$2(domCache.actions);
  }
};

/**
 * Gets the input DOM node, this method works with input parameter.
 *
 * @returns {HTMLInputElement | null}
 */
function getInput() {
  const innerParams = privateProps.innerParams.get(this);
  const domCache = privateProps.domCache.get(this);
  if (!domCache) {
    return null;
  }
  return getInput$1(domCache.popup, innerParams.input);
}

/**
 * @param {SweetAlert} instance
 * @param {string[]} buttons
 * @param {boolean} disabled
 */
function setButtonsDisabled(instance, buttons, disabled) {
  const domCache = privateProps.domCache.get(instance);
  buttons.forEach(button => {
    domCache[button].disabled = disabled;
  });
}

/**
 * @param {HTMLInputElement | null} input
 * @param {boolean} disabled
 */
function setInputDisabled(input, disabled) {
  const popup = getPopup();
  if (!popup || !input) {
    return;
  }
  if (input.type === 'radio') {
    /** @type {NodeListOf<HTMLInputElement>} */
    const radios = popup.querySelectorAll(`[name="${swalClasses.radio}"]`);
    for (let i = 0; i < radios.length; i++) {
      radios[i].disabled = disabled;
    }
  } else {
    input.disabled = disabled;
  }
}

/**
 * Enable all the buttons
 * @this {SweetAlert}
 */
function enableButtons() {
  setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);
}

/**
 * Disable all the buttons
 * @this {SweetAlert}
 */
function disableButtons() {
  setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);
}

/**
 * Enable the input field
 * @this {SweetAlert}
 */
function enableInput() {
  setInputDisabled(this.getInput(), false);
}

/**
 * Disable the input field
 * @this {SweetAlert}
 */
function disableInput() {
  setInputDisabled(this.getInput(), true);
}

/**
 * Show block with validation message
 *
 * @param {string} error
 * @this {SweetAlert}
 */
function showValidationMessage$1(error) {
  const domCache = privateProps.domCache.get(this);
  const params = privateProps.innerParams.get(this);
  setInnerHtml(domCache.validationMessage, error);
  domCache.validationMessage.className = swalClasses['validation-message'];
  if (params.customClass && params.customClass.validationMessage) {
    addClass(domCache.validationMessage, params.customClass.validationMessage);
  }
  show(domCache.validationMessage);
  const input = this.getInput();
  if (input) {
    input.setAttribute('aria-invalid', 'true');
    input.setAttribute('aria-describedby', swalClasses['validation-message']);
    focusInput(input);
    addClass(input, swalClasses.inputerror);
  }
}

/**
 * Hide block with validation message
 *
 * @this {SweetAlert}
 */
function resetValidationMessage() {
  const domCache = privateProps.domCache.get(this);
  if (domCache.validationMessage) {
    hide$2(domCache.validationMessage);
  }
  const input = this.getInput();
  if (input) {
    input.removeAttribute('aria-invalid');
    input.removeAttribute('aria-describedby');
    removeClass(input, swalClasses.inputerror);
  }
}

const defaultParams = {
  title: '',
  titleText: '',
  text: '',
  html: '',
  footer: '',
  icon: undefined,
  iconColor: undefined,
  iconHtml: undefined,
  template: undefined,
  toast: false,
  draggable: false,
  animation: true,
  theme: 'light',
  showClass: {
    popup: 'swal2-show',
    backdrop: 'swal2-backdrop-show',
    icon: 'swal2-icon-show'
  },
  hideClass: {
    popup: 'swal2-hide',
    backdrop: 'swal2-backdrop-hide',
    icon: 'swal2-icon-hide'
  },
  customClass: {},
  target: 'body',
  color: undefined,
  backdrop: true,
  heightAuto: true,
  allowOutsideClick: true,
  allowEscapeKey: true,
  allowEnterKey: true,
  stopKeydownPropagation: true,
  keydownListenerCapture: false,
  showConfirmButton: true,
  showDenyButton: false,
  showCancelButton: false,
  preConfirm: undefined,
  preDeny: undefined,
  confirmButtonText: 'OK',
  confirmButtonAriaLabel: '',
  confirmButtonColor: undefined,
  denyButtonText: 'No',
  denyButtonAriaLabel: '',
  denyButtonColor: undefined,
  cancelButtonText: 'Cancel',
  cancelButtonAriaLabel: '',
  cancelButtonColor: undefined,
  buttonsStyling: true,
  reverseButtons: false,
  focusConfirm: true,
  focusDeny: false,
  focusCancel: false,
  returnFocus: true,
  showCloseButton: false,
  closeButtonHtml: '&times;',
  closeButtonAriaLabel: 'Close this dialog',
  loaderHtml: '',
  showLoaderOnConfirm: false,
  showLoaderOnDeny: false,
  imageUrl: undefined,
  imageWidth: undefined,
  imageHeight: undefined,
  imageAlt: '',
  timer: undefined,
  timerProgressBar: false,
  width: undefined,
  padding: undefined,
  background: undefined,
  input: undefined,
  inputPlaceholder: '',
  inputLabel: '',
  inputValue: '',
  inputOptions: {},
  inputAutoFocus: true,
  inputAutoTrim: true,
  inputAttributes: {},
  inputValidator: undefined,
  returnInputValueOnDeny: false,
  validationMessage: undefined,
  grow: false,
  position: 'center',
  progressSteps: [],
  currentProgressStep: undefined,
  progressStepsDistance: undefined,
  willOpen: undefined,
  didOpen: undefined,
  didRender: undefined,
  willClose: undefined,
  didClose: undefined,
  didDestroy: undefined,
  scrollbarPadding: true,
  topLayer: false
};
const updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'color', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'draggable', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'preConfirm', 'preDeny', 'progressSteps', 'returnFocus', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'theme', 'willClose'];

/** @type {Record<string, string | undefined>} */
const deprecatedParams = {
  allowEnterKey: undefined
};
const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'draggable', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];

/**
 * Is valid parameter
 *
 * @param {string} paramName
 * @returns {boolean}
 */
const isValidParameter = paramName => {
  return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
};

/**
 * Is valid parameter for Swal.update() method
 *
 * @param {string} paramName
 * @returns {boolean}
 */
const isUpdatableParameter = paramName => {
  return updatableParams.indexOf(paramName) !== -1;
};

/**
 * Is deprecated parameter
 *
 * @param {string} paramName
 * @returns {string | undefined}
 */
const isDeprecatedParameter = paramName => {
  return deprecatedParams[paramName];
};

/**
 * @param {string} param
 */
const checkIfParamIsValid = param => {
  if (!isValidParameter(param)) {
    warn(`Unknown parameter "${param}"`);
  }
};

/**
 * @param {string} param
 */
const checkIfToastParamIsValid = param => {
  if (toastIncompatibleParams.includes(param)) {
    warn(`The parameter "${param}" is incompatible with toasts`);
  }
};

/**
 * @param {string} param
 */
const checkIfParamIsDeprecated = param => {
  const isDeprecated = isDeprecatedParameter(param);
  if (isDeprecated) {
    warnAboutDeprecation(param, isDeprecated);
  }
};

/**
 * Show relevant warnings for given params
 *
 * @param {SweetAlertOptions} params
 */
const showWarningsForParams = params => {
  if (params.backdrop === false && params.allowOutsideClick) {
    warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
  }
  if (params.theme && !['light', 'dark', 'auto', 'minimal', 'borderless', 'embed-iframe', 'bulma', 'bulma-light', 'bulma-dark'].includes(params.theme)) {
    warn(`Invalid theme "${params.theme}"`);
  }
  for (const param in params) {
    checkIfParamIsValid(param);
    if (params.toast) {
      checkIfToastParamIsValid(param);
    }
    checkIfParamIsDeprecated(param);
  }
};

/**
 * Updates popup parameters.
 *
 * @param {SweetAlertOptions} params
 */
function update(params) {
  const container = getContainer();
  const popup = getPopup();
  const innerParams = privateProps.innerParams.get(this);
  if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
    warn(`You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.`);
    return;
  }
  const validUpdatableParams = filterValidParams(params);
  const updatedParams = Object.assign({}, innerParams, validUpdatableParams);
  showWarningsForParams(updatedParams);
  container.dataset['swal2Theme'] = updatedParams.theme;
  render(this, updatedParams);
  privateProps.innerParams.set(this, updatedParams);
  Object.defineProperties(this, {
    params: {
      value: Object.assign({}, this.params, params),
      writable: false,
      enumerable: true
    }
  });
}

/**
 * @param {SweetAlertOptions} params
 * @returns {SweetAlertOptions}
 */
const filterValidParams = params => {
  const validUpdatableParams = {};
  Object.keys(params).forEach(param => {
    if (isUpdatableParameter(param)) {
      validUpdatableParams[param] = params[param];
    } else {
      warn(`Invalid parameter to update: ${param}`);
    }
  });
  return validUpdatableParams;
};

/**
 * Dispose the current SweetAlert2 instance
 */
function _destroy() {
  const domCache = privateProps.domCache.get(this);
  const innerParams = privateProps.innerParams.get(this);
  if (!innerParams) {
    disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335
    return; // This instance has already been destroyed
  }

  // Check if there is another Swal closing
  if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
    globalState.swalCloseEventFinishedCallback();
    delete globalState.swalCloseEventFinishedCallback;
  }
  if (typeof innerParams.didDestroy === 'function') {
    innerParams.didDestroy();
  }
  globalState.eventEmitter.emit('didDestroy');
  disposeSwal(this);
}

/**
 * @param {SweetAlert} instance
 */
const disposeSwal = instance => {
  disposeWeakMaps(instance);
  // Unset this.params so GC will dispose it (#1569)
  delete instance.params;
  // Unset globalState props so GC will dispose globalState (#1569)
  delete globalState.keydownHandler;
  delete globalState.keydownTarget;
  // Unset currentInstance
  delete globalState.currentInstance;
};

/**
 * @param {SweetAlert} instance
 */
const disposeWeakMaps = instance => {
  // If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335
  if (instance.isAwaitingPromise) {
    unsetWeakMaps(privateProps, instance);
    instance.isAwaitingPromise = true;
  } else {
    unsetWeakMaps(privateMethods, instance);
    unsetWeakMaps(privateProps, instance);
    delete instance.isAwaitingPromise;
    // Unset instance methods
    delete instance.disableButtons;
    delete instance.enableButtons;
    delete instance.getInput;
    delete instance.disableInput;
    delete instance.enableInput;
    delete instance.hideLoading;
    delete instance.disableLoading;
    delete instance.showValidationMessage;
    delete instance.resetValidationMessage;
    delete instance.close;
    delete instance.closePopup;
    delete instance.closeModal;
    delete instance.closeToast;
    delete instance.rejectPromise;
    delete instance.update;
    delete instance._destroy;
  }
};

/**
 * @param {object} obj
 * @param {SweetAlert} instance
 */
const unsetWeakMaps = (obj, instance) => {
  for (const i in obj) {
    obj[i].delete(instance);
  }
};

var instanceMethods = /*#__PURE__*/Object.freeze({
  __proto__: null,
  _destroy: _destroy,
  close: close,
  closeModal: close,
  closePopup: close,
  closeToast: close,
  disableButtons: disableButtons,
  disableInput: disableInput,
  disableLoading: hideLoading,
  enableButtons: enableButtons,
  enableInput: enableInput,
  getInput: getInput,
  handleAwaitingPromise: handleAwaitingPromise,
  hideLoading: hideLoading,
  rejectPromise: rejectPromise,
  resetValidationMessage: resetValidationMessage,
  showValidationMessage: showValidationMessage$1,
  update: update
});

/**
 * @param {SweetAlertOptions} innerParams
 * @param {DomCache} domCache
 * @param {Function} dismissWith
 */
const handlePopupClick = (innerParams, domCache, dismissWith) => {
  if (innerParams.toast) {
    handleToastClick(innerParams, domCache, dismissWith);
  } else {
    // Ignore click events that had mousedown on the popup but mouseup on the container
    // This can happen when the user drags a slider
    handleModalMousedown(domCache);

    // Ignore click events that had mousedown on the container but mouseup on the popup
    handleContainerMousedown(domCache);
    handleModalClick(innerParams, domCache, dismissWith);
  }
};

/**
 * @param {SweetAlertOptions} innerParams
 * @param {DomCache} domCache
 * @param {Function} dismissWith
 */
const handleToastClick = (innerParams, domCache, dismissWith) => {
  // Closing toast by internal click
  domCache.popup.onclick = () => {
    if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {
      return;
    }
    dismissWith(DismissReason.close);
  };
};

/**
 * @param {SweetAlertOptions} innerParams
 * @returns {boolean}
 */
const isAnyButtonShown = innerParams => {
  return !!(innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton);
};
let ignoreOutsideClick = false;

/**
 * @param {DomCache} domCache
 */
const handleModalMousedown = domCache => {
  domCache.popup.onmousedown = () => {
    domCache.container.onmouseup = function (e) {
      domCache.container.onmouseup = () => {};
      // We only check if the mouseup target is the container because usually it doesn't
      // have any other direct children aside of the popup
      if (e.target === domCache.container) {
        ignoreOutsideClick = true;
      }
    };
  };
};

/**
 * @param {DomCache} domCache
 */
const handleContainerMousedown = domCache => {
  domCache.container.onmousedown = e => {
    // prevent the modal text from being selected on double click on the container (allowOutsideClick: false)
    if (e.target === domCache.container) {
      e.preventDefault();
    }
    domCache.popup.onmouseup = function (e) {
      domCache.popup.onmouseup = () => {};
      // We also need to check if the mouseup target is a child of the popup
      if (e.target === domCache.popup || e.target instanceof HTMLElement && domCache.popup.contains(e.target)) {
        ignoreOutsideClick = true;
      }
    };
  };
};

/**
 * @param {SweetAlertOptions} innerParams
 * @param {DomCache} domCache
 * @param {Function} dismissWith
 */
const handleModalClick = (innerParams, domCache, dismissWith) => {
  domCache.container.onclick = e => {
    if (ignoreOutsideClick) {
      ignoreOutsideClick = false;
      return;
    }
    if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
      dismissWith(DismissReason.backdrop);
    }
  };
};

const isJqueryElement = elem => typeof elem === 'object' && elem.jquery;
const isElement$1 = elem => elem instanceof Element || isJqueryElement(elem);
const argsToParams = args => {
  const params = {};
  if (typeof args[0] === 'object' && !isElement$1(args[0])) {
    Object.assign(params, args[0]);
  } else {
    ['title', 'html', 'icon'].forEach((name, index) => {
      const arg = args[index];
      if (typeof arg === 'string' || isElement$1(arg)) {
        params[name] = arg;
      } else if (arg !== undefined) {
        error(`Unexpected type of ${name}! Expected "string" or "Element", got ${typeof arg}`);
      }
    });
  }
  return params;
};

/**
 * Main method to create a new SweetAlert2 popup
 *
 * @param  {...SweetAlertOptions} args
 * @returns {Promise<SweetAlertResult>}
 */
function fire(...args) {
  return new this(...args);
}

/**
 * Returns an extended version of `Swal` containing `params` as defaults.
 * Useful for reusing Swal configuration.
 *
 * For example:
 *
 * Before:
 * const textPromptOptions = { input: 'text', showCancelButton: true }
 * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
 * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
 *
 * After:
 * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
 * const {value: firstName} = await TextPrompt('What is your first name?')
 * const {value: lastName} = await TextPrompt('What is your last name?')
 *
 * @param {SweetAlertOptions} mixinParams
 * @returns {SweetAlert}
 */
function mixin(mixinParams) {
  class MixinSwal extends this {
    _main(params, priorityMixinParams) {
      return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));
    }
  }
  // @ts-ignore
  return MixinSwal;
}

/**
 * If `timer` parameter is set, returns number of milliseconds of timer remained.
 * Otherwise, returns undefined.
 *
 * @returns {number | undefined}
 */
const getTimerLeft = () => {
  return globalState.timeout && globalState.timeout.getTimerLeft();
};

/**
 * Stop timer. Returns number of milliseconds of timer remained.
 * If `timer` parameter isn't set, returns undefined.
 *
 * @returns {number | undefined}
 */
const stopTimer = () => {
  if (globalState.timeout) {
    stopTimerProgressBar();
    return globalState.timeout.stop();
  }
};

/**
 * Resume timer. Returns number of milliseconds of timer remained.
 * If `timer` parameter isn't set, returns undefined.
 *
 * @returns {number | undefined}
 */
const resumeTimer = () => {
  if (globalState.timeout) {
    const remaining = globalState.timeout.start();
    animateTimerProgressBar(remaining);
    return remaining;
  }
};

/**
 * Resume timer. Returns number of milliseconds of timer remained.
 * If `timer` parameter isn't set, returns undefined.
 *
 * @returns {number | undefined}
 */
const toggleTimer = () => {
  const timer = globalState.timeout;
  return timer && (timer.running ? stopTimer() : resumeTimer());
};

/**
 * Increase timer. Returns number of milliseconds of an updated timer.
 * If `timer` parameter isn't set, returns undefined.
 *
 * @param {number} ms
 * @returns {number | undefined}
 */
const increaseTimer = ms => {
  if (globalState.timeout) {
    const remaining = globalState.timeout.increase(ms);
    animateTimerProgressBar(remaining, true);
    return remaining;
  }
};

/**
 * Check if timer is running. Returns true if timer is running
 * or false if timer is paused or stopped.
 * If `timer` parameter isn't set, returns undefined
 *
 * @returns {boolean}
 */
const isTimerRunning = () => {
  return !!(globalState.timeout && globalState.timeout.isRunning());
};

let bodyClickListenerAdded = false;
const clickHandlers = {};

/**
 * @param {string} attr
 */
function bindClickHandler(attr = 'data-swal-template') {
  clickHandlers[attr] = this;
  if (!bodyClickListenerAdded) {
    document.body.addEventListener('click', bodyClickListener);
    bodyClickListenerAdded = true;
  }
}
const bodyClickListener = event => {
  for (let el = event.target; el && el !== document; el = el.parentNode) {
    for (const attr in clickHandlers) {
      const template = el.getAttribute(attr);
      if (template) {
        clickHandlers[attr].fire({
          template
        });
        return;
      }
    }
  }
};

// Source: https://gist.github.com/mudge/5830382?permalink_comment_id=2691957#gistcomment-2691957

class EventEmitter {
  constructor() {
    /** @type {Events} */
    this.events = {};
  }

  /**
   * @param {string} eventName
   * @returns {EventHandlers}
   */
  _getHandlersByEventName(eventName) {
    if (typeof this.events[eventName] === 'undefined') {
      // not Set because we need to keep the FIFO order
      // https://github.com/sweetalert2/sweetalert2/pull/2763#discussion_r1748990334
      this.events[eventName] = [];
    }
    return this.events[eventName];
  }

  /**
   * @param {string} eventName
   * @param {EventHandler} eventHandler
   */
  on(eventName, eventHandler) {
    const currentHandlers = this._getHandlersByEventName(eventName);
    if (!currentHandlers.includes(eventHandler)) {
      currentHandlers.push(eventHandler);
    }
  }

  /**
   * @param {string} eventName
   * @param {EventHandler} eventHandler
   */
  once(eventName, eventHandler) {
    /**
     * @param {Array} args
     */
    const onceFn = (...args) => {
      this.removeListener(eventName, onceFn);
      eventHandler.apply(this, args);
    };
    this.on(eventName, onceFn);
  }

  /**
   * @param {string} eventName
   * @param {Array} args
   */
  emit(eventName, ...args) {
    this._getHandlersByEventName(eventName).forEach(
    /**
     * @param {EventHandler} eventHandler
     */
    eventHandler => {
      try {
        eventHandler.apply(this, args);
      } catch (error) {
        console.error(error);
      }
    });
  }

  /**
   * @param {string} eventName
   * @param {EventHandler} eventHandler
   */
  removeListener(eventName, eventHandler) {
    const currentHandlers = this._getHandlersByEventName(eventName);
    const index = currentHandlers.indexOf(eventHandler);
    if (index > -1) {
      currentHandlers.splice(index, 1);
    }
  }

  /**
   * @param {string} eventName
   */
  removeAllListeners(eventName) {
    if (this.events[eventName] !== undefined) {
      // https://github.com/sweetalert2/sweetalert2/pull/2763#discussion_r1749239222
      this.events[eventName].length = 0;
    }
  }
  reset() {
    this.events = {};
  }
}

globalState.eventEmitter = new EventEmitter();

/**
 * @param {string} eventName
 * @param {EventHandler} eventHandler
 */
const on = (eventName, eventHandler) => {
  globalState.eventEmitter.on(eventName, eventHandler);
};

/**
 * @param {string} eventName
 * @param {EventHandler} eventHandler
 */
const once = (eventName, eventHandler) => {
  globalState.eventEmitter.once(eventName, eventHandler);
};

/**
 * @param {string} [eventName]
 * @param {EventHandler} [eventHandler]
 */
const off = (eventName, eventHandler) => {
  // Remove all handlers for all events
  if (!eventName) {
    globalState.eventEmitter.reset();
    return;
  }
  if (eventHandler) {
    // Remove a specific handler
    globalState.eventEmitter.removeListener(eventName, eventHandler);
  } else {
    // Remove all handlers for a specific event
    globalState.eventEmitter.removeAllListeners(eventName);
  }
};

var staticMethods = /*#__PURE__*/Object.freeze({
  __proto__: null,
  argsToParams: argsToParams,
  bindClickHandler: bindClickHandler,
  clickCancel: clickCancel,
  clickConfirm: clickConfirm,
  clickDeny: clickDeny,
  enableLoading: showLoading,
  fire: fire,
  getActions: getActions,
  getCancelButton: getCancelButton,
  getCloseButton: getCloseButton,
  getConfirmButton: getConfirmButton,
  getContainer: getContainer,
  getDenyButton: getDenyButton,
  getFocusableElements: getFocusableElements,
  getFooter: getFooter,
  getHtmlContainer: getHtmlContainer,
  getIcon: getIcon,
  getIconContent: getIconContent,
  getImage: getImage,
  getInputLabel: getInputLabel,
  getLoader: getLoader,
  getPopup: getPopup,
  getProgressSteps: getProgressSteps,
  getTimerLeft: getTimerLeft,
  getTimerProgressBar: getTimerProgressBar,
  getTitle: getTitle$1,
  getValidationMessage: getValidationMessage,
  increaseTimer: increaseTimer,
  isDeprecatedParameter: isDeprecatedParameter,
  isLoading: isLoading$2,
  isTimerRunning: isTimerRunning,
  isUpdatableParameter: isUpdatableParameter,
  isValidParameter: isValidParameter,
  isVisible: isVisible,
  mixin: mixin,
  off: off,
  on: on,
  once: once,
  resumeTimer: resumeTimer,
  showLoading: showLoading,
  stopTimer: stopTimer,
  toggleTimer: toggleTimer
});

class Timer {
  /**
   * @param {Function} callback
   * @param {number} delay
   */
  constructor(callback, delay) {
    this.callback = callback;
    this.remaining = delay;
    this.running = false;
    this.start();
  }

  /**
   * @returns {number}
   */
  start() {
    if (!this.running) {
      this.running = true;
      this.started = new Date();
      this.id = setTimeout(this.callback, this.remaining);
    }
    return this.remaining;
  }

  /**
   * @returns {number}
   */
  stop() {
    if (this.started && this.running) {
      this.running = false;
      clearTimeout(this.id);
      this.remaining -= new Date().getTime() - this.started.getTime();
    }
    return this.remaining;
  }

  /**
   * @param {number} n
   * @returns {number}
   */
  increase(n) {
    const running = this.running;
    if (running) {
      this.stop();
    }
    this.remaining += n;
    if (running) {
      this.start();
    }
    return this.remaining;
  }

  /**
   * @returns {number}
   */
  getTimerLeft() {
    if (this.running) {
      this.stop();
      this.start();
    }
    return this.remaining;
  }

  /**
   * @returns {boolean}
   */
  isRunning() {
    return this.running;
  }
}

const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];

/**
 * @param {SweetAlertOptions} params
 * @returns {SweetAlertOptions}
 */
const getTemplateParams = params => {
  const template = typeof params.template === 'string' ? (/** @type {HTMLTemplateElement} */document.querySelector(params.template)) : params.template;
  if (!template) {
    return {};
  }
  /** @type {DocumentFragment} */
  const templateContent = template.content;
  showWarningsForElements(templateContent);
  const result = Object.assign(getSwalParams(templateContent), getSwalFunctionParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));
  return result;
};

/**
 * @param {DocumentFragment} templateContent
 * @returns {Record<string, any>}
 */
const getSwalParams = templateContent => {
  /** @type {Record<string, any>} */
  const result = {};
  /** @type {HTMLElement[]} */
  const swalParams = Array.from(templateContent.querySelectorAll('swal-param'));
  swalParams.forEach(param => {
    showWarningsForAttributes(param, ['name', 'value']);
    const paramName = /** @type {keyof SweetAlertOptions} */param.getAttribute('name');
    const value = param.getAttribute('value');
    if (!paramName || !value) {
      return;
    }
    if (typeof defaultParams[paramName] === 'boolean') {
      result[paramName] = value !== 'false';
    } else if (typeof defaultParams[paramName] === 'object') {
      result[paramName] = JSON.parse(value);
    } else {
      result[paramName] = value;
    }
  });
  return result;
};

/**
 * @param {DocumentFragment} templateContent
 * @returns {Record<string, any>}
 */
const getSwalFunctionParams = templateContent => {
  /** @type {Record<string, any>} */
  const result = {};
  /** @type {HTMLElement[]} */
  const swalFunctions = Array.from(templateContent.querySelectorAll('swal-function-param'));
  swalFunctions.forEach(param => {
    const paramName = /** @type {keyof SweetAlertOptions} */param.getAttribute('name');
    const value = param.getAttribute('value');
    if (!paramName || !value) {
      return;
    }
    result[paramName] = new Function(`return ${value}`)();
  });
  return result;
};

/**
 * @param {DocumentFragment} templateContent
 * @returns {Record<string, any>}
 */
const getSwalButtons = templateContent => {
  /** @type {Record<string, any>} */
  const result = {};
  /** @type {HTMLElement[]} */
  const swalButtons = Array.from(templateContent.querySelectorAll('swal-button'));
  swalButtons.forEach(button => {
    showWarningsForAttributes(button, ['type', 'color', 'aria-label']);
    const type = button.getAttribute('type');
    if (!type || !['confirm', 'cancel', 'deny'].includes(type)) {
      return;
    }
    result[`${type}ButtonText`] = button.innerHTML;
    result[`show${capitalizeFirstLetter(type)}Button`] = true;
    if (button.hasAttribute('color')) {
      result[`${type}ButtonColor`] = button.getAttribute('color');
    }
    if (button.hasAttribute('aria-label')) {
      result[`${type}ButtonAriaLabel`] = button.getAttribute('aria-label');
    }
  });
  return result;
};

/**
 * @param {DocumentFragment} templateContent
 * @returns {Pick<SweetAlertOptions, 'imageUrl' | 'imageWidth' | 'imageHeight' | 'imageAlt'>}
 */
const getSwalImage = templateContent => {
  const result = {};
  /** @type {HTMLElement | null} */
  const image = templateContent.querySelector('swal-image');
  if (image) {
    showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);
    if (image.hasAttribute('src')) {
      result.imageUrl = image.getAttribute('src') || undefined;
    }
    if (image.hasAttribute('width')) {
      result.imageWidth = image.getAttribute('width') || undefined;
    }
    if (image.hasAttribute('height')) {
      result.imageHeight = image.getAttribute('height') || undefined;
    }
    if (image.hasAttribute('alt')) {
      result.imageAlt = image.getAttribute('alt') || undefined;
    }
  }
  return result;
};

/**
 * @param {DocumentFragment} templateContent
 * @returns {Record<string, any>}
 */
const getSwalIcon = templateContent => {
  const result = {};
  /** @type {HTMLElement | null} */
  const icon = templateContent.querySelector('swal-icon');
  if (icon) {
    showWarningsForAttributes(icon, ['type', 'color']);
    if (icon.hasAttribute('type')) {
      result.icon = icon.getAttribute('type');
    }
    if (icon.hasAttribute('color')) {
      result.iconColor = icon.getAttribute('color');
    }
    result.iconHtml = icon.innerHTML;
  }
  return result;
};

/**
 * @param {DocumentFragment} templateContent
 * @returns {Record<string, any>}
 */
const getSwalInput = templateContent => {
  /** @type {Record<string, any>} */
  const result = {};
  /** @type {HTMLElement | null} */
  const input = templateContent.querySelector('swal-input');
  if (input) {
    showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);
    result.input = input.getAttribute('type') || 'text';
    if (input.hasAttribute('label')) {
      result.inputLabel = input.getAttribute('label');
    }
    if (input.hasAttribute('placeholder')) {
      result.inputPlaceholder = input.getAttribute('placeholder');
    }
    if (input.hasAttribute('value')) {
      result.inputValue = input.getAttribute('value');
    }
  }
  /** @type {HTMLElement[]} */
  const inputOptions = Array.from(templateContent.querySelectorAll('swal-input-option'));
  if (inputOptions.length) {
    result.inputOptions = {};
    inputOptions.forEach(option => {
      showWarningsForAttributes(option, ['value']);
      const optionValue = option.getAttribute('value');
      if (!optionValue) {
        return;
      }
      const optionName = option.innerHTML;
      result.inputOptions[optionValue] = optionName;
    });
  }
  return result;
};

/**
 * @param {DocumentFragment} templateContent
 * @param {string[]} paramNames
 * @returns {Record<string, any>}
 */
const getSwalStringParams = (templateContent, paramNames) => {
  /** @type {Record<string, any>} */
  const result = {};
  for (const i in paramNames) {
    const paramName = paramNames[i];
    /** @type {HTMLElement | null} */
    const tag = templateContent.querySelector(paramName);
    if (tag) {
      showWarningsForAttributes(tag, []);
      result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();
    }
  }
  return result;
};

/**
 * @param {DocumentFragment} templateContent
 */
const showWarningsForElements = templateContent => {
  const allowedElements = swalStringParams.concat(['swal-param', 'swal-function-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);
  Array.from(templateContent.children).forEach(el => {
    const tagName = el.tagName.toLowerCase();
    if (!allowedElements.includes(tagName)) {
      warn(`Unrecognized element <${tagName}>`);
    }
  });
};

/**
 * @param {HTMLElement} el
 * @param {string[]} allowedAttributes
 */
const showWarningsForAttributes = (el, allowedAttributes) => {
  Array.from(el.attributes).forEach(attribute => {
    if (allowedAttributes.indexOf(attribute.name) === -1) {
      warn([`Unrecognized attribute "${attribute.name}" on <${el.tagName.toLowerCase()}>.`, `${allowedAttributes.length ? `Allowed attributes are: ${allowedAttributes.join(', ')}` : 'To set the value, use HTML within the element.'}`]);
    }
  });
};

const SHOW_CLASS_TIMEOUT = 10;

/**
 * Open popup, add necessary classes and styles, fix scrollbar
 *
 * @param {SweetAlertOptions} params
 */
const openPopup = params => {
  const container = getContainer();
  const popup = getPopup();
  if (typeof params.willOpen === 'function') {
    params.willOpen(popup);
  }
  globalState.eventEmitter.emit('willOpen', popup);
  const bodyStyles = window.getComputedStyle(document.body);
  const initialBodyOverflow = bodyStyles.overflowY;
  addClasses(container, popup, params);

  // scrolling is 'hidden' until animation is done, after that 'auto'
  setTimeout(() => {
    setScrollingVisibility(container, popup);
  }, SHOW_CLASS_TIMEOUT);
  if (isModal()) {
    fixScrollContainer(container, params.scrollbarPadding, initialBodyOverflow);
    setAriaHidden();
  }
  if (!isToast() && !globalState.previousActiveElement) {
    globalState.previousActiveElement = document.activeElement;
  }
  if (typeof params.didOpen === 'function') {
    setTimeout(() => params.didOpen(popup));
  }
  globalState.eventEmitter.emit('didOpen', popup);
  removeClass(container, swalClasses['no-transition']);
};

/**
 * @param {AnimationEvent} event
 */
const swalOpenAnimationFinished = event => {
  const popup = getPopup();
  if (event.target !== popup) {
    return;
  }
  const container = getContainer();
  popup.removeEventListener('animationend', swalOpenAnimationFinished);
  popup.removeEventListener('transitionend', swalOpenAnimationFinished);
  container.style.overflowY = 'auto';
};

/**
 * @param {HTMLElement} container
 * @param {HTMLElement} popup
 */
const setScrollingVisibility = (container, popup) => {
  if (hasCssAnimation(popup)) {
    container.style.overflowY = 'hidden';
    popup.addEventListener('animationend', swalOpenAnimationFinished);
    popup.addEventListener('transitionend', swalOpenAnimationFinished);
  } else {
    container.style.overflowY = 'auto';
  }
};

/**
 * @param {HTMLElement} container
 * @param {boolean} scrollbarPadding
 * @param {string} initialBodyOverflow
 */
const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {
  iOSfix();
  if (scrollbarPadding && initialBodyOverflow !== 'hidden') {
    replaceScrollbarWithPadding(initialBodyOverflow);
  }

  // sweetalert2/issues/1247
  setTimeout(() => {
    container.scrollTop = 0;
  });
};

/**
 * @param {HTMLElement} container
 * @param {HTMLElement} popup
 * @param {SweetAlertOptions} params
 */
const addClasses = (container, popup, params) => {
  addClass(container, params.showClass.backdrop);
  if (params.animation) {
    // this workaround with opacity is needed for https://github.com/sweetalert2/sweetalert2/issues/2059
    popup.style.setProperty('opacity', '0', 'important');
    show(popup, 'grid');
    setTimeout(() => {
      // Animate popup right after showing it
      addClass(popup, params.showClass.popup);
      // and remove the opacity workaround
      popup.style.removeProperty('opacity');
    }, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062
  } else {
    show(popup, 'grid');
  }
  addClass([document.documentElement, document.body], swalClasses.shown);
  if (params.heightAuto && params.backdrop && !params.toast) {
    addClass([document.documentElement, document.body], swalClasses['height-auto']);
  }
};

var defaultInputValidators = {
  /**
   * @param {string} string
   * @param {string} [validationMessage]
   * @returns {Promise<string | void>}
   */
  email: (string, validationMessage) => {
    return /^[a-zA-Z0-9.+_'-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]+$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');
  },
  /**
   * @param {string} string
   * @param {string} [validationMessage]
   * @returns {Promise<string | void>}
   */
  url: (string, validationMessage) => {
    // taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013
    return /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid URL');
  }
};

/**
 * @param {SweetAlertOptions} params
 */
function setDefaultInputValidators(params) {
  // Use default `inputValidator` for supported input types if not provided
  if (params.inputValidator) {
    return;
  }
  if (params.input === 'email') {
    params.inputValidator = defaultInputValidators['email'];
  }
  if (params.input === 'url') {
    params.inputValidator = defaultInputValidators['url'];
  }
}

/**
 * @param {SweetAlertOptions} params
 */
function validateCustomTargetElement(params) {
  // Determine if the custom target element is valid
  if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
    warn('Target parameter is not valid, defaulting to "body"');
    params.target = 'body';
  }
}

/**
 * Set type, text and actions on popup
 *
 * @param {SweetAlertOptions} params
 */
function setParameters(params) {
  setDefaultInputValidators(params);

  // showLoaderOnConfirm && preConfirm
  if (params.showLoaderOnConfirm && !params.preConfirm) {
    warn('showLoaderOnConfirm is set to true, but preConfirm is not defined.\n' + 'showLoaderOnConfirm should be used together with preConfirm, see usage example:\n' + 'https://sweetalert2.github.io/#ajax-request');
  }
  validateCustomTargetElement(params);

  // Replace newlines with <br> in title
  if (typeof params.title === 'string') {
    params.title = params.title.split('\n').join('<br />');
  }
  init$1(params);
}

/** @type {SweetAlert} */
let currentInstance;
var _promise = /*#__PURE__*/new WeakMap();
class SweetAlert {
  /**
   * @param {...any} args
   * @this {SweetAlert}
   */
  constructor(...args) {
    /**
     * @type {Promise<SweetAlertResult>}
     */
    _classPrivateFieldInitSpec(this, _promise, void 0);
    // Prevent run in Node env
    if (typeof window === 'undefined') {
      return;
    }
    currentInstance = this;

    // @ts-ignore
    const outerParams = Object.freeze(this.constructor.argsToParams(args));

    /** @type {Readonly<SweetAlertOptions>} */
    this.params = outerParams;

    /** @type {boolean} */
    this.isAwaitingPromise = false;
    _classPrivateFieldSet2(_promise, this, this._main(currentInstance.params));
  }
  _main(userParams, mixinParams = {}) {
    showWarningsForParams(Object.assign({}, mixinParams, userParams));
    if (globalState.currentInstance) {
      const swalPromiseResolve = privateMethods.swalPromiseResolve.get(globalState.currentInstance);
      const {
        isAwaitingPromise
      } = globalState.currentInstance;
      globalState.currentInstance._destroy();
      if (!isAwaitingPromise) {
        swalPromiseResolve({
          isDismissed: true
        });
      }
      if (isModal()) {
        unsetAriaHidden();
      }
    }
    globalState.currentInstance = currentInstance;
    const innerParams = prepareParams(userParams, mixinParams);
    setParameters(innerParams);
    Object.freeze(innerParams);

    // clear the previous timer
    if (globalState.timeout) {
      globalState.timeout.stop();
      delete globalState.timeout;
    }

    // clear the restore focus timeout
    clearTimeout(globalState.restoreFocusTimeout);
    const domCache = populateDomCache(currentInstance);
    render(currentInstance, innerParams);
    privateProps.innerParams.set(currentInstance, innerParams);
    return swalPromise(currentInstance, domCache, innerParams);
  }

  // `catch` cannot be the name of a module export, so we define our thenable methods here instead
  then(onFulfilled) {
    return _classPrivateFieldGet2(_promise, this).then(onFulfilled);
  }
  finally(onFinally) {
    return _classPrivateFieldGet2(_promise, this).finally(onFinally);
  }
}

/**
 * @param {SweetAlert} instance
 * @param {DomCache} domCache
 * @param {SweetAlertOptions} innerParams
 * @returns {Promise}
 */
const swalPromise = (instance, domCache, innerParams) => {
  return new Promise((resolve, reject) => {
    // functions to handle all closings/dismissals
    /**
     * @param {DismissReason} dismiss
     */
    const dismissWith = dismiss => {
      instance.close({
        isDismissed: true,
        dismiss
      });
    };
    privateMethods.swalPromiseResolve.set(instance, resolve);
    privateMethods.swalPromiseReject.set(instance, reject);
    domCache.confirmButton.onclick = () => {
      handleConfirmButtonClick(instance);
    };
    domCache.denyButton.onclick = () => {
      handleDenyButtonClick(instance);
    };
    domCache.cancelButton.onclick = () => {
      handleCancelButtonClick(instance, dismissWith);
    };
    domCache.closeButton.onclick = () => {
      dismissWith(DismissReason.close);
    };
    handlePopupClick(innerParams, domCache, dismissWith);
    addKeydownHandler(globalState, innerParams, dismissWith);
    handleInputOptionsAndValue(instance, innerParams);
    openPopup(innerParams);
    setupTimer(globalState, innerParams, dismissWith);
    initFocus(domCache, innerParams);

    // Scroll container to top on open (#1247, #1946)
    setTimeout(() => {
      domCache.container.scrollTop = 0;
    });
  });
};

/**
 * @param {SweetAlertOptions} userParams
 * @param {SweetAlertOptions} mixinParams
 * @returns {SweetAlertOptions}
 */
const prepareParams = (userParams, mixinParams) => {
  const templateParams = getTemplateParams(userParams);
  const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131
  params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);
  params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);
  if (params.animation === false) {
    params.showClass = {
      backdrop: 'swal2-noanimation'
    };
    params.hideClass = {};
  }
  return params;
};

/**
 * @param {SweetAlert} instance
 * @returns {DomCache}
 */
const populateDomCache = instance => {
  const domCache = {
    popup: getPopup(),
    container: getContainer(),
    actions: getActions(),
    confirmButton: getConfirmButton(),
    denyButton: getDenyButton(),
    cancelButton: getCancelButton(),
    loader: getLoader(),
    closeButton: getCloseButton(),
    validationMessage: getValidationMessage(),
    progressSteps: getProgressSteps()
  };
  privateProps.domCache.set(instance, domCache);
  return domCache;
};

/**
 * @param {GlobalState} globalState
 * @param {SweetAlertOptions} innerParams
 * @param {Function} dismissWith
 */
const setupTimer = (globalState, innerParams, dismissWith) => {
  const timerProgressBar = getTimerProgressBar();
  hide$2(timerProgressBar);
  if (innerParams.timer) {
    globalState.timeout = new Timer(() => {
      dismissWith('timer');
      delete globalState.timeout;
    }, innerParams.timer);
    if (innerParams.timerProgressBar) {
      show(timerProgressBar);
      applyCustomClass(timerProgressBar, innerParams, 'timerProgressBar');
      setTimeout(() => {
        if (globalState.timeout && globalState.timeout.running) {
          // timer can be already stopped or unset at this point
          animateTimerProgressBar(innerParams.timer);
        }
      });
    }
  }
};

/**
 * Initialize focus in the popup:
 *
 * 1. If `toast` is `true`, don't steal focus from the document.
 * 2. Else if there is an [autofocus] element, focus it.
 * 3. Else if `focusConfirm` is `true` and confirm button is visible, focus it.
 * 4. Else if `focusDeny` is `true` and deny button is visible, focus it.
 * 5. Else if `focusCancel` is `true` and cancel button is visible, focus it.
 * 6. Else focus the first focusable element in a popup (if any).
 *
 * @param {DomCache} domCache
 * @param {SweetAlertOptions} innerParams
 */
const initFocus = (domCache, innerParams) => {
  if (innerParams.toast) {
    return;
  }
  // TODO: this is dumb, remove `allowEnterKey` param in the next major version
  if (!callIfFunction(innerParams.allowEnterKey)) {
    warnAboutDeprecation('allowEnterKey');
    blurActiveElement();
    return;
  }
  if (focusAutofocus(domCache)) {
    return;
  }
  if (focusButton(domCache, innerParams)) {
    return;
  }
  setFocus(-1, 1);
};

/**
 * @param {DomCache} domCache
 * @returns {boolean}
 */
const focusAutofocus = domCache => {
  const autofocusElements = Array.from(domCache.popup.querySelectorAll('[autofocus]'));
  for (const autofocusElement of autofocusElements) {
    if (autofocusElement instanceof HTMLElement && isVisible$1(autofocusElement)) {
      autofocusElement.focus();
      return true;
    }
  }
  return false;
};

/**
 * @param {DomCache} domCache
 * @param {SweetAlertOptions} innerParams
 * @returns {boolean}
 */
const focusButton = (domCache, innerParams) => {
  if (innerParams.focusDeny && isVisible$1(domCache.denyButton)) {
    domCache.denyButton.focus();
    return true;
  }
  if (innerParams.focusCancel && isVisible$1(domCache.cancelButton)) {
    domCache.cancelButton.focus();
    return true;
  }
  if (innerParams.focusConfirm && isVisible$1(domCache.confirmButton)) {
    domCache.confirmButton.focus();
    return true;
  }
  return false;
};
const blurActiveElement = () => {
  if (document.activeElement instanceof HTMLElement && typeof document.activeElement.blur === 'function') {
    document.activeElement.blur();
  }
};

// Assign instance methods from src/instanceMethods/*.js to prototype
SweetAlert.prototype.disableButtons = disableButtons;
SweetAlert.prototype.enableButtons = enableButtons;
SweetAlert.prototype.getInput = getInput;
SweetAlert.prototype.disableInput = disableInput;
SweetAlert.prototype.enableInput = enableInput;
SweetAlert.prototype.hideLoading = hideLoading;
SweetAlert.prototype.disableLoading = hideLoading;
SweetAlert.prototype.showValidationMessage = showValidationMessage$1;
SweetAlert.prototype.resetValidationMessage = resetValidationMessage;
SweetAlert.prototype.close = close;
SweetAlert.prototype.closePopup = close;
SweetAlert.prototype.closeModal = close;
SweetAlert.prototype.closeToast = close;
SweetAlert.prototype.rejectPromise = rejectPromise;
SweetAlert.prototype.update = update;
SweetAlert.prototype._destroy = _destroy;

// Assign static methods from src/staticMethods/*.js to constructor
Object.assign(SweetAlert, staticMethods);

// Proxy to instance methods to constructor, for now, for backwards compatibility
Object.keys(instanceMethods).forEach(key => {
  /**
   * @param {...any} args
   * @returns {any | undefined}
   */
  SweetAlert[key] = function (...args) {
    if (currentInstance && currentInstance[key]) {
      return currentInstance[key](...args);
    }
    return null;
  };
});
SweetAlert.DismissReason = DismissReason;
SweetAlert.version = '11.22.4';

const Swal = SweetAlert;
// @ts-ignore
Swal.default = Swal;
"undefined"!=typeof document&&function(e,t){var n=e.createElement("style");if(e.getElementsByTagName("head")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=t);else try{n.innerHTML=t;}catch(e){n.innerText=t;}}(document,":root{--swal2-outline: 0 0 0 3px rgba(100, 150, 200, 0.5);--swal2-container-padding: 0.625em;--swal2-backdrop: rgba(0, 0, 0, 0.4);--swal2-backdrop-transition: background-color 0.1s;--swal2-width: 32em;--swal2-padding: 0 0 1.25em;--swal2-border: none;--swal2-border-radius: 0.3125rem;--swal2-background: white;--swal2-color: #545454;--swal2-show-animation: swal2-show 0.3s;--swal2-hide-animation: swal2-hide 0.15s forwards;--swal2-icon-zoom: 1;--swal2-icon-animations: true;--swal2-title-padding: 0.8em 1em 0;--swal2-html-container-padding: 1em 1.6em 0.3em;--swal2-input-border: 1px solid #d9d9d9;--swal2-input-border-radius: 0.1875em;--swal2-input-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px transparent;--swal2-input-background: transparent;--swal2-input-transition: border-color 0.2s, box-shadow 0.2s;--swal2-input-hover-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px transparent;--swal2-input-focus-border: 1px solid #b4dbed;--swal2-input-focus-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px $swal2-outline-color;--swal2-progress-step-background: #add8e6;--swal2-validation-message-background: #f0f0f0;--swal2-validation-message-color: #666;--swal2-footer-border-color: #eee;--swal2-footer-background: transparent;--swal2-footer-color: inherit;--swal2-timer-progress-bar-background: rgba(0, 0, 0, 0.3);--swal2-close-button-position: initial;--swal2-close-button-inset: auto;--swal2-close-button-font-size: 2.5em;--swal2-close-button-color: #ccc;--swal2-close-button-transition: color 0.2s, box-shadow 0.2s;--swal2-close-button-outline: initial;--swal2-close-button-box-shadow: inset 0 0 0 3px transparent;--swal2-close-button-focus-box-shadow: inset var(--swal2-outline);--swal2-close-button-hover-transform: none;--swal2-actions-justify-content: center;--swal2-actions-width: auto;--swal2-actions-margin: 1.25em auto 0;--swal2-actions-padding: 0;--swal2-actions-border-radius: 0;--swal2-actions-background: transparent;--swal2-action-button-transition: background-color 0.2s, box-shadow 0.2s;--swal2-action-button-hover: black 10%;--swal2-action-button-active: black 10%;--swal2-confirm-button-box-shadow: none;--swal2-confirm-button-border-radius: 0.25em;--swal2-confirm-button-background-color: #7066e0;--swal2-confirm-button-color: #fff;--swal2-deny-button-box-shadow: none;--swal2-deny-button-border-radius: 0.25em;--swal2-deny-button-background-color: #dc3741;--swal2-deny-button-color: #fff;--swal2-cancel-button-box-shadow: none;--swal2-cancel-button-border-radius: 0.25em;--swal2-cancel-button-background-color: #6e7881;--swal2-cancel-button-color: #fff;--swal2-toast-show-animation: swal2-toast-show 0.5s;--swal2-toast-hide-animation: swal2-toast-hide 0.1s forwards;--swal2-toast-border: none;--swal2-toast-box-shadow: 0 0 1px hsl(0deg 0% 0% / 0.075), 0 1px 2px hsl(0deg 0% 0% / 0.075), 1px 2px 4px hsl(0deg 0% 0% / 0.075), 1px 3px 8px hsl(0deg 0% 0% / 0.075), 2px 4px 16px hsl(0deg 0% 0% / 0.075)}[data-swal2-theme=dark]{--swal2-dark-theme-black: #19191a;--swal2-dark-theme-white: #e1e1e1;--swal2-background: var(--swal2-dark-theme-black);--swal2-color: var(--swal2-dark-theme-white);--swal2-footer-border-color: #555;--swal2-input-background: color-mix(in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10%);--swal2-validation-message-background: color-mix( in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10% );--swal2-validation-message-color: var(--swal2-dark-theme-white);--swal2-timer-progress-bar-background: rgba(255, 255, 255, 0.7)}@media(prefers-color-scheme: dark){[data-swal2-theme=auto]{--swal2-dark-theme-black: #19191a;--swal2-dark-theme-white: #e1e1e1;--swal2-background: var(--swal2-dark-theme-black);--swal2-color: var(--swal2-dark-theme-white);--swal2-footer-border-color: #555;--swal2-input-background: color-mix(in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10%);--swal2-validation-message-background: color-mix( in srgb, var(--swal2-dark-theme-black), var(--swal2-dark-theme-white) 10% );--swal2-validation-message-color: var(--swal2-dark-theme-white);--swal2-timer-progress-bar-background: rgba(255, 255, 255, 0.7)}}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto !important}body.swal2-no-backdrop .swal2-container{background-color:rgba(0,0,0,0) !important;pointer-events:none}body.swal2-no-backdrop .swal2-container .swal2-popup{pointer-events:all}body.swal2-no-backdrop .swal2-container .swal2-modal{box-shadow:0 0 10px var(--swal2-backdrop)}body.swal2-toast-shown .swal2-container{box-sizing:border-box;width:360px;max-width:100%;background-color:rgba(0,0,0,0);pointer-events:none}body.swal2-toast-shown .swal2-container.swal2-top{inset:0 auto auto 50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{inset:0 0 auto auto}body.swal2-toast-shown .swal2-container.swal2-top-start,body.swal2-toast-shown .swal2-container.swal2-top-left{inset:0 auto auto 0}body.swal2-toast-shown .swal2-container.swal2-center-start,body.swal2-toast-shown .swal2-container.swal2-center-left{inset:50% auto auto 0;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{inset:50% auto auto 50%;transform:translate(-50%, -50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{inset:50% 0 auto auto;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-start,body.swal2-toast-shown .swal2-container.swal2-bottom-left{inset:auto auto 0 0}body.swal2-toast-shown .swal2-container.swal2-bottom{inset:auto auto 0 50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{inset:auto 0 0 auto}@media print{body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown){overflow-y:scroll !important}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown)>[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop,.swal2-toast-shown) .swal2-container{position:static !important}}div:where(.swal2-container){display:grid;position:fixed;z-index:1060;inset:0;box-sizing:border-box;grid-template-areas:\"top-start     top            top-end\" \"center-start  center         center-end\" \"bottom-start  bottom-center  bottom-end\";grid-template-rows:minmax(min-content, auto) minmax(min-content, auto) minmax(min-content, auto);height:100%;padding:var(--swal2-container-padding);overflow-x:hidden;transition:var(--swal2-backdrop-transition);-webkit-overflow-scrolling:touch}div:where(.swal2-container).swal2-backdrop-show,div:where(.swal2-container).swal2-noanimation{background:var(--swal2-backdrop)}div:where(.swal2-container).swal2-backdrop-hide{background:rgba(0,0,0,0) !important}div:where(.swal2-container).swal2-top-start,div:where(.swal2-container).swal2-center-start,div:where(.swal2-container).swal2-bottom-start{grid-template-columns:minmax(0, 1fr) auto auto}div:where(.swal2-container).swal2-top,div:where(.swal2-container).swal2-center,div:where(.swal2-container).swal2-bottom{grid-template-columns:auto minmax(0, 1fr) auto}div:where(.swal2-container).swal2-top-end,div:where(.swal2-container).swal2-center-end,div:where(.swal2-container).swal2-bottom-end{grid-template-columns:auto auto minmax(0, 1fr)}div:where(.swal2-container).swal2-top-start>.swal2-popup{align-self:start}div:where(.swal2-container).swal2-top>.swal2-popup{grid-column:2;place-self:start center}div:where(.swal2-container).swal2-top-end>.swal2-popup,div:where(.swal2-container).swal2-top-right>.swal2-popup{grid-column:3;place-self:start end}div:where(.swal2-container).swal2-center-start>.swal2-popup,div:where(.swal2-container).swal2-center-left>.swal2-popup{grid-row:2;align-self:center}div:where(.swal2-container).swal2-center>.swal2-popup{grid-column:2;grid-row:2;place-self:center center}div:where(.swal2-container).swal2-center-end>.swal2-popup,div:where(.swal2-container).swal2-center-right>.swal2-popup{grid-column:3;grid-row:2;place-self:center end}div:where(.swal2-container).swal2-bottom-start>.swal2-popup,div:where(.swal2-container).swal2-bottom-left>.swal2-popup{grid-column:1;grid-row:3;align-self:end}div:where(.swal2-container).swal2-bottom>.swal2-popup{grid-column:2;grid-row:3;place-self:end center}div:where(.swal2-container).swal2-bottom-end>.swal2-popup,div:where(.swal2-container).swal2-bottom-right>.swal2-popup{grid-column:3;grid-row:3;place-self:end end}div:where(.swal2-container).swal2-grow-row>.swal2-popup,div:where(.swal2-container).swal2-grow-fullscreen>.swal2-popup{grid-column:1/4;width:100%}div:where(.swal2-container).swal2-grow-column>.swal2-popup,div:where(.swal2-container).swal2-grow-fullscreen>.swal2-popup{grid-row:1/4;align-self:stretch}div:where(.swal2-container).swal2-no-transition{transition:none !important}div:where(.swal2-container)[popover]{width:auto;border:0}div:where(.swal2-container) div:where(.swal2-popup){display:none;position:relative;box-sizing:border-box;grid-template-columns:minmax(0, 100%);width:var(--swal2-width);max-width:100%;padding:var(--swal2-padding);border:var(--swal2-border);border-radius:var(--swal2-border-radius);background:var(--swal2-background);color:var(--swal2-color);font-family:inherit;font-size:1rem;container-name:swal2-popup}div:where(.swal2-container) div:where(.swal2-popup):focus{outline:none}div:where(.swal2-container) div:where(.swal2-popup).swal2-loading{overflow-y:hidden}div:where(.swal2-container) div:where(.swal2-popup).swal2-draggable{cursor:grab}div:where(.swal2-container) div:where(.swal2-popup).swal2-draggable div:where(.swal2-icon){cursor:grab}div:where(.swal2-container) div:where(.swal2-popup).swal2-dragging{cursor:grabbing}div:where(.swal2-container) div:where(.swal2-popup).swal2-dragging div:where(.swal2-icon){cursor:grabbing}div:where(.swal2-container) h2:where(.swal2-title){position:relative;max-width:100%;margin:0;padding:var(--swal2-title-padding);color:inherit;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;word-wrap:break-word;cursor:initial}div:where(.swal2-container) div:where(.swal2-actions){display:flex;z-index:1;box-sizing:border-box;flex-wrap:wrap;align-items:center;justify-content:var(--swal2-actions-justify-content);width:var(--swal2-actions-width);margin:var(--swal2-actions-margin);padding:var(--swal2-actions-padding);border-radius:var(--swal2-actions-border-radius);background:var(--swal2-actions-background)}div:where(.swal2-container) div:where(.swal2-loader){display:none;align-items:center;justify-content:center;width:2.2em;height:2.2em;margin:0 1.875em;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border-width:.25em;border-style:solid;border-radius:100%;border-color:#2778c4 rgba(0,0,0,0) #2778c4 rgba(0,0,0,0)}div:where(.swal2-container) button:where(.swal2-styled){margin:.3125em;padding:.625em 1.1em;transition:var(--swal2-action-button-transition);border:none;box-shadow:0 0 0 3px rgba(0,0,0,0);font-weight:500}div:where(.swal2-container) button:where(.swal2-styled):not([disabled]){cursor:pointer}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-confirm){border-radius:var(--swal2-confirm-button-border-radius);background:initial;background-color:var(--swal2-confirm-button-background-color);box-shadow:var(--swal2-confirm-button-box-shadow);color:var(--swal2-confirm-button-color);font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-confirm):hover{background-color:color-mix(in srgb, var(--swal2-confirm-button-background-color), var(--swal2-action-button-hover))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-confirm):active{background-color:color-mix(in srgb, var(--swal2-confirm-button-background-color), var(--swal2-action-button-active))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-deny){border-radius:var(--swal2-deny-button-border-radius);background:initial;background-color:var(--swal2-deny-button-background-color);box-shadow:var(--swal2-deny-button-box-shadow);color:var(--swal2-deny-button-color);font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-deny):hover{background-color:color-mix(in srgb, var(--swal2-deny-button-background-color), var(--swal2-action-button-hover))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-deny):active{background-color:color-mix(in srgb, var(--swal2-deny-button-background-color), var(--swal2-action-button-active))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-cancel){border-radius:var(--swal2-cancel-button-border-radius);background:initial;background-color:var(--swal2-cancel-button-background-color);box-shadow:var(--swal2-cancel-button-box-shadow);color:var(--swal2-cancel-button-color);font-size:1em}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-cancel):hover{background-color:color-mix(in srgb, var(--swal2-cancel-button-background-color), var(--swal2-action-button-hover))}div:where(.swal2-container) button:where(.swal2-styled):where(.swal2-cancel):active{background-color:color-mix(in srgb, var(--swal2-cancel-button-background-color), var(--swal2-action-button-active))}div:where(.swal2-container) button:where(.swal2-styled):focus-visible{outline:none;box-shadow:var(--swal2-action-button-focus-box-shadow)}div:where(.swal2-container) button:where(.swal2-styled)[disabled]:not(.swal2-loading){opacity:.4}div:where(.swal2-container) button:where(.swal2-styled)::-moz-focus-inner{border:0}div:where(.swal2-container) div:where(.swal2-footer){margin:1em 0 0;padding:1em 1em 0;border-top:1px solid var(--swal2-footer-border-color);background:var(--swal2-footer-background);color:var(--swal2-footer-color);font-size:1em;text-align:center;cursor:initial}div:where(.swal2-container) .swal2-timer-progress-bar-container{position:absolute;right:0;bottom:0;left:0;grid-column:auto !important;overflow:hidden;border-bottom-right-radius:var(--swal2-border-radius);border-bottom-left-radius:var(--swal2-border-radius)}div:where(.swal2-container) div:where(.swal2-timer-progress-bar){width:100%;height:.25em;background:var(--swal2-timer-progress-bar-background)}div:where(.swal2-container) img:where(.swal2-image){max-width:100%;margin:2em auto 1em;cursor:initial}div:where(.swal2-container) button:where(.swal2-close){position:var(--swal2-close-button-position);inset:var(--swal2-close-button-inset);z-index:2;align-items:center;justify-content:center;width:1.2em;height:1.2em;margin-top:0;margin-right:0;margin-bottom:-1.2em;padding:0;overflow:hidden;transition:var(--swal2-close-button-transition);border:none;border-radius:var(--swal2-border-radius);outline:var(--swal2-close-button-outline);background:rgba(0,0,0,0);color:var(--swal2-close-button-color);font-family:monospace;font-size:var(--swal2-close-button-font-size);cursor:pointer;justify-self:end}div:where(.swal2-container) button:where(.swal2-close):hover{transform:var(--swal2-close-button-hover-transform);background:rgba(0,0,0,0);color:#f27474}div:where(.swal2-container) button:where(.swal2-close):focus-visible{outline:none;box-shadow:var(--swal2-close-button-focus-box-shadow)}div:where(.swal2-container) button:where(.swal2-close)::-moz-focus-inner{border:0}div:where(.swal2-container) div:where(.swal2-html-container){z-index:1;justify-content:center;margin:0;padding:var(--swal2-html-container-padding);overflow:auto;color:inherit;font-size:1.125em;font-weight:normal;line-height:normal;text-align:center;word-wrap:break-word;word-break:break-word;cursor:initial}div:where(.swal2-container) input:where(.swal2-input),div:where(.swal2-container) input:where(.swal2-file),div:where(.swal2-container) textarea:where(.swal2-textarea),div:where(.swal2-container) select:where(.swal2-select),div:where(.swal2-container) div:where(.swal2-radio),div:where(.swal2-container) label:where(.swal2-checkbox){margin:1em 2em 3px}div:where(.swal2-container) input:where(.swal2-input),div:where(.swal2-container) input:where(.swal2-file),div:where(.swal2-container) textarea:where(.swal2-textarea){box-sizing:border-box;width:auto;transition:var(--swal2-input-transition);border:var(--swal2-input-border);border-radius:var(--swal2-input-border-radius);background:var(--swal2-input-background);box-shadow:var(--swal2-input-box-shadow);color:inherit;font-size:1.125em}div:where(.swal2-container) input:where(.swal2-input).swal2-inputerror,div:where(.swal2-container) input:where(.swal2-file).swal2-inputerror,div:where(.swal2-container) textarea:where(.swal2-textarea).swal2-inputerror{border-color:#f27474 !important;box-shadow:0 0 2px #f27474 !important}div:where(.swal2-container) input:where(.swal2-input):hover,div:where(.swal2-container) input:where(.swal2-file):hover,div:where(.swal2-container) textarea:where(.swal2-textarea):hover{box-shadow:var(--swal2-input-hover-box-shadow)}div:where(.swal2-container) input:where(.swal2-input):focus,div:where(.swal2-container) input:where(.swal2-file):focus,div:where(.swal2-container) textarea:where(.swal2-textarea):focus{border:var(--swal2-input-focus-border);outline:none;box-shadow:var(--swal2-input-focus-box-shadow)}div:where(.swal2-container) input:where(.swal2-input)::placeholder,div:where(.swal2-container) input:where(.swal2-file)::placeholder,div:where(.swal2-container) textarea:where(.swal2-textarea)::placeholder{color:#ccc}div:where(.swal2-container) .swal2-range{margin:1em 2em 3px;background:var(--swal2-background)}div:where(.swal2-container) .swal2-range input{width:80%}div:where(.swal2-container) .swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}div:where(.swal2-container) .swal2-range input,div:where(.swal2-container) .swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}div:where(.swal2-container) .swal2-input{height:2.625em;padding:0 .75em}div:where(.swal2-container) .swal2-file{width:75%;margin-right:auto;margin-left:auto;background:var(--swal2-input-background);font-size:1.125em}div:where(.swal2-container) .swal2-textarea{height:6.75em;padding:.75em}div:where(.swal2-container) .swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:var(--swal2-input-background);color:inherit;font-size:1.125em}div:where(.swal2-container) .swal2-radio,div:where(.swal2-container) .swal2-checkbox{align-items:center;justify-content:center;background:var(--swal2-background);color:inherit}div:where(.swal2-container) .swal2-radio label,div:where(.swal2-container) .swal2-checkbox label{margin:0 .6em;font-size:1.125em}div:where(.swal2-container) .swal2-radio input,div:where(.swal2-container) .swal2-checkbox input{flex-shrink:0;margin:0 .4em}div:where(.swal2-container) label:where(.swal2-input-label){display:flex;justify-content:center;margin:1em auto 0}div:where(.swal2-container) div:where(.swal2-validation-message){align-items:center;justify-content:center;margin:1em 0 0;padding:.625em;overflow:hidden;background:var(--swal2-validation-message-background);color:var(--swal2-validation-message-color);font-size:1em;font-weight:300}div:where(.swal2-container) div:where(.swal2-validation-message)::before{content:\"!\";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}div:where(.swal2-container) .swal2-progress-steps{flex-wrap:wrap;align-items:center;max-width:100%;margin:1.25em auto;padding:0;background:rgba(0,0,0,0);font-weight:600}div:where(.swal2-container) .swal2-progress-steps li{display:inline-block;position:relative}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step{z-index:20;flex-shrink:0;width:2em;height:2em;border-radius:2em;background:#2778c4;color:#fff;line-height:2em;text-align:center}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#2778c4}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:var(--swal2-progress-step-background);color:#fff}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:var(--swal2-progress-step-background)}div:where(.swal2-container) .swal2-progress-steps .swal2-progress-step-line{z-index:10;flex-shrink:0;width:2.5em;height:.4em;margin:0 -1px;background:#2778c4}div:where(.swal2-icon){position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:2.5em auto .6em;zoom:var(--swal2-icon-zoom);border:.25em solid rgba(0,0,0,0);border-radius:50%;border-color:#000;font-family:inherit;line-height:5em;cursor:default;user-select:none}div:where(.swal2-icon) .swal2-icon-content{display:flex;align-items:center;font-size:3.75em}div:where(.swal2-icon).swal2-error{border-color:#f27474;color:#f27474}div:where(.swal2-icon).swal2-error .swal2-x-mark{position:relative;flex-grow:1}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;transform:rotate(45deg)}div:where(.swal2-icon).swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;transform:rotate(-45deg)}@container swal2-popup style(--swal2-icon-animations:true){div:where(.swal2-icon).swal2-error.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-error.swal2-icon-show .swal2-x-mark{animation:swal2-animate-error-x-mark .5s}}div:where(.swal2-icon).swal2-warning{border-color:#f8bb86;color:#f8bb86}@container swal2-popup style(--swal2-icon-animations:true){div:where(.swal2-icon).swal2-warning.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-warning.swal2-icon-show .swal2-icon-content{animation:swal2-animate-i-mark .5s}}div:where(.swal2-icon).swal2-info{border-color:#3fc3ee;color:#3fc3ee}@container swal2-popup style(--swal2-icon-animations:true){div:where(.swal2-icon).swal2-info.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-info.swal2-icon-show .swal2-icon-content{animation:swal2-animate-i-mark .8s}}div:where(.swal2-icon).swal2-question{border-color:#87adbd;color:#87adbd}@container swal2-popup style(--swal2-icon-animations:true){div:where(.swal2-icon).swal2-question.swal2-icon-show{animation:swal2-animate-error-icon .5s}div:where(.swal2-icon).swal2-question.swal2-icon-show .swal2-icon-content{animation:swal2-animate-question-mark .8s}}div:where(.swal2-icon).swal2-success{border-color:#a5dc86;color:#a5dc86}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;border-radius:50%}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line][class$=left]{top:-0.4375em;left:-2.0635em;transform:rotate(-45deg);transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}div:where(.swal2-icon).swal2-success [class^=swal2-success-circular-line][class$=right]{top:-0.6875em;left:1.875em;transform:rotate(-45deg);transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}div:where(.swal2-icon).swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-0.25em;left:-0.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}div:where(.swal2-icon).swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;transform:rotate(-45deg)}div:where(.swal2-icon).swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}div:where(.swal2-icon).swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.8125em;width:1.5625em;transform:rotate(45deg)}div:where(.swal2-icon).swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;transform:rotate(-45deg)}@container swal2-popup style(--swal2-icon-animations:true){div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-line-tip{animation:swal2-animate-success-line-tip .75s}div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-line-long{animation:swal2-animate-success-line-long .75s}div:where(.swal2-icon).swal2-success.swal2-icon-show .swal2-success-circular-line-right{animation:swal2-rotate-success-circular-line 4.25s ease-in}}[class^=swal2]{-webkit-tap-highlight-color:rgba(0,0,0,0)}.swal2-show{animation:var(--swal2-show-animation)}.swal2-hide{animation:var(--swal2-hide-animation)}.swal2-noanimation{transition:none}.swal2-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.swal2-rtl .swal2-close{margin-right:initial;margin-left:0}.swal2-rtl .swal2-timer-progress-bar{right:0;left:auto}.swal2-toast{box-sizing:border-box;grid-column:1/4 !important;grid-row:1/4 !important;grid-template-columns:min-content auto min-content;padding:1em;overflow-y:hidden;border:var(--swal2-toast-border);background:var(--swal2-background);box-shadow:var(--swal2-toast-box-shadow);pointer-events:all}.swal2-toast>*{grid-column:2}.swal2-toast h2:where(.swal2-title){margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-toast .swal2-loading{justify-content:center}.swal2-toast input:where(.swal2-input){height:2em;margin:.5em;font-size:1em}.swal2-toast .swal2-validation-message{font-size:1em}.swal2-toast div:where(.swal2-footer){margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-toast button:where(.swal2-close){grid-column:3/3;grid-row:1/99;align-self:center;width:.8em;height:.8em;margin:0;font-size:2em}.swal2-toast div:where(.swal2-html-container){margin:.5em 1em;padding:0;overflow:initial;font-size:1em;text-align:initial}.swal2-toast div:where(.swal2-html-container):empty{padding:0}.swal2-toast .swal2-loader{grid-column:1;grid-row:1/99;align-self:center;width:2em;height:2em;margin:.25em}.swal2-toast .swal2-icon{grid-column:1;grid-row:1/99;align-self:center;width:2em;min-width:2em;height:2em;margin:0 .5em 0 0}.swal2-toast .swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:1.8em;font-weight:bold}.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-toast div:where(.swal2-actions){justify-content:flex-start;height:auto;margin:0;margin-top:.5em;padding:0 .5em}.swal2-toast button:where(.swal2-styled){margin:.25em .5em;padding:.4em .6em;font-size:1em}.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;border-radius:50%}.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-0.8em;left:-0.5em;transform:rotate(-45deg);transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-0.25em;left:.9375em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}@container swal2-popup style(--swal2-icon-animations:true){.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip{animation:swal2-toast-animate-success-line-tip .75s}.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long{animation:swal2-toast-animate-success-line-long .75s}}.swal2-toast.swal2-show{animation:var(--swal2-toast-show-animation)}.swal2-toast.swal2-hide{animation:var(--swal2-toast-hide-animation)}@keyframes swal2-show{0%{transform:scale(0.7)}45%{transform:scale(1.05)}80%{transform:scale(0.95)}100%{transform:scale(1)}}@keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(0.5);opacity:0}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-0.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(0.4);opacity:0}50%{margin-top:1.625em;transform:scale(0.4);opacity:0}80%{margin-top:-0.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0deg);opacity:1}}@keyframes swal2-rotate-loading{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-toast-show{0%{transform:translateY(-0.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(0.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0deg)}}@keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-0.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}");

/**
 * The Cron object
 * This object is used to fetch the cron jobs, and run them
 * @type {{runCron: (function(*=): Promise<void>)}}
 */
const Cron = {
  /**
   * The run cron function
   * @param endpoint The (optional) endpoint to run the cron job on
   * @returns {Promise<void>}
   */
  runCron: async (endpoint = '') => {
    return await authenticatedRequest('/superuser/cron', "POST", {
      job: endpoint === '' ? null : endpoint
    })
        .then(
            (response) => {
              // Success
              Swal.fire({
                title: 'Success',
                text: 'The cron job has been run',
                icon: 'success',
                confirmButtonText: 'OK'
              });
            }
        )
        .catch(
            (error) => {
              parseError(error, 'universalRunCron');
            }
        );
  },
  /**
   * The get cron status function
   * @param endpoint
   * @returns {Promise<void>}
   */
  getCronStatus: async (endpoint) => {
    return await authenticatedRequest(endpoint, "GET", {})
        .then(
            (response) => {
              // Success
              Swal.fire({
                title: 'Success',
                text: 'The cron job has been run',
                icon: 'success',
                confirmButtonText: 'OK'
              });
            }
        )
        .catch(
            (error) => {
              parseError(error, 'universalRunCron');
            }
        );
  },
  /**
   * Cron jobs
   */
  cronJobs: ref([
    {
      name: 'All cron jobs',
      description: 'Run all cron jobs',
      icon: 'fas fa-sync-alt',
      endpoint: ''
    },
    {
      name: 'Syncronize logs',
      description: 'Syncronize the logs',
      icon: 'fas fa-sync-alt',
      endpoint: 'SyncLogs'
    },
    {
      name: 'Syncronize bookings',
      description: 'Syncronize the bookings',
      icon: 'fas fa-sync-alt',
      endpoint: 'SyncBookings'
    },
    {
      name: 'Check unfulfilled bookings',
      description: 'Check if there are any unfulfilled bookings',
      icon: 'fas fa-sync-alt',
      endpoint: 'CheckUnfulfilledBookings'
    },
    {
      name: 'Clear all users economic discount from cache',
      description: 'Clear all users economic discount from cache',
      icon: 'fas fa-sync-alt',
      endpoint: 'ClearEconomicDiscountCache'
    }
  ])
};


const _sfc_main$3n = {};
const cron = /*#__PURE__*/_export_sfc(_sfc_main$3n, [['__file',"cron.vue"]]);

const handleEconomicError = (error) => {
  if (error.response) {
    // Check if the response has the economic_error meta field
    if (error.response.data.meta && error.response.data.meta.economic_errors) {
      // Turn the economic_errors object into a string and display it

      Swal.fire({
        title: 'Fejl fra e-conomic',
        text: error.response.data.data.message,
        icon: 'error',
        confirmButtonText: 'Læs mere',
        cancelButtonText: 'OK',
        showCancelButton: true,
      })
      .then((result) => {
        if (result.isConfirmed) {
          Swal.fire({
            title: 'Fejl fra e-conomic',
            html: '<pre style="text-align: left; max-height: 40vh; overflow-y: auto;">' + JSON.stringify(error.response.data.meta.economic_errors, null, 2) + '</pre>',
            icon: 'error',
            confirmButtonText: 'Kopier til udklipsholder',
            cancelButtonText: 'Luk',
            showCancelButton: true,
            width: '50rem',
          })
          .then((result) => {
            if (result.isConfirmed) {
              navigator.clipboard.writeText(JSON.stringify(error.response.data.meta.economic_errors, null, 2));
            }
          });
        }
      });
      return;
    }
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    if (error.response.data.data.message) {
      Swal.fire({
        title: 'Fejl',
        text: error.response.data.data.message,
        icon: 'error',
        confirmButtonText: 'OK'
      });
    } else {
      Swal.fire({
        title: 'Fejl',
        text: error.response.data.message,
        icon: 'error',
        confirmButtonText: 'OK'
      });
    }
  } else if (error.request) {
    // The request was made but no response was received
    Swal.fire({
      title: 'Fejl',
      text: 'Ingen respons modtaget',
      icon: 'error',
      confirmButtonText: 'OK'
    });
  } else {
    // Something happened in setting up the request that triggered an Error
    Swal.fire({
      title: 'Fejl',
      text: 'Der skete en fejl',
      icon: 'error',
      confirmButtonText: 'OK'
    });
  }
  // Log the error to the console
  console.log('Caught error:', error);
};

const _sfc_main$3m = {};
const HandleEconomicError = /*#__PURE__*/_export_sfc(_sfc_main$3m, [['__file',"HandleEconomicError.vue"]]);

/**
 * The Economic -> Layouts object
 */
const Layouts = {
    get: async () => {
      return authenticatedRequest(
          "/economic/layouts",
          "GET")
    },
    set: async (layout) => {
      return SessionUser.superUser.modules.economic.config.layouts.set(layout);
    },
};


const _sfc_main$3l = {};
const Layouts_default = /*#__PURE__*/_export_sfc(_sfc_main$3l, [['__file',"Layouts.vue"]]);

/**
 * The Economic -> PaymentTerms object
 */
const PaymentTerms = {
    get: async () => {
      return authenticatedRequest(
          "/economic/payment-terms",
          "GET")
    }
};


const _sfc_main$3k = {};
const PaymentTerms_default = /*#__PURE__*/_export_sfc(_sfc_main$3k, [['__file',"PaymentTerms.vue"]]);

/**
 * The Economic -> Config object
 */
const Config$o = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/economic/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/economic/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/economic/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    layouts: {
      invoiceLayoutNumber: {
        get: async () => {
          return Config$o.get("invoiceLayoutNumber");
        },
        set: async (layout) => {
          return Config$o.set("invoiceLayoutNumber", layout);
        },
      },
      invoiceDiscountLayoutNumber: {
        get: async () => {
          return Config$o.get("invoiceDiscountLayoutNumber");
        },
        set: async (layout) => {
          return Config$o.set("invoiceDiscountLayoutNumber", layout);
        },
      },
    },
    fees: {
     adminFeeMonthly:  {
        get: async () => {
          return Config$o.get("adminFeeMonthly");
        },
        set: async (amount) => {
          return Config$o.set("adminFeeMonthly", amount);
        },
      },
      adminFeeOrder: {
        get: async () => {
          return Config$o.get("adminFeeOrder");
        },
        set: async (amount) => {
          return Config$o.set("adminFeeOrder", amount);
        },
      },
      feeProductId: {
        get: async () => {
          return Config$o.get("feeProductId");
        },
        set: async (productId) => {
          return Config$o.set("feeProductId", productId);
        },
      },
    },
    transactionDraftCustomerNumber: {
      get: async () => {
        return Config$o.get("transactionDraftCustomerNumber");
      },
      set: async (customerNumber) => {
        return Config$o.set("transactionDraftCustomerNumber", customerNumber);
      },
    },
    defaultDepartmentId: {
      get: async () => {
        return Config$o.get("defaultDepartmentId");
      },
      set: async (departmentId) => {
        return Config$o.set("defaultDepartmentId", departmentId);
      },
    }
};


const _sfc_main$3j = {};
const Config_default$n = /*#__PURE__*/_export_sfc(_sfc_main$3j, [['__file',"Config.vue"]]);

/**
 * The Economic object
 */
const Economic = {
  meta: {
    title: "E-conomic",
    icon: "fas fa-euro-sign",
    description: "Integration med Economic",
    endpoint: "/economic",
    config_endpoint: "/configuration/economic",
    labels: {
      single: "Economic",
      multiple: "Economic"
    }
  },
  layouts: Layouts,
  paymentTerms: PaymentTerms,
  config: Config$o,
  functions: {
    customers: {
      /**
       * Import customer from economic
       * @param customerNumber
       * @returns {Promise}
       */
      import: async (customerNumber) => {
        return authenticatedRequest(
            "/economic/customers/import",
            "POST",
            {
              customer_number: customerNumber
            }
        ).catch((error) => {
          handleEconomicError(error);
        });
      }
    },
    departments: {
      /**
       * Get department from economic
       * @returns {Promise}
       */
      get: async () => {
        return authenticatedRequest(
            "/economic/departments",
            "GET"
        ).catch((error) => {
          handleEconomicError(error);
        });
      }
    }
  }
};


const _sfc_main$3i = {};
const Economic_default = /*#__PURE__*/_export_sfc(_sfc_main$3i, [['__file',"Economic.vue"]]);

/**
 * The reCAPTCHA -> API Keys object
 */
const API_keys = {
    get: async () => {
      return authenticatedRequest(
          "/reCAPTCHA/api_keys",
          "GET")
    },
    set: async (api_key) => {
      return SessionUser.superUser.modules.reCAPTCHA.config.API_keys.set(api_key);
    },
};


const _sfc_main$3h = {};
const ApiKeys = /*#__PURE__*/_export_sfc(_sfc_main$3h, [['__file',"ApiKeys.vue"]]);

/**
 * The reCAPTCHA -> Config object
 */
const Config$n = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/reCAPTCHA/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/reCAPTCHA/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/reCAPTCHA/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      site_key_v2: {
        get: async () => {
          return Config$n.get("site_key_v2");
        },
        set: async (value) => {
          return Config$n.set("site_key_v2", value);
        },
      },
      secret_key_v2: {
        get: async () => {
          return Config$n.get("secret_key_v2");
        },
        set: async (value) => {
          return Config$n.set("secret_key_v2", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$n.get("enabled");
      },
      set: async (enabled) => {
        return Config$n.set("enabled", enabled);
      },
  },
};


const _sfc_main$3g = {};
const Config_default$m = /*#__PURE__*/_export_sfc(_sfc_main$3g, [['__file',"Config.vue"]]);

/**
 * The reCAPTCHA object
 */
const reCAPTCHA$1 = {
  meta: {
    title: "reCAPTCHA",
    icon: "fas fa-shield-alt",
    description: "Integration med reCAPTCHA",
    endpoint: "/recaptcha",
    config_endpoint: "/configuration/recaptcha",
    labels: {
      single: "reCAPTCHA",
      multiple: "reCAPTCHA"
    }
  },
  api_keys: API_keys,
  config: Config$n,
};


const _sfc_main$3f = {};
const reCAPTCHA_default$1 = /*#__PURE__*/_export_sfc(_sfc_main$3f, [['__file',"reCAPTCHA.vue"]]);

/**
 * The Email -> Config object
 */
const Config$m = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/email/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/email/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/email/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      smtp_host: {
        get: async () => {
          return Config$m.get("smtp_host");
        },
        set: async (value) => {
          return Config$m.set("smtp_host", value);
        },
      },
      smtp_port: {
        get: async () => {
          return Config$m.get("smtp_port");
        },
        set: async (value) => {
          return Config$m.set("smtp_port", parseInt(value));
        },
      },
      smtp_username: {
        get: async () => {
          return Config$m.get("smtp_username");
        },
        set: async (value) => {
          return Config$m.set("smtp_username", value);
        },
      },
      smtp_password: {
        get: async () => {
          return Config$m.get("smtp_password");
        },
        set: async (value) => {
          return Config$m.set("smtp_password", value);
        },
      },
      smtp_encryption: {
        get: async () => {
          return Config$m.get("smtp_encryption");
        },
        set: async (value) => {
          return Config$m.set("smtp_encryption", value);
        },
      },
      smtp_from: {
        get: async () => {
          return Config$m.get("smtp_from");
        },
        set: async (value) => {
          return Config$m.set("smtp_from", value);
        },
      },
      smtp_from_name: {
        get: async () => {
          return Config$m.get("smtp_from_name");
        },
        set: async (value) => {
          return Config$m.set("smtp_from_name", value);
        },
      },
      smtp_reply_to: {
        get: async () => {
          return Config$m.get("smtp_reply_to");
        },
        set: async (value) => {
          return Config$m.set("smtp_reply_to", value);
        },
      },
      smtp_reply_to_name: {
        get: async () => {
          return Config$m.get("smtp_reply_to_name");
        },
        set: async (value) => {
          return Config$m.set("smtp_reply_to_name", value);
        },
      },
      mailersend_enabled: {
        get: async () => {
          return Config$m.get("mailersend_enabled");
        },
        set: async (value) => {
          return Config$m.set("mailersend_enabled", value);
        },
      },
      mailersend_api_key: {
        get: async () => {
          return Config$m.get("mailersend_api_key");
        },
        set: async (value) => {
          return Config$m.set("mailersend_api_key", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$m.get("enabled");
      },
      set: async (enabled) => {
        return Config$m.set("enabled", enabled);
      },
  },
};


const _sfc_main$3e = {};
const Config_default$l = /*#__PURE__*/_export_sfc(_sfc_main$3e, [['__file',"Config.vue"]]);

/**
 * The Email object
 */
const Email = {
  meta: {
    title: "Email",
    icon: "fas fa-envelope",
    description: "Email konfiguration",
    endpoint: "/email/config",
    config_endpoint: "/configuration/email",
    labels: {
      single: "email",
      multiple: "email"
    }
  },
  config: Config$m,
  sendTestEmail: async (email) => {
    return authenticatedRequest(
        "/email/config/test",
        "POST",
        {
          email: email
        }
    )
  },
};


const _sfc_main$3d = {};
const Email_default = /*#__PURE__*/_export_sfc(_sfc_main$3d, [['__file',"Email.vue"]]);

/**
 * The Backups -> Config object
 */
const Config$l = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/backups/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/backups/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/backups/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      examplevariable1: {
        get: async () => {
          return Config$l.get("example_var1")
        },
        set: async (value) => {
          return Config$l.set("example_var1", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$l.get("enabled");
      },
      set: async (enabled) => {
        return Config$l.set("enabled", enabled);
      },
    },
    retentionRecentHours: {
      set: async (value) => Config$l.set("retention_recent_hours", value),
    },
    retentionDailyDays: {
      set: async (value) => Config$l.set("retention_daily_days", value),
    },
    retentionWeeklyWeeks: {
      set: async (value) => Config$l.set("retention_weekly_weeks", value),
    },
    retentionMonthlyMonths: {
      set: async (value) => Config$l.set("retention_monthly_months", value),
    },
    appDataEnabled: {
      set: async (enabled) => Config$l.set("app_data_enabled", enabled),
    },
    verificationRequired: {
      set: async (enabled) => Config$l.set("verification_required", enabled),
    },
    restoreEnabled: {
      set: async (enabled) => Config$l.set("restore_enabled", enabled),
    },
};


const _sfc_main$3c = {};
const Config_default$k = /*#__PURE__*/_export_sfc(_sfc_main$3c, [['__file',"Config.vue"]]);

/**
 * The Backups object
 */
const Backups = {
  meta: {
    title: "Backups",
    icon: "fas fa-database",
    description: "Backup af data",
    endpoint: "/modules/backup/backups",
    config_endpoint: "/configuration/backup",
    labels: {
      single: "backup",
      multiple: "backups"
    }
  },
  config: Config$l,
  createBackup: async (name = null, description = null) => {
    return authenticatedRequest(
        Backups.meta.endpoint,
        "POST",
        {
          name: name,
          description: description
        }
    )
  },
  getJob: async (jobId) => {
    return authenticatedRequest(
        `/modules/backup/jobs/${jobId}`,
        "GET"
    )
  },
  listBackups: async () => {
    return authenticatedRequest(
        Backups.meta.endpoint,
        "GET"
    )
  },
  verifyBackup: async (backupUuid) => {
    return authenticatedRequest(
        `${Backups.meta.endpoint}/${backupUuid}/verify`,
        "POST"
    )
  },
  previewRestore: async (backupUuid) => {
    return authenticatedRequest(
        `${Backups.meta.endpoint}/${backupUuid}/restore/preview`,
        "POST"
    )
  },
  restoreBackup: async (backupUuid, previewId, confirmationPhrase, reason) => {
    return authenticatedRequest(
        `${Backups.meta.endpoint}/${backupUuid}/restore`,
        "POST",
        {
          preview_id: previewId,
          confirmation_phrase: confirmationPhrase,
          reason: reason
        }
    )
  },
  restoreAudit: async () => {
    return authenticatedRequest(
        "/modules/backup/restore-audit",
        "GET"
    )
  },
};


const _sfc_main$3b = {};
const Backups_default = /*#__PURE__*/_export_sfc(_sfc_main$3b, [['__file',"Backups.vue"]]);

/**
 * The MotorAPI -> Config object
 */
const Config$k = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/motorapi/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/motorapi/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/motorapi/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      daily_limit: {
        get: async () => {
          return Config$k.get("daily_limit");
        },
        set: async (value) => {
          return Config$k.set("daily_limit", value);
        },
      },
      secret_key: {
        get: async () => {
          return Config$k.get("secret_key");
        },
        set: async (value) => {
          return Config$k.set("secret_key", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$k.get("enabled");
      },
      set: async (enabled) => {
        return Config$k.set("enabled", enabled);
      },
  },
};


const _sfc_main$3a = {};
const Config_default$j = /*#__PURE__*/_export_sfc(_sfc_main$3a, [['__file',"Config.vue"]]);

/**
 * The MotorAPI object
 */
const MotorAPI = {
  meta: {
    title: "MotorAPI",
    icon: "fas fa-car",
    description: "MotorAPI",
    endpoint: "/modules/motorapi",
    config_endpoint: "/configuration/motorapi",
    labels: {
      single: "motorapi",
      multiple: "motorapi"
    }
  },
  config: Config$k,
  functions: {
    lookup: async (licensePlate) => {
      return authenticatedRequest(
          "/modules/motorapi/lookup?license_plate=" + licensePlate,
          "GET"
          )
    },
  }
};


const _sfc_main$39 = {};
const MotorAPI_default = /*#__PURE__*/_export_sfc(_sfc_main$39, [['__file',"MotorAPI.vue"]]);

/**
 * The Stripe -> Config object
 */
const Config$j = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/stripe/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/stripe/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/stripe/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      publishable_key: {
        get: async () => {
          return Config$j.get("publishable_key");
        },
        set: async (value) => {
          return Config$j.set("publishable_key", value);
        },
      },
      secret_key: {
        get: async () => {
          return Config$j.get("secret_key");
        },
        set: async (value) => {
          return Config$j.set("secret_key", value);
        },
      },
      economic_customer_number: {
        get: async () => {
          return Config$j.get("economic_customer_number");
        },
        set: async (value) => {
          return Config$j.set("economic_customer_number", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$j.get("enabled");
      },
      set: async (enabled) => {
        return Config$j.set("enabled", enabled);
      },
  },
};


const _sfc_main$38 = {};
const Config_default$i = /*#__PURE__*/_export_sfc(_sfc_main$38, [['__file',"Config.vue"]]);

/**
 * The Stripe object
 */
const Stripe = {
  meta: {
    title: "Stripe",
    icon: "fas fa-credit-card",
    description: "Stripe integration",
    endpoint: "/modules/stripe",
    config_endpoint: "/configuration/stripe",
    labels: {
      single: "Stripe",
      multiple: "Stripe"
    }
  },
  config: Config$j,
  functions: {
    customers: {
      list: async () => {
        return authenticatedRequest(
            "/modules/stripe/customers",
            "GET")
      },
    },
    products: {
      list: async () => {
        return authenticatedRequest(
            "/modules/stripe/products",
            "GET")
      },
    },
    prices: {
      list: async () => {
        return authenticatedRequest(
            "/modules/stripe/prices",
            "GET")
      },
    },
    terminals: {
      readers: {
        list: async () => {
          return authenticatedRequest(
              "/modules/stripe/terminal/readers",
              "GET")
        },
        listDepartment: async (departmentId) => {
          return authenticatedRequest(
              "/modules/stripe/department/terminal/readers?id=" + departmentId,
              "GET")
        },
      },
      locations: {
        list: async () => {
          return authenticatedRequest(
              "/modules/stripe/terminal/locations",
              "GET")
        },
        getDepartmentLocation: async (departmentId) => {
          return authenticatedRequest(
              "/modules/stripe/department/terminal/location?id=" + departmentId,
              "GET")
        },
        setDepartmentLocation: async (departmentId, locationId) => {
          return authenticatedRequest(
              "/modules/stripe/department/terminal/location",
              "POST",
              {
                id: departmentId,
                location: locationId
              })
        },
      },
    },
  },
  departments: {
    terminals: {
      location: {
        get: async (departmentId) => {return Stripe.functions.terminals.locations.getDepartmentLocation(departmentId)},
        set: async (departmentId, locationId) => {return Stripe.functions.terminals.locations.setDepartmentLocation(departmentId, locationId)},
      },
      readers: {
        list: async (departmentId) => {return Stripe.functions.terminals.readers.listDepartment(departmentId)},
      },
    },
  },
};


const _sfc_main$37 = {};
const Stripe_default = /*#__PURE__*/_export_sfc(_sfc_main$37, [['__file',"Stripe.vue"]]);

/**
 * The FXRatesAPI -> Config object
 */
const Config$i = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/fxratesapi/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/fxratesapi/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/fxratesapi/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      daily_limit: {
        get: async () => {
          return Config$i.get("daily_limit");
        },
        set: async (value) => {
          return Config$i.set("daily_limit", value);
        },
      },
      secret_key: {
        get: async () => {
          return Config$i.get("secret_key");
        },
        set: async (value) => {
          return Config$i.set("secret_key", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$i.get("enabled");
      },
      set: async (enabled) => {
        return Config$i.set("enabled", enabled);
      },
  },
};


const _sfc_main$36 = {};
const Config_default$h = /*#__PURE__*/_export_sfc(_sfc_main$36, [['__file',"Config.vue"]]);

/**
 * The FXRatesAPI object
 */
const FXRatesAPI = {
  meta: {
    title: "FXRatesAPI",
    icon: "fas fa-car",
    description: "FXRatesAPI, som bruges til at hente valutakurser",
    endpoint: "/modules/fxratesapi",
    config_endpoint: "/configuration/fxratesapi",
    labels: {
      single: "fxratesapi",
      multiple: "fxratesapi"
    }
  },
  config: Config$i,
  functions: {
    conversion_rate: async (base = 'DKK', target = 'EUR') => {
      return authenticatedRequest(
          "/modules/fxratesapi/rate",
          "GET",
          {
            base: base,
            target: target
          })
    },
    conversion_rates: async (base = 'DKK') => {
      return authenticatedRequest(
          "/modules/fxratesapi/rates",
          "GET",
          {
            base: base
          })
    },
  }
};


const _sfc_main$35 = {};
const FXRatesAPI_default = /*#__PURE__*/_export_sfc(_sfc_main$35, [['__file',"FXRatesAPI.vue"]]);

/**
 * The WeatherAPI -> Config object
 */
const Config$h = {
  get: async (variable) => {
    return authenticatedRequest(
      "/weatherapi/config?variable=" + variable,
      "GET"
    );
  },
  get_all: async () => {
    return authenticatedRequest(
      "/weatherapi/config",
      "GET"
    );
  },
  set: async (variable, value) => {
    return authenticatedRequest(
      "/weatherapi/config",
      "POST",
      {
        variable: variable,
        value: value
      }
    );
  },
  keys: {
    secret_key: {
      get: async () => {
        return Config$h.get("secret_key");
      },
      set: async (value) => {
        return Config$h.set("secret_key", value);
      },
    },
  },
  enabled: {
    get: async () => {
      return Config$h.get("enabled");
    },
    set: async (enabled) => {
      return Config$h.set("enabled", enabled);
    },
  },
};


const _sfc_main$34 = {};
const Config_default$g = /*#__PURE__*/_export_sfc(_sfc_main$34, [['__file',"Config.vue"]]);

/**
 * The WeatherAPI object
 */
const WeatherAPI = {
  meta: {
    title: "WeatherAPI",
    icon: "fas fa-cloud-sun",
    description: "The WeatherAPI integration",
    endpoint: "/modules/weatherapi",
    config_endpoint: "/configuration/weatherapi",
    labels: {
      single: "weatherapi",
      multiple: "weatherapi",
    }
  },
  config: Config$h,
  functions: {
    current: async (query) => {
      return authenticatedRequest(
        "/modules/weatherapi/current?q=" + encodeURIComponent(query),
        "GET"
      );
    },
    forecast: async (query, days = null) => {
      const daysParameter = Number.isInteger(days) ? "&days=" + days : "";
      return authenticatedRequest(
        "/modules/weatherapi/forecast?q=" + encodeURIComponent(query) + daysParameter,
        "GET"
      );
    },
    search: async (query) => {
      return authenticatedRequest(
        "/modules/weatherapi/search?q=" + encodeURIComponent(query),
        "GET"
      );
    },
  }
};


const _sfc_main$33 = {};
const WeatherAPI_default = /*#__PURE__*/_export_sfc(_sfc_main$33, [['__file',"WeatherAPI.vue"]]);

/**
 * The Workfeed -> Config object
 */
const Config$g = {
  get: async (variable) => {
    return authenticatedRequest(
      "/workfeed/config?variable=" + variable,
      "GET"
    );
  },
  get_all: async () => {
    return authenticatedRequest(
      "/workfeed/config",
      "GET"
    );
  },
  set: async (variable, value) => {
    return authenticatedRequest(
      "/workfeed/config",
      "POST",
      {
        variable: variable,
        value: value
      }
    );
  },
  keys: {
    api_url: {
      get: async () => {
        return Config$g.get("api_url");
      },
      set: async (value) => {
        return Config$g.set("api_url", value);
      },
    },
    api_key: {
      get: async () => {
        return Config$g.get("api_key");
      },
      set: async (value) => {
        return Config$g.set("api_key", value);
      },
    },
    companyId: {
      get: async () => {
        return Config$g.get("CompanyID");
      },
      set: async (value) => {
        return Config$g.set("CompanyID", value);
      },
    },
  },
  enabled: {
    get: async () => {
      return Config$g.get("enabled");
    },
    set: async (enabled) => {
      return Config$g.set("enabled", enabled);
    },
  },
};

const _sfc_main$32 = {};
const Config_default$f = /*#__PURE__*/_export_sfc(_sfc_main$32, [['__file',"Config.vue"]]);

const sanitizeQuery = (query = {}) => {
  return Object.fromEntries(
    Object.entries(query).filter(([, value]) => value !== undefined && value !== null && value !== "")
  );
};

/**
 * The Workfeed object
 */
const Workfeed = {
  meta: {
    title: "Workfeed",
    icon: "fas fa-users-cog",
    description: "The Workfeed integration",
    endpoint: "/modules/workfeed",
    config_endpoint: "/configuration/workfeed",
    labels: {
      single: "workfeed",
      multiple: "workfeed",
    }
  },
  config: Config$g,
  functions: {
    listEmployees: async () => {
      return authenticatedRequest(
        "/modules/workfeed/employees",
        "GET"
      );
    },
    getEmployee: async (id) => {
      return authenticatedRequest(
        "/modules/workfeed/employees/" + encodeURIComponent(id),
        "GET"
      );
    },
    listShifts: async ({
      startFrom,
      startTo,
      employeeID,
      released,
    } = {}) => {
      if (!startFrom || !startTo) {
        throw new Error("startFrom and startTo are required");
      }

      return authenticatedRequest(
        "/modules/workfeed/shifts",
        "GET",
        sanitizeQuery({
          startFrom,
          startTo,
          employeeID,
          released,
        })
      );
    },
    getShift: async (id) => {
      return authenticatedRequest(
        "/modules/workfeed/shifts/" + encodeURIComponent(id),
        "GET"
      );
    },
    listDepartments: async () => {
      return authenticatedRequest(
        "/modules/workfeed/departments",
        "GET"
      );
    },
  }
};

const _sfc_main$31 = {};
const Workfeed_default = /*#__PURE__*/_export_sfc(_sfc_main$31, [['__file',"Workfeed.vue"]]);

/**
 * The GatewayAPI -> Config object
 */
const Config$f = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/gatewayapi/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/gatewayapi/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/gatewayapi/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      api_secret: {
        get: async () => {
          return Config$f.get("api_secret");
        },
        set: async (value) => {
          return Config$f.set("api_secret", value);
        },
      },
      api_key: {
        get: async () => {
          return Config$f.get("api_key");
        },
        set: async (value) => {
          return Config$f.set("api_key", value);
        },
      },
      api_token: {
        get: async () => {
          return Config$f.get("api_token");
        },
        set: async (value) => {
          return Config$f.set("api_token", value);
        },
      },
      sender: {
        get: async () => {
          return Config$f.get("sender");
        },
        set: async (value) => {
          return Config$f.set("sender", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$f.get("enabled");
      },
      set: async (enabled) => {
        return Config$f.set("enabled", enabled);
      },
  },
};


const _sfc_main$30 = {};
const Config_default$e = /*#__PURE__*/_export_sfc(_sfc_main$30, [['__file',"Config.vue"]]);

/**
 * The GatewayAPI object
 */
const GatewayAPI = {
  meta: {
    title: "GatewayAPI",
    icon: "fas fa-cogs",
    description: "The GatewayAPI integration",
    endpoint: "/modules/gatewayapi",
    config_endpoint: "/configuration/gatewayapi",
    labels: {
      single: "gatewayapi",
      multiple: "gatewayapi",
    }
  },
  config: Config$f,
  functions: {}
};


const _sfc_main$2$ = {};
const GatewayAPI_default = /*#__PURE__*/_export_sfc(_sfc_main$2$, [['__file',"GatewayAPI.vue"]]);

/**
 * The XLVask -> Config object
 */
const Config$e = {
  get: async ( variable ) => {
    return authenticatedRequest(
        "/xlvask/config?variable=" + variable,
        "GET")
  },
  get_all: async () => {
    return authenticatedRequest(
        "/xlvask/config",
        "GET")
  },
  set: async ( variable, value ) => {
    return authenticatedRequest(
        "/xlvask/config",
        "POST",
        {
          variable: variable,
          value: value
        })
  },
  keys: {
    username: {
      get: async () => {
        return Config$e.get("username");
      },
      set: async (value) => {
        return Config$e.set("username", value);
      },
    },
    password: {
      get: async () => {
        return Config$e.get("password");
      },
      set: async (value) => {
        return Config$e.set("password", value);
      },
    },
    synchronization_enabled: {
      get: async () => {
        return Config$e.get("synchronization_enabled");
      },
      set: async (value) => {
        return Config$e.set("synchronization_enabled", value);
      },
    },
    automatic_order_attachment_enabled: {
      get: async () => {
        return Config$e.get("automatic_order_attachment_enabled");
      },
      set: async (value) => {
        return Config$e.set("automatic_order_attachment_enabled", value);
      },
    },
    automatic_order_creation_enabled: {
      get: async () => {
        return Config$e.get("automatic_order_creation_enabled");
      },
      set: async (value) => {
        return Config$e.set("automatic_order_creation_enabled", value);
      },
    },
    openai_integration_enabled: {
      get: async () => {
        return Config$e.get("openai_integration_enabled");
      },
      set: async (value) => {
        return Config$e.set("openai_integration_enabled", value);
      },
    },
  },
  enabled: {
    get: async () => {
      return Config$e.get("enabled");
    },
    set: async (enabled) => {
      return Config$e.set("enabled", enabled);
    },
  },
};

const _sfc_main$2_ = {};
const Config_default$d = /*#__PURE__*/_export_sfc(_sfc_main$2_, [['__file',"Config.vue"]]);

const xlvask_module_model_customer = {
  "customerId": String, // 21ba156a-b2d2-44be-8398-4b67d66003d6",
  "name": String, // DITOBUS EXCURSIONS A/S",
  "vendorId": String, // 9dde3a0a-197d-4172-8d0d-b4652d867593",
  "customerTypeId": String, // COMPANY",
  "discount": Number,
  "phone": String, // 59440200",
  "email": String, // faktura.excursions@ditobus.dk",
  "address": String, // K.P.Danøsvej 2",
  "address2": String, // null,
  "zip": String, // 4300",
  "city": String, // Holbæk",
  "userId": String, // 2f77a33c-6477-4cac-a16f-15d86346d1a5",
  "vatnumber": String, // 31171520",
  "excludeFromAutoInvoice": Boolean,
  "country": String, // dk",
  "createDate": String, // 2021-11-25T12:09:23",
  "externId": String, // 59440200",
  "active": Boolean,
  "language": String, // da",
  "note": String,
  "updated": String, // "2025-03-09T09:42:02.397"
};
const xlvask_module_model_washItem = {
  "WashItemId": String, // 6dad2e34-1004-42ea-9659-e8faf2936754,
  "ExternalProductId": null|String, // null,
  "ExternalProductName": null|String, // null,
  "OriginalProductName": String, // Ikke HT dysebom på front,
  "Unit": String, // stk,
  "UnitPrice": Number, // 0,
  "Count": Number, // 1,
  "Discount": Number, // 65,
  "PriceExVat": Number, // 0,
  "Vat": Number, // 0,
  "PriceIncVat": Number // 0
};
const xlvask_module_model_usageLog = {
  "WashId": String, // b250f016-8c78-4219-a779-d3789dd645ef,
  "CustomerId": String, // 59440200,
  "Customer": String, // DITOBUS EXCURSIONS A/S,
  "VatNumber": String, // 31171520,
  "Location": String, // Hvidovre,
  "Hall": String, // Hvidovre_1,
  "HallId": String, // 845d29a1-a7d2-4e3b-bbc3-2b13242d744a,
  "StartTime": String, // 2025-07-02T11:54:32.687,
  "FinishTime": String, // 2025-07-02T12:01:23.100,
  "RegistrationNumber": String, // DB90580,
  "VehicleType": String, // Bus/autocamper, M,
  "IdentificationType": String, // LPR,
  "IdentificationId": String, // DB90580,
  "Info": String, // DB90580,
  "Updated": String, // "",
  "Prepaid": null, // null,
  "FinishStatus": Number, // 1,
  "CustomerGuid": String, // 21ba156a-b2d2-44be-8398-4b67d66003d6,
  "VehicleId": String, // ce0f30f7-f814-40dc-9fd7-cff725892ca8,
  "WashItems": Array <xlvask_module_model_washItem>[],
};
/**
 * The XLVask object
 */
const XLVask = {
  meta: {
    title: "XLVask",
    icon: "fas fa-car",
    description: "XLVask",
    endpoint: "/modules/xlvask",
    config_endpoint: "/configuration/xlvask",
    labels: {
      single: "xlvask",
      multiple: "xlvask"
    }
  },
  config: Config$e,
  functions: {
    convertDateTimeToISO: (date) => {
      if (date === null) {
        return null
      }
      return date.getFullYear() + '-' +
          String(date.getMonth() + 1).padStart(2, '0') + '-' +
          String(date.getDate()).padStart(2, '0') + 'T' +
          String(date.getHours()).padStart(2, '0') + ':' +
          String(date.getMinutes()).padStart(2, '0') + ':' +
          String(date.getSeconds()).padStart(2, '0') + '.' +
          String(date.getMilliseconds()).padStart(3, '0')
    },
    convertISODateTimeToDate: (date) => {
      if (date === null) {
        return null
      }
      const dateTime = date.split('T');
      const dateParts = dateTime[0].split('-');
      const timeParts = dateTime[1].split(':');
      return new Date(dateParts[0], dateParts[1] - 1, dateParts[2], timeParts[0], timeParts[1], timeParts[2]);
    },
    testConnection: async () => {
      return SessionUser.superUser.modules.xlvask.functions.getCustomers(
          null,
          null,
          null,
          null,
      )
    },
    getUsageLog: async (dateFrom = null, regNr = null, customerId = null, vehicleId = null) => {
      return SessionUser.request(
          "/modules/xlvask/usageLog",
          "GET",
          {
            dateFrom: dateFrom,
            regNr: regNr,
            customerId: customerId,
            vehicleId: vehicleId,
          }
      )
    },
    getVehicles: async (customerId = null, vehicleId = null, registrationNumber = null, changeDate = null) => {
      return SessionUser.request(
          "/modules/xlvask/vehicles",
          "GET",
          {
            customerId: customerId,
            vehicleId: vehicleId,
            registrationNumber: registrationNumber,
            changeDate: changeDate,
          }
      )
    },
    getCustomers: async (customerId = null, customerName = null, customerExternalId = null, vatNumber = null, changeDate = null, users = null) => {
      return SessionUser.request(
          "/modules/xlvask/customers",
          "GET",
          {
            customerId: customerId,
            customerName: customerName,
            customerExternalId: customerExternalId,
            vatNumber: vatNumber,
            changeDate: changeDate,
            users: users,
          }
      )
    },
    getVehicleTypes: async () => {
      return SessionUser.request(
          "/modules/xlvask/internal/vehicle-types",
          "GET",
          {}
      )
    },
    getRelatedOrders(washIds) {
      console.log("Getting related orders for washIds: ", washIds);
      return SessionUser.request(
          "/modules/xlvask/related-orders",
          "GET",
          {
            washIds
          }
      )
    }
  },
  models: {
    customer: xlvask_module_model_customer,
    washItem: xlvask_module_model_washItem,
    usageLog: xlvask_module_model_usageLog,
  }
};

const _sfc_main$2Z = {};
const XLVask_default = /*#__PURE__*/_export_sfc(_sfc_main$2Z, [['__file',"XLVask.vue"]]);

/**
 * The Entra -> Config object
 */
const Config$d = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/entra/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/entra/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/entra/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      entra_client_id: {
        get: async () => {
          return Config$d.get("entra_client_id");
        },
        set: async (value) => {
          return Config$d.set("entra_client_id", value);
        },
      },
      entra_client_secret: {
        get: async () => {
          return Config$d.get("entra_client_secret");
        },
        set: async (value) => {
          return Config$d.set("entra_client_secret", value);
        },
      },
      entra_tenant_id: {
        get: async () => {
          return Config$d.get("entra_tenant_id");
        },
        set: async (value) => {
          return Config$d.set("entra_tenant_id", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$d.get("enabled");
      },
      set: async (enabled) => {
        return Config$d.set("enabled", enabled);
      },
  },
};


const _sfc_main$2Y = {};
const Config_default$c = /*#__PURE__*/_export_sfc(_sfc_main$2Y, [['__file',"Config.vue"]]);

/**
 * The Entra object
 */
const Entra = {
  meta: {
    title: "Entra",
    icon: "fas fa-shield-alt",
    description: "Integration med Entra ID",
    endpoint: "/entra",
    config_endpoint: "/configuration/entra",
    labels: {
      single: "Entra",
      multiple: "Entra",
    }
  },
  config: Config$d,
};


const _sfc_main$2X = {};
const Entra_default = /*#__PURE__*/_export_sfc(_sfc_main$2X, [['__file',"Entra.vue"]]);

/**
 * The Limble -> Config object
 */
const Config$c = {
  get: async ( variable ) => {
    return authenticatedRequest(
        "/limble/config?variable=" + variable,
        "GET")
  },
  get_all: async () => {
    return authenticatedRequest(
        "/limble/config",
        "GET")
  },
  set: async ( variable, value ) => {
    return authenticatedRequest(
        "/limble/config",
        "POST",
        {
          variable: variable,
          value: value
        })
  },
  keys: {
    /**
     * The Limble configuration keys
     */
    client_id: {
      get: async () => {
        return Config$c.get("client_id");
      },
      set: async (value) => {
        return Config$c.set("client_id", value);
      },
    },
    client_secret: {
      get: async () => {
        return Config$c.get("client_secret");
      },
      set: async (value) => {
        return Config$c.set("client_secret", value);
      },
    },
    webhooks_enabled: {
      get: async () => {
        return Config$c.get("webhooks_enabled");
      },
      set: async (value) => {
        return Config$c.set("webhooks_enabled", value);
      },
    },
  },
  enabled: {
    get: async () => {
      return Config$c.get("enabled");
    },
    set: async (enabled) => {
      return Config$c.set("enabled", enabled);
    },
  },
};

const _sfc_main$2W = {};
const Config_default$b = /*#__PURE__*/_export_sfc(_sfc_main$2W, [['__file',"Config.vue"]]);

/**
 * The Limble object
 */
const Limble = {
  meta: {
    title: "Limble",
    icon: "fas fa-car",
    description: "Limble",
    endpoint: "/modules/limble",
    config_endpoint: "/configuration/limble",
    labels: {
      single: "limble",
      multiple: "limble"
    }
  },
  config: Config$c,
  functions: {
    testConnection: async () => {
      return SessionUser.superUser.modules.limble.functions.getTasks()
    },
    getTasks: async () => {
      return SessionUser.request(
          "/modules/limble/tasks",
          "GET",
          {}
      )
    },
  },
};

const _sfc_main$2V = {};
const Limble_default = /*#__PURE__*/_export_sfc(_sfc_main$2V, [['__file',"Limble.vue"]]);

/**
 * The OcrSpace -> Config object
 */
const Config$b = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/ocrspace/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/ocrspace/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/ocrspace/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      api_key: {
        get: async () => {
          return Config$b.get("api_key");
        },
        set: async (value) => {
          return Config$b.set("api_key", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$b.get("enabled");
      },
      set: async (enabled) => {
        return Config$b.set("enabled", enabled);
      },
  },
};


const _sfc_main$2U = {};
const Config_default$a = /*#__PURE__*/_export_sfc(_sfc_main$2U, [['__file',"Config.vue"]]);

/**
 * The OcrSpace object
 */
const OcrSpace = {
  meta: {
    title: "OcrSpace",
    icon: "fas fa-file-image",
    description: "OcrSpace",
    endpoint: "/modules/OcrSpace",
    config_endpoint: "/configuration/OcrSpace",
    labels: {
      single: "OcrSpace",
      multiple: "OcrSpace"
    }
  },
  config: Config$b,
  functions: {}
};


const _sfc_main$2T = {};
const OcrSpace_default = /*#__PURE__*/_export_sfc(_sfc_main$2T, [['__file',"OcrSpace.vue"]]);

/**
 * The OpenAI -> Config object
 */
const Config$a = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/openai/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/openai/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/openai/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      api_key: {
        get: async () => {
          return Config$a.get("api_key");
        },
        set: async (value) => {
          return Config$a.set("api_key", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$a.get("enabled");
      },
      set: async (enabled) => {
        return Config$a.set("enabled", enabled);
      },
  },
};


const _sfc_main$2S = {};
const Config_default$9 = /*#__PURE__*/_export_sfc(_sfc_main$2S, [['__file',"Config.vue"]]);

/**
 * The OpenAI object
 */
const OpenAI = {
  meta: {
    title: "OpenAI",
    icon: "fab fa-openai",
    description: "OpenAI",
    endpoint: "/modules/OpenAI",
    config_endpoint: "/configuration/OpenAI",
    labels: {
      single: "OpenAI",
      multiple: "OpenAI"
    }
  },
  config: Config$a,
  functions: {}
};

const _sfc_main$2R = {};
const OpenAI_default = /*#__PURE__*/_export_sfc(_sfc_main$2R, [['__file',"OpenAI.vue"]]);

/**
 * The licenseplaterecognizer -> Config object
 */
const Config$9 = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/licenseplaterecognizer/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/licenseplaterecognizer/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/licenseplaterecognizer/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      api_key: {
        get: async () => {
          return Config$9.get("api_key");
        },
        set: async (value) => {
          return Config$9.set("api_key", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$9.get("enabled");
      },
      set: async (enabled) => {
        return Config$9.set("enabled", enabled);
      },
  },
};


const _sfc_main$2Q = {};
const Config_default$8 = /*#__PURE__*/_export_sfc(_sfc_main$2Q, [['__file',"Config.vue"]]);

/**
 * The LicensePlateRecognizer object
 */
const LicensePlateRecognizer = {
  meta: {
    title: "LicensePlateRecognizer",
    icon: "fas fa-file-image",
    description: "LicensePlateRecognizer",
    endpoint: "/modules/LicensePlateRecognizer",
    config_endpoint: "/configuration/LicensePlateRecognizer",
    labels: {
      single: "LicensePlateRecognizer",
      multiple: "LicensePlateRecognizer"
    }
  },
  config: Config$9,
  functions: {}
};


const _sfc_main$2P = {};
const LicensePlateRecognizer_default = /*#__PURE__*/_export_sfc(_sfc_main$2P, [['__file',"LicensePlateRecognizer.vue"]]);

/**
 * The VirkData -> Config object
 */
const Config$8 = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/virkdata/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/virkdata/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/virkdata/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      monthly_limit: {
        get: async () => {
          return Config$8.get("monthly_limit");
        },
        set: async (value) => {
          return Config$8.set("monthly_limit", value);
        },
      },
      secret_key: {
        get: async () => {
          return Config$8.get("secret_key");
        },
        set: async (value) => {
          return Config$8.set("secret_key", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$8.get("enabled");
      },
      set: async (enabled) => {
        return Config$8.set("enabled", enabled);
      },
  },
};


const _sfc_main$2O = {};
const Config_default$7 = /*#__PURE__*/_export_sfc(_sfc_main$2O, [['__file',"Config.vue"]]);

/**
 * The VirkData object
 */
const VirkData = {
  meta: {
    title: "VirkData",
    icon: "fas fa-building",
    description: "VirkData",
    endpoint: "/modules/virkdata",
    config_endpoint: "/configuration/virkdata",
    labels: {
      single: "virkdata",
      multiple: "virkdata"
    }
  },
  config: Config$8,
  functions: {
    search: async (search) => {
      return authenticatedRequest(
          "/modules/virkdata/search",
          "GET",
          {
            search: search
          })
    },
  }
};


const _sfc_main$2N = {};
const VirkData_default = /*#__PURE__*/_export_sfc(_sfc_main$2N, [['__file',"VirkData.vue"]]);

/**
 * The Shelly -> Config object
 */
const Config$7 = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/shelly/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/shelly/config",
          "GET")
    },
    set: async ( variable, value ) => {
      return authenticatedRequest(
          "/shelly/config",
          "POST",
          {
            variable: variable,
            value: value
          })
    },
    keys: {
      server_url: {
        get: async () => {
          return Config$7.get("server_url");
        },
        set: async (value) => {
          return Config$7.set("server_url", value);
        },
      },
      secret_key: {
        get: async () => {
          return Config$7.get("secret_key");
        },
        set: async (value) => {
          return Config$7.set("secret_key", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$7.get("enabled");
      },
      set: async (enabled) => {
        return Config$7.set("enabled", enabled);
      },
  },
};


const _sfc_main$2M = {};
const Config_default$6 = /*#__PURE__*/_export_sfc(_sfc_main$2M, [['__file',"Config.vue"]]);

/**
 * The Shelly object
 */
const Shelly = {
  meta: {
    title: "Shelly",
    icon: "fas fa-building",
    description: "Shelly",
    endpoint: "/modules/shelly",
    config_endpoint: "/configuration/shelly",
    labels: {
      single: "shelly",
      multiple: "shelly"
    }
  },
  config: Config$7,
  functions: {
    test_connection: async () => {
      return authenticatedRequest(
          "/modules/shelly/test_connection",
          "GET",
          {
          })
    },
  }
};


const _sfc_main$2L = {};
const Shelly_default = /*#__PURE__*/_export_sfc(_sfc_main$2L, [['__file',"Shelly.vue"]]);

const normalizeEntries$1 = (entries) => {
  if (Array.isArray(entries)) {
    return entries;
  }

  if (entries && typeof entries === "object") {
    return Object.values(entries);
  }

  return [];
};

const toConfigPayload$1 = (entries) => {
  const payload = {};
  normalizeEntries$1(entries).forEach((entry) => {
    if (!entry || !entry.variable) {
      return;
    }
    payload[entry.variable] = entry.value;
  });
  return payload;
};

/**
 * The Self Serve -> Config object
 */
const Config$6 = {
    get: async ( variable ) => {
      return authenticatedRequest(
          "/selfserve/config?variable=" + variable,
          "GET")
    },
    get_all: async () => {
      return authenticatedRequest(
          "/selfserve/config",
          "GET").then((response) => {
            const normalizedEntries = normalizeEntries$1(response?.data?.data);
            response.data.data = normalizedEntries;
            response.data.config = toConfigPayload$1(normalizedEntries);
            return response;
          });
    },
    get_config: async () => {
      return Config$6.get_all().then((response) => response?.data?.config || {});
    },
    set_config: async (payload) => {
      return authenticatedRequest(
          "/selfserve/config",
          "POST",
          payload
      );
    },
    set: async ( variable, value ) => {
      const currentConfig = await Config$6.get_config();
      return Config$6.set_config({
        ...currentConfig,
        [variable]: value
      });
    },
    keys: {
      machine_wash_enabled: {
        get: async () => {
          return Config$6.get("machine_wash_enabled");
        },
        set: async (value) => {
          return Config$6.set("machine_wash_enabled", value);
        },
      },
      dynamic_image_size: {
        get: async () => {
          return Config$6.get("dynamic_image_size");
        },
        set: async (value) => {
          return Config$6.set("dynamic_image_size", value);
        },
      },
      minute_product: {
        get: async () => {
          return Config$6.get("minute_product");
        },
        set: async (value) => {
          return Config$6.set("minute_product", value);
        },
      },
    },
    enabled: {
      get: async () => {
        return Config$6.get("enabled");
      },
      set: async (enabled) => {
        return Config$6.set("enabled", enabled);
      },
  },
};


const _sfc_main$2K = {};
const Config_default$5 = /*#__PURE__*/_export_sfc(_sfc_main$2K, [['__file',"Config.vue"]]);

/**
 * The Self Serve object
 */
const SelfServe = {
  meta: {
    title: "SelfServe",
    icon: "fas fa-car",
    description: "SelfServe, som bruges til at hente valutakurser",
    endpoint: "/modules/selfserve",
    config_endpoint: "/configuration/selfserve",
    labels: {
      single: "selfserve",
      multiple: "selfserve"
    }
  },
  config: Config$6,
  functions: {}
};


const _sfc_main$2J = {};
const SelfServe_default = /*#__PURE__*/_export_sfc(_sfc_main$2J, [['__file',"SelfServe.vue"]]);

/**
 * The Bird -> Config object
 */
const Config$5 = {
  get: async (variable) => {
    return authenticatedRequest(
      "/bird/config?variable=" + variable,
      "GET"
    );
  },
  get_all: async () => {
    return authenticatedRequest(
      "/bird/config",
      "GET"
    );
  },
  set: async (variable, value) => {
    return authenticatedRequest(
      "/bird/config",
      "POST",
      {
        variable: variable,
        value: value
      }
    );
  },
  keys: {
    api_key: {
      get: async () => {
        return Config$5.get("api_key");
      },
      set: async (value) => {
        return Config$5.set("api_key", value);
      },
    },
    server_url: {
      get: async () => {
        return Config$5.get("server_url");
      },
      set: async (value) => {
        return Config$5.set("server_url", value);
      },
    },
    workplaceId: {
      get: async () => {
        return Config$5.get("workplaceId");
      },
      set: async (value) => {
        return Config$5.set("workplaceId", value);
      },
    },
    channelId: {
      get: async () => {
        return Config$5.get("channelId");
      },
      set: async (value) => {
        return Config$5.set("channelId", value);
      },
    },
  },
  enabled: {
    get: async () => {
      return Config$5.get("enabled");
    },
    set: async (enabled) => {
      return Config$5.set("enabled", enabled);
    },
  },
};

const _sfc_main$2I = {};
const Config_default$4 = /*#__PURE__*/_export_sfc(_sfc_main$2I, [['__file',"Config.vue"]]);

const withWorkspaceAndChannel = (workspaceId, channelId) => {
  const params = new URLSearchParams({
    workspaceId,
    channelId
  });
  // If the value is null or undefined, it will be converted to the string "null" or "undefined", so we need to remove those parameters
  if (workspaceId === null || workspaceId === undefined) {
    params.delete("workspaceId");
  }
  if (channelId === null || channelId === undefined) {
    params.delete("channelId");
  }

  return `?${params.toString()}`;
};

/**
 * The Bird object
 */
const Bird = {
  meta: {
    title: "Bird",
    icon: "fas fa-phone",
    description: "Bird Voice Calls",
    endpoint: "/bird",
    config_endpoint: "/bird/config",
    labels: {
      single: "bird",
      multiple: "bird"
    }
  },
  config: Config$5,
  functions: {
    createVoiceCall: async (workspaceId, channelId, payload) => {
      return authenticatedRequest(
        "/bird/voice/calls" + withWorkspaceAndChannel(workspaceId, channelId),
        "POST",
        payload
      );
    },
    listVoiceCalls: async (workspaceId, channelId, page = null) => {
      return authenticatedRequest(
        "/bird/voice/calls",
        "GET",
        {
          workspaceId,
          channelId,
          ...(page !== null ? { page } : {})
        }
      );
    },
    getVoiceCall: async (workspaceId, channelId, id) => {
      return authenticatedRequest(
        `/bird/voice/calls/${id}`,
        "GET",
        {
          workspaceId,
          channelId
        }
      );
    },
    hangupVoiceCall: async (workspaceId, channelId, id) => {
      return authenticatedRequest(
        `/bird/voice/calls/${id}/hangup` + withWorkspaceAndChannel(workspaceId, channelId),
        "POST"
      );
    },
    testOutboundVoiceCall: async (workspaceId, channelId, payload = {}) => {
      return authenticatedRequest(
        "/bird/voice/calls/test-outbound" + withWorkspaceAndChannel(workspaceId, channelId),
        "POST",
        payload
      );
    },
    listNumbers: async (page = null) => {
      return authenticatedRequest(
        "/bird/numbers",
        "GET",
        {
          ...(page !== null ? { page } : {})
        }
      );
    },
    getNumber: async (id) => {
      return authenticatedRequest(
        `/bird/numbers/${id}`,
        "GET"
      );
    },
    deleteNumber: async (id) => {
      return authenticatedRequest(
        `/bird/numbers/${id}`,
        "DELETE"
      );
    },
    createFlashCall: async (workspaceId, channelId, payload) => {
      return authenticatedRequest(
        "/bird/voice/flash-calls" + withWorkspaceAndChannel(workspaceId, channelId),
        "POST",
        payload
      );
    },
    listFlashCalls: async (workspaceId, channelId, page = null) => {
      return authenticatedRequest(
        "/bird/voice/flash-calls",
        "GET",
        {
          workspaceId,
          channelId,
          ...(page !== null ? { page } : {})
        }
      );
    },
    getFlashCall: async (workspaceId, channelId, id) => {
      return authenticatedRequest(
        `/bird/voice/flash-calls/${id}`,
        "GET",
        {
          workspaceId,
          channelId
        }
      );
    },
    endFlashCall: async (workspaceId, channelId, id, payload = {}) => {
      return authenticatedRequest(
        `/bird/voice/flash-calls/${id}` + withWorkspaceAndChannel(workspaceId, channelId),
        "POST",
        payload
      );
    },
    endFlashCallByNumbers: async (workspaceId, channelId, payload) => {
      return authenticatedRequest(
        "/bird/voice/flash-calls/end" + withWorkspaceAndChannel(workspaceId, channelId),
        "POST",
        payload
      );
    },
  }
};


const _sfc_main$2H = {};
const Bird_default = /*#__PURE__*/_export_sfc(_sfc_main$2H, [['__file',"Bird.vue"]]);

const normalizeEntries = (entries) => {
  if (Array.isArray(entries)) {
    return entries;
  }

  if (entries && typeof entries === "object") {
    return Object.values(entries);
  }

  return [];
};

const SENSITIVE_WRITE_ONLY_KEYS = new Set(["broker_shared_secret"]);

const toConfigPayload = (entries) => {
  const payload = {};
  normalizeEntries(entries).forEach((entry) => {
    if (!entry || !entry.variable) {
      return;
    }
    payload[entry.variable] = SENSITIVE_WRITE_ONLY_KEYS.has(entry.variable) ? "" : entry.value;
  });
  return payload;
};

const Config$4 = {
  get: async (variable) => getEdgeGatewayModuleConfig(variable),
  get_all: async () =>
    getEdgeGatewayModuleConfig().then((response) => {
      const entries = normalizeEntries(response?.data?.data || []);
      response.data.data = entries;
      response.data.config = toConfigPayload(entries);
      return response;
    }),
  get_config: async () => Config$4.get_all().then((response) => response?.data?.config || {}),
  set_config: async (payload) => setEdgeGatewayModuleConfig(payload),
  test_broker: async (payload) => testEdgeGatewayBrokerConfig(payload),
  set: async (variable, value) => {
    const currentConfig = await Config$4.get_config();
    SENSITIVE_WRITE_ONLY_KEYS.forEach((key) => {
      if (key !== variable) {
        delete currentConfig[key];
      }
    });
    return Config$4.set_config({
      ...currentConfig,
      [variable]: value,
    });
  },
  keys: {
    enabled: {
      get: async () => Config$4.get("enabled"),
      set: async (value) => Config$4.set("enabled", value),
    },
    default_release_channel: {
      get: async () => Config$4.get("default_release_channel"),
      set: async (value) => Config$4.set("default_release_channel", value),
    },
    default_update_window: {
      get: async () => Config$4.get("default_update_window"),
      set: async (value) => Config$4.set("default_update_window", value),
    },
    broker_url: {
      get: async () => Config$4.get("broker_url"),
      set: async (value) => Config$4.set("broker_url", value),
    },
    public_broker_url: {
      get: async () => Config$4.get("public_broker_url"),
      set: async (value) => Config$4.set("public_broker_url", value),
    },
    broker_auth_mode: {
      get: async () => Config$4.get("broker_auth_mode"),
      set: async (value) => Config$4.set("broker_auth_mode", value),
    },
    broker_shared_secret: {
      set: async (value) => Config$4.set("broker_shared_secret", value),
    },
  },
};

const _sfc_main$2G = {};
const Config_default$3 = /*#__PURE__*/_export_sfc(_sfc_main$2G, [['__file',"Config.vue"]]);

const EdgeGateway = {
  meta: {
    title: "Edge Gateway",
    icon: "fas fa-network-wired",
    description: "Containerized edge gateway control plane and fleet management.",
    endpoint: "/modules/edge-gateways",
    config_endpoint: "/configuration/edgegateway",
    labels: {
      single: "edge gateway",
      multiple: "edge gateways",
    },
  },
  config: Config$4,
  functions: {},
};

const _sfc_main$2F = {};
const EdgeGateway_default = /*#__PURE__*/_export_sfc(_sfc_main$2F, [['__file',"EdgeGateway.vue"]]);

const Config$3 = {
  get: async (variable) => {
    return authenticatedRequest(
      "/failover/config?variable=" + variable,
      "GET"
    );
  },
  get_all: async () => {
    return authenticatedRequest(
      "/failover/config",
      "GET"
    );
  },
  set: async (variable, value) => {
    return authenticatedRequest(
      "/failover/config",
      "POST",
      {
        variable: variable,
        value: value,
      }
    );
  },
  enabled: {
    get: async () => Config$3.get("enabled"),
    set: async (enabled) => Config$3.set("enabled", enabled),
  },
  database_enabled: {
    get: async () => Config$3.get("database_enabled"),
    set: async (enabled) => Config$3.set("database_enabled", enabled),
  },
  redis_enabled: {
    get: async () => Config$3.get("redis_enabled"),
    set: async (enabled) => Config$3.set("redis_enabled", enabled),
  },
  minio_enabled: {
    get: async () => Config$3.get("minio_enabled"),
    set: async (enabled) => Config$3.set("minio_enabled", enabled),
  },
  max_status_age_seconds: {
    get: async () => Config$3.get("max_status_age_seconds"),
    set: async (seconds) => Config$3.set("max_status_age_seconds", seconds),
  },
};

const _sfc_main$2E = {};
const Config_default$2 = /*#__PURE__*/_export_sfc(_sfc_main$2E, [['__file',"Config.vue"]]);

const Failover = {
  meta: {
    title: "Failover",
    icon: "fas fa-exchange-alt",
    description: "Automatic replica failover",
    endpoint: "/modules/failover",
    config_endpoint: "/configuration/failover",
    labels: {
      single: "failover",
      multiple: "failover",
    },
  },
  config: Config$3,
};

const _sfc_main$2D = {};
const Failover_default = /*#__PURE__*/_export_sfc(_sfc_main$2D, [['__file',"Failover.vue"]]);

const RELEASE_MANAGER_CONTROL_API_STORAGE_KEY = "release_manager_control_api_url";
const RELEASE_MANAGER_LAST_WORKING_CONTROL_API_STORAGE_KEY = "release_manager_last_working_control_api_url";

const normalizeApiUrl = (value) => {
  const url = String(value || "")
    .trim()
    .replace(/\/+$/, "");
  if (url.startsWith("/") && !url.startsWith("//")) {
    return url || "/";
  }
  if (!/^https?:\/\//i.test(url)) {
    return "";
  }
  return url;
};

const isTrustedApiUrl = (value) => {
  const url = normalizeApiUrl(value);
  return Boolean(url && isTrustedReleaseUrl(url));
};

const isLocalApiUrl = (value) => {
  const url = normalizeApiUrl(value);
  if (!isTrustedApiUrl(url)) {
    return false;
  }
  if (url.startsWith("/") && !url.startsWith("//")) {
    return true;
  }
  try {
    const parsed = new URL(url);
    return ["localhost", "127.0.0.1", "::1"].includes(parsed.hostname);
  } catch {
    return false;
  }
};

const browserStorage$1 = (name) => {
  if (typeof window === "undefined") {
    return null;
  }
  try {
    return window[name] || null;
  } catch {
    return null;
  }
};

const getSelectedCustomerNumber$1 = () => {
  const stored = browserStorage$1("localStorage")?.getItem("selected_customer_number");
  return stored ? parseInt(stored, 10) : null;
};

const uniqueUrls = (urls) => {
  const seen = new Set();
  return urls
    .map((url) => normalizeApiUrl(url))
    .filter((url) => {
      if (!url || seen.has(url)) {
        return false;
      }
      seen.add(url);
      return true;
    });
};

const releaseManagerLocalStorage = () => browserStorage$1("localStorage");
const releaseManagerSessionStorage = () => browserStorage$1("sessionStorage");

const releaseManagerControlApiCandidates = () => {
  const runtimeApiBaseUrl = getReleaseRuntimeApiBaseUrl();
  const lastWorkingUrl = releaseManagerSessionStorage()?.getItem(RELEASE_MANAGER_LAST_WORKING_CONTROL_API_STORAGE_KEY);
  const storedUrl = releaseManagerLocalStorage()?.getItem(RELEASE_MANAGER_CONTROL_API_STORAGE_KEY);
  const localSource = String(releaseRuntimeState.source || "").toLowerCase() === "local";
  const localCandidates = uniqueUrls([
    runtimeApiBaseUrl,
    isLocalApiUrl(lastWorkingUrl) ? lastWorkingUrl : "",
    isLocalApiUrl(storedUrl) ? storedUrl : "",
    RELEASE_MANAGER_CONTROL_API_URL,
    API_URL,
  ]).filter(isLocalApiUrl);

  if (localSource && localCandidates.length > 0) {
    return localCandidates;
  }

  const deploymentConfigUrls = [RELEASE_MANAGER_CONTROL_API_URL, API_URL].filter((url) => !isLocalApiUrl(url));
  return uniqueUrls([
    getReleaseRuntimeApiBaseUrl(),
    lastWorkingUrl,
    storedUrl,
    ...deploymentConfigUrls,
    ...RELEASE_MANAGER_CONTROL_API_FALLBACK_URLS,
  ]).filter(isTrustedApiUrl);
};

const getReleaseManagerControlApiUrl = () => releaseManagerControlApiCandidates()[0] || API_URL;

const setReleaseManagerControlApiUrl = (url) => {
  const normalized = normalizeApiUrl(url);
  if (!isTrustedApiUrl(normalized)) {
    return "";
  }
  releaseManagerLocalStorage()?.setItem(RELEASE_MANAGER_CONTROL_API_STORAGE_KEY, normalized);
  releaseManagerSessionStorage()?.setItem(RELEASE_MANAGER_LAST_WORKING_CONTROL_API_STORAGE_KEY, normalized);
  return normalized;
};

const clearReleaseManagerControlApiUrl = () => {
  releaseManagerLocalStorage()?.removeItem(RELEASE_MANAGER_CONTROL_API_STORAGE_KEY);
  releaseManagerSessionStorage()?.removeItem(RELEASE_MANAGER_LAST_WORKING_CONTROL_API_STORAGE_KEY);
};

const rememberWorkingControlApiUrl = (url) => {
  const normalized = normalizeApiUrl(url);
  if (isTrustedApiUrl(normalized)) {
    releaseManagerSessionStorage()?.setItem(RELEASE_MANAGER_LAST_WORKING_CONTROL_API_STORAGE_KEY, normalized);
  }
};

const shouldTryNextControlApi = (error, method) => {
  const status = Number(error?.response?.status || 0);
  return (
    status === 0 ||
    (method === "GET" && status === 404) ||
    status === 405 ||
    status === 501 ||
    error?.code === "ERR_NETWORK"
  );
};

const buildHeaders = () => {
  const headers = {};
  const token = releaseManagerLocalStorage()?.getItem("token");
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  const isSubuser = releaseManagerLocalStorage()?.getItem("is_subuser") === "true";
  const selectedCustomerNumber = getSelectedCustomerNumber$1();
  if (isSubuser && selectedCustomerNumber) {
    headers["X-Customer-Number"] = selectedCustomerNumber;
  }

  return headers;
};

const requestReleaseManager = (url, method, data = {}) => {
  const candidates = releaseManagerControlApiCandidates();
  const headers = buildHeaders();

  return enqueueRequest(
    async () => {
      let lastError = null;
      for (const baseUrl of candidates) {
        try {
          const response = await axios({
            method,
            url: `${baseUrl}${url}`,
            ...(method === "GET" ? { params: data } : { data }),
            __skipRequestQueue: true,
            __skipReleaseApiRewrite: true,
            headers,
          });
          rememberWorkingControlApiUrl(baseUrl);
          return response;
        } catch (error) {
          lastError = error;
          if (!shouldTryNextControlApi(error, method)) {
            throw error;
          }
        }
      }
      throw lastError;
    },
    {
      method,
      url: `${candidates[0] || API_URL}${url}`,
      requestData: {
        params: method === "GET" ? data : null,
        data: method === "GET" ? null : data,
        headers,
      },
      shouldRetry: () => false,
    }
  );
};

const getReleaseSummary = () => requestReleaseManager("/superuser/releases", "GET", {});

const getReleaseConfig = () => requestReleaseManager("/superuser/releases/config", "GET", {});

const updateReleaseConfig = (payload) => requestReleaseManager("/superuser/releases/config", "POST", payload);

const listReleaseChannels = () => requestReleaseManager("/superuser/releases/channels", "GET", {});

const createReleaseChannel = (payload) => requestReleaseManager("/superuser/releases/channels", "POST", payload);

const updateReleaseChannel = (id, payload) =>
  requestReleaseManager(`/superuser/releases/channels/${id}`, "PATCH", payload);

const rollbackReleaseChannel = (id) =>
  requestReleaseManager(`/superuser/releases/channels/${id}/rollback`, "POST", {});

const syncReleaseChannel = (id) =>
  requestReleaseManager(`/superuser/releases/channels/${id}/sync`, "POST", {});

const setReleaseChannelBundle = (id, payload) =>
  requestReleaseManager(`/superuser/releases/channels/${id}/bundle`, "POST", payload);

const listReleaseOperations = (params = {}) =>
  requestReleaseManager("/superuser/releases/operations", "GET", params);

const getReleaseOperation = (id) =>
  requestReleaseManager(`/superuser/releases/operations/${id}`, "GET", {});

const runReleaseTest = (payload = {}) =>
  requestReleaseManager("/superuser/releases/test-runs", "POST", payload);

const previewReleaseCoolifyCleanup = (payload = {}) =>
  requestReleaseManager("/superuser/releases/coolify-cleanup/preview", "POST", payload);

const applyReleaseCoolifyCleanup = (payload = {}) =>
  requestReleaseManager("/superuser/releases/coolify-cleanup/apply", "POST", payload);

const listReleaseAssignments = () => requestReleaseManager("/superuser/releases/assignments", "GET", {});

const searchReleaseAssignmentSubjects = (params = {}) =>
  requestReleaseManager("/superuser/releases/assignment-subjects", "GET", params);

const createReleaseAssignment = (payload) =>
  requestReleaseManager("/superuser/releases/assignments", "POST", payload);

const deleteReleaseAssignment = (id) =>
  requestReleaseManager(`/superuser/releases/assignments/${id}`, "DELETE", {});

const listReleaseDeploymentTargets = () => requestReleaseManager("/superuser/releases/targets", "GET", {});

const saveReleaseDeploymentTarget = (payload) =>
  requestReleaseManager("/superuser/releases/targets", "POST", payload);

const deleteReleaseDeploymentTarget = (id) =>
  requestReleaseManager(`/superuser/releases/targets/${id}`, "DELETE", {});

const listReleaseServiceSets = () => requestReleaseManager("/superuser/releases/service-sets", "GET", {});

const createReleaseServiceSet = (payload) =>
  requestReleaseManager("/superuser/releases/service-sets", "POST", payload);

const deleteReleaseServiceSet = (id) =>
  requestReleaseManager(`/superuser/releases/service-sets/${id}`, "DELETE", {});

const completeReleaseServiceSetIsolatedDataServices = (id, payload = {}) =>
  requestReleaseManager(`/superuser/releases/service-sets/${id}/isolated-data-services`, "POST", payload);

const listReleaseBundles = (limit = 50) =>
  requestReleaseManager("/superuser/releases/bundles", "GET", { limit });

const createReleaseBundle = (payload) =>
  requestReleaseManager("/superuser/releases/bundles", "POST", payload);

const deployReleaseBundle = (id) =>
  requestReleaseManager(`/superuser/releases/bundles/${id}/deploy`, "POST", {});

const promoteReleaseBundle = (id) =>
  requestReleaseManager(`/superuser/releases/bundles/${id}/promote`, "POST", {});

const listReleaseGithubRepositories = (params = {}) =>
  requestReleaseManager("/superuser/releases/github/repositories", "GET", params);

const listReleaseGithubBranches = (repository) =>
  requestReleaseManager("/superuser/releases/github/branches", "GET", { repository });

const listReleaseGithubCommits = ({ repository, branch, query = "", commit_sha = "" } = {}) =>
  requestReleaseManager("/superuser/releases/github/commits", "GET", { repository, branch, query, commit_sha });

const testReleaseGithubAccess = (payload) =>
  requestReleaseManager("/superuser/releases/github/test", "POST", payload);

const listReleaseDeployments = (limit = 50) =>
  requestReleaseManager("/superuser/releases/deployments", "GET", { limit });

const startReleaseDeployment = (payload) =>
  requestReleaseManager("/superuser/releases/deployments", "POST", payload);

const promoteReleaseDeployment = (id) =>
  requestReleaseManager(`/superuser/releases/deployments/${id}/promote`, "POST", {});

const runReleaseIssueAction = (payload) =>
  requestReleaseManager("/superuser/releases/issues/actions", "POST", payload);

const setReleaseReplayTarget = (payload) =>
  requestReleaseManager("/superuser/releases/replay-targets", "POST", payload);

const searchReleaseTimeline = (filters = {}) =>
  requestReleaseManager("/superuser/releases/timeline", "GET", filters);

const listReleaseTimelineSessions = (filters = {}) =>
  requestReleaseManager("/superuser/releases/timeline/sessions", "GET", filters);

const getReleaseTimelineSession = (traceId) =>
  requestReleaseManager(`/superuser/releases/timeline/sessions/${encodeURIComponent(traceId)}`, "GET", {});

const getCoolifySummary = () =>
  requestReleaseManager("/superuser/coolify", "GET", {});

const getCoolifyLoadBalancer = () =>
  requestReleaseManager("/superuser/coolify/load-balancer", "GET", {});

const reconcileCoolifyLoadBalancer = (payload) =>
  requestReleaseManager("/superuser/coolify/load-balancer/reconcile", "POST", payload);

const deployCoolifyGatewayRoutes = (payload) =>
  requestReleaseManager("/superuser/coolify/load-balancer/routes/deploy", "POST", payload);

const deployCoolifyGatewayApiCode = (payload) =>
  requestReleaseManager("/superuser/coolify/load-balancer/api/deploy", "POST", payload);

const listCoolifyGateways = () =>
  requestReleaseManager("/superuser/coolify/gateways", "GET", {});

const saveCoolifyGateway = (payload) =>
  requestReleaseManager("/superuser/coolify/gateways", "POST", payload);

const testCoolifyGateway = (id) =>
  requestReleaseManager(`/superuser/coolify/gateways/${id}/test`, "POST", {});

const createCoolifyInstance = (payload) =>
  requestReleaseManager("/superuser/coolify/instances", "POST", payload);

const testCoolifyInstance = (id) =>
  requestReleaseManager(`/superuser/coolify/instances/${id}/test`, "POST", {});

const discoverCoolifyPlacement = (id) =>
  requestReleaseManager(`/superuser/coolify/instances/${id}/placement`, "GET", {});

const listCoolifyTargets = ({ kind = null } = {}) =>
  requestReleaseManager("/superuser/coolify/targets", "GET", kind ? { kind } : {});

const createCoolifyTarget = (payload) =>
  requestReleaseManager("/superuser/coolify/targets", "POST", payload);

const reconcileCoolifyTarget = (id) =>
  requestReleaseManager(`/superuser/coolify/targets/${id}/reconcile`, "POST", {});

const deployCoolifyTarget = (id) =>
  requestReleaseManager(`/superuser/coolify/targets/${id}/deploy`, "POST", {});

const restartCoolifyTarget = (id) =>
  requestReleaseManager(`/superuser/coolify/targets/${id}/restart`, "POST", {});

const failoverCoolifyTarget = (id) =>
  requestReleaseManager(`/superuser/coolify/targets/${id}/failover`, "POST", {});

const deleteCoolifyTarget = (id, payload) =>
  requestReleaseManager(`/superuser/coolify/targets/${id}`, "DELETE", payload);

const getCoolifyConfig = (variable = null) =>
  requestReleaseManager("/coolify/config", "GET", variable ? { variable } : {});

const setCoolifyConfig = (payload) =>
  requestReleaseManager("/coolify/config", "POST", payload);

const Config$2 = {
  get: (variable) => getCoolifyConfig(variable),
  get_all: () => getCoolifyConfig(),
  set: (payload) => setCoolifyConfig(payload),
  enabled: {
    get: () => getCoolifyConfig(),
    set: (value) => setCoolifyConfig({ variable: "enabled", value }),
  },
};

const _sfc_main$2C = {};
const Config_default$1 = /*#__PURE__*/_export_sfc(_sfc_main$2C, [['__file',"Config.vue"]]);

const Coolify = {
  meta: {
    title: "Coolify",
    description: "Managed replicated infrastructure",
    endpoint: "/superuser/coolify",
    config_endpoint: "/configuration/coolify",
    labels: {
      single: "Coolify",
      multiple: "Coolify",
    },
    icon: "fas fa-server",
  },
  get config() {
    return Config$2;
  },
};

const _sfc_main$2B = {};
const Coolify_default = /*#__PURE__*/_export_sfc(_sfc_main$2B, [['__file',"Coolify.vue"]]);

const ReleaseManager = {
  meta: {
    title: "Release Manager",
    description: "Gradual API and Front-End releases",
    endpoint: "/superuser/releases",
    config_endpoint: "/configuration/releases",
    labels: {
      single: "Release Manager",
      multiple: "Release Manager",
    },
    icon: "fas fa-code-branch",
  },
};

const _sfc_main$2A = {};
const ReleaseManager_default = /*#__PURE__*/_export_sfc(_sfc_main$2A, [['__file',"ReleaseManager.vue"]]);

/**
 * The Slack -> Config object
 */
const Config$1 = {
  get: async (variable) => {
    return authenticatedRequest("/slack/config?variable=" + variable, "GET");
  },
  get_all: async () => {
    return authenticatedRequest("/slack/config", "GET");
  },
  set: async (variable, value) => {
    return authenticatedRequest("/slack/config", "POST", {
      variable: variable,
      value: value,
    });
  },
  test_customer_registration_webhook: async () => {
    return authenticatedRequest("/slack/config/test", "POST", {});
  },
  test_internal_department_goal_progress_webhook: async () => {
    return authenticatedRequest("/slack/config/internal-department-goal-progress/test", "POST", {});
  },
  get_internal_department_goal_progress: async () => {
    return authenticatedRequest("/slack/config/internal-department-goal-progress", "GET");
  },
  set_internal_department_goal_progress: async (webhookUrl, departmentIds) => {
    return authenticatedRequest("/slack/config/internal-department-goal-progress", "POST", {
      internal_department_goal_progress_webhook_url: webhookUrl,
      internal_department_ids: departmentIds,
    });
  },
  keys: {
    customer_registration_webhook_url: {
      get: async () => {
        return Config$1.get("customer_registration_webhook_url");
      },
      set: async (value) => {
        return Config$1.set("customer_registration_webhook_url", value);
      },
    },
    internal_department_goal_progress_webhook_url: {
      get: async () => {
        return Config$1.get("internal_department_goal_progress_webhook_url");
      },
      set: async (value) => {
        return Config$1.set("internal_department_goal_progress_webhook_url", value);
      },
    },
    internal_department_ids: {
      get: async () => {
        return Config$1.get("internal_department_ids");
      },
      set: async (value) => {
        return Config$1.set("internal_department_ids", value);
      },
    },
  },
};

const _sfc_main$2z = {};
const Config_default = /*#__PURE__*/_export_sfc(_sfc_main$2z, [['__file',"Config.vue"]]);

/**
 * The Slack object
 */
const Slack = {
  meta: {
    title: "Slack",
    icon: "fab fa-slack",
    description: "Slack notifications",
    endpoint: "/slack/config",
    config_endpoint: "/configuration/slack",
    labels: {
      single: "slack",
      multiple: "slack",
    },
  },
  config: Config$1,
};

const _sfc_main$2y = {};
const Slack_default = /*#__PURE__*/_export_sfc(_sfc_main$2y, [['__file',"Slack.vue"]]);

let qrCodeModulePromise$1;

const loadQRCodeModule$1 = async () => {
  if (!qrCodeModulePromise$1) {
    qrCodeModulePromise$1 = __vitePreload(() => import('./browser-CIlJ6MKH.js').then(n => n.b),true              ?[]:void 0);
  }

  return qrCodeModulePromise$1;
};

/**
 * The superuser object
 */
const SuperUserObject = {
  system: {
    get database() {
      return DatabaseSystemObject;
    },
    get redis() {
      return RedisSystemObject;
    },
    get minio() {
      return MinioSystemObject;
    },
  },
  modules: {
    get economic() {
      return Economic;
    },
    get reCAPTCHA() {
      return reCAPTCHA$1;
    },
    get email() {
      return Email;
    },
    get backups() {
      return Backups;
    },
    get motorapi() {
      return MotorAPI;
    },
    get stripe() {
      return Stripe;
    },
    get fxratesapi() {
      return FXRatesAPI;
    },
    get weatherapi() {
      return WeatherAPI;
    },
    get workfeed() {
      return Workfeed;
    },
    get gatewayapi() {
      return GatewayAPI;
    },
    get xlvask() {
      return XLVask;
    },
    get entra() {
      return Entra;
    },
    get limble() {
      return Limble;
    },
    get ocrspace() {
      return OcrSpace;
    },
    get openai() {
      return OpenAI;
    },
    get licenseplaterecognizer() {
      return LicensePlateRecognizer;
    },
    get virkdata() {
      return VirkData;
    },
    get shelly() {
      return Shelly;
    },
    get selfserve() {
      return SelfServe;
    },
    get bird() {
      return Bird;
    },
    get edgegateway() {
      return EdgeGateway;
    },
    get failover() {
      return Failover;
    },
    get coolify() {
      return Coolify;
    },
    get releasemanager() {
      return ReleaseManager;
    },
    get slack() {
      return Slack;
    },
  },
  /** Intimidate a user */
  intimidate: {
    /**
     * Get an impersonation (session) token for a user
     * @param userId
     * @returns {Promise<string>} The impersonation token
     */
    getImpersonationToken: async (userId) => {
      return await authenticatedRequest("/su/intimidate", "POST", { user_id: userId })
        .then((response) => {
          // Return the token
          return response.data.data.token;
        })
        .catch((error) => {
          parseError(error, "auth");
        });
    },
    /**
     * Intimidate a user
     * @param userId
     * @returns {Promise<void>}
     */
    intimidateUser: async (userId) => {
      return await authenticatedRequest("/su/intimidate", "POST", { user_id: userId })
        .then((response) => {
          // Save the current token, so we can restore it after the user has been intimidated
          const currentToken = localStorage.getItem("token");
          localStorage.setItem("superuser_token", currentToken);
          // Set the token in the local storage
          clearEdgeGatewayWorkspaceCache();
          localStorage.setItem("token", response.data.data.token);
          // Redirect the user to the dashboard
          window.location = "/";
        })
        .catch((error) => {
          parseError(error, "auth");
        });
    },
    /**
     * Can the current superuser intimidate another superuser?
     * @returns {boolean}
     */
    canImpersonateAdmin: () => {
      // TODO: Implement this function
      return true;
    },
    /**
     * Show a QR code for logging in as a user
     * @param link
     * @returns {Promise<string>} The QR code URL
     */
    showImpersonationQRCode: async (link) => {
      const { toDataURL } = await loadQRCodeModule$1();
      return {
        value: await toDataURL(link),
      };
    },
    /**
     * Go back from intimidating a user
     */
    goBack: () => {
      // Get the superuser token
      const superuserToken = localStorage.getItem("superuser_token");
      // Set the token in the local storage
      clearEdgeGatewayWorkspaceCache();
      localStorage.setItem("token", superuserToken);
      // Clear the superuser token
      localStorage.removeItem("superuser_token");
      // Redirect the user to the dashboard
      window.location = "/";
    },
    /**
     * Check if the superuser is currently intimidating a user
     * @returns {boolean}
     */
    isIntimidated: () => {
      return localStorage.getItem("superuser_token") !== null;
    },
  },
  get cron() {
    return Cron;
  },
};

const _sfc_main$2x = {};
const superUserObject = /*#__PURE__*/_export_sfc(_sfc_main$2x, [['__file',"superUserObject.vue"]]);

const code = {
  getCode: async (customer_number) => {
    return await authenticatedRequest("/admin/customer/code?customer_number=" + customer_number, "GET")
      .then((response) => {
        return response.data.data.code;
      })
      .catch((error) => {
        parseError(error, "auth");
        console.error(error);
      });
  },
};

const _sfc_main$2w = {};
const codes = /*#__PURE__*/_export_sfc(_sfc_main$2w, [['__file',"codes.vue"]]);

/**
 * Booking object
 */

const booking_object = {
  id: null,
  customer_number: null,
  wash_type: null,
  contact_email: null,
  reference_number: null,
  regNrTraekker: null,
  regNrTrailer: null,
  washCertificateEmail: null,
  date: null,
  department: null,
  pickup_bool: null,
  notes: null,
  washCertificateStatus: null,
  washCertificateUrl: null,
  status: null,
  created_at: null,
  constructor: function (booking = {}) {
    this.id = booking.id;
    this.customer_number = booking.customer_number;
    this.wash_type = booking.wash_type;
    this.contact_email = booking.contact_email;
    this.reference_number = booking.reference_number;
    this.regNrTraekker = booking.regNrTraekker;
    this.regNrTrailer = booking.regNrTrailer;
    this.washCertificateEmail = booking.washCertificateEmail;
    this.date = booking.date;
    this.department = booking.department;
    this.pickup_bool = booking.pickup_bool;
    this.notes = booking.notes;
    this.washCertificateStatus = booking.washCertificateStatus;
    this.washCertificateUrl = booking.washCertificateUrl;
    this.status = booking.status;
    this.created_at = booking.created_at;
    return this;
  },
};

const _sfc_main$2v = {};
const booking_object_default = /*#__PURE__*/_export_sfc(_sfc_main$2v, [['__file',"booking_object.vue"]]);

/**
 * The statistics object
 */
const statistics = {
  query: {
    start: ref(null),
    end: ref(null),
    set: {
      start: (start_date) => {
        statistics.query.start.value = start_date;
      },
      end: (end_date) => {
        statistics.query.end.value = end_date;
      }
    },
    get: {
      start: () => {
        return statistics.query.start.value;
      },
      end: () => {
        return statistics.query.end.value;
      }
    }
  },
  requests: {
    get_query: async (uri) => {
      // Get the response from the server
      const response = await authenticatedRequest(
          uri + '?start_date=' + statistics.query.start.value + '&end_date=' + statistics.query.end.value,
          'GET',
          null
      );
      if (response.status === 200) {
        // return the response
        return response;
      } else {
        return null;
      }
    },
  },
  data: {
    labels: [],
    datasets: []
  },
  labels: ref([]),
  datasets: ref([]),
  get: {
    labels: () => {
      return statistics.labels.value;
    },
    datasets: () => {
      return statistics.datasets.value;
    }
  },
  set: {
    labels: (labels) => {
      statistics.labels.value = labels;
    },
    datasets: (datasets) => {
      statistics.datasets.value = datasets;
    }
  },
  current_view: ref('bookings_new'),
  views: {
    bookings_new: {
      name: 'New bookings',
      description: 'The number of new bookings',
      uri: '/statistics/bookings/new',
      id: 'bookings_new'
    },
    orders_new: {
      name: 'New orders',
      description: 'The number of new orders',
      uri: '/statistics/orders/new',
      id: 'orders_new'
    },
    economic_totals: {
      name: 'Economic totals',
      description: 'The economic totals',
      uri: '/statistics/economic/totals',
      id: 'economic_totals'
    },
    economic_department_total_sent: {
      name: 'Fakturaer sendt',
      description: 'The total amount invoiced',
      uri: '/statistics/economic/totals/department_sent_invoice_totals',
      id: 'economic_department_total_sent'
    },
    economic_department_invoices_drafts: {
      name: 'Facturaer udkast',
      description: 'The total amount of drafts invoices',
      uri: '/statistics/economic/totals/department_draft_invoice_totals',
      id: 'economic_department_invoices_drafts'
    },
  },
  set_view: (view) => {
    console.log('Setting view to: ' + view);
    statistics.current_view.value = view;
    statistics.fetch_view();
  },
  fetch_view: () => {
    // Get the response from the server
    statistics.requests.get_query(statistics.views[statistics.current_view.value].uri).then((response) => {
      if (response.status === 200) {
        // Set the response to the object
        statistics.datasets.value = response.data.data.datasets;
        statistics.labels.value = response.data.data.labels;
        return response.data.data;
      } else {
        return null;
      }
    });
  },
  set_time: (start_date, end_date) => {
    // Convert the time to the correct format
    statistics.query.start.value = start_date;
    statistics.query.end.value = end_date;
  }
};

// Watch the query
watch(statistics.query.get.start, (newVal) => {
  console.log('Start date changed');
  console.log(newVal);
});

watch(statistics.query.get.end, (newVal,) => {
  console.log('End date changed');
  console.log(newVal);
  // Get the new bookings
  statistics.fetch_view();
});

const _sfc_main$2u = {};
const Statistics = /*#__PURE__*/_export_sfc(_sfc_main$2u, [['__file',"Statistics.vue"]]);

/**
 * The plates object
 */
const plates = {
  get_order_history: async (plate) => {
    return authenticatedRequest(
        "/department/license-plate/lookup?plate=" + plate,
        "GET")
        .then((response) => {
          return response.data.data;
        })
        .catch((error) => {
          console.error(error);
        });
  },
  search_customer_plates: async (customer_number, plate, column = 'reg_1') => {
    return authenticatedRequest(
        "/department/license-plate/customer-lookup?customer_number=" + parseInt(customer_number) + "&plate=" + plate + "&column=" + column,
        "GET")
        .then((response) => {
          return response.data.data;
        })
        .catch((error) => {
          console.error(error);
        });
  },
  /**
   * Parse the motorapi string
   * This is used to decode the Unicode characters like u00f8 to ø
   * @param string The string to parse
   * @returns {*}
   */
  parse_motorapi_string: (string) => {
    {
      // Check if the string contains u00, if so add a backslash
      if (string.includes('u00')) {
        string = string.replace(/u00/g, '\\u00');
      }
      // unicode decode
      return string.replace(/\\u[\dA-F]{4}/gi,
          (match) => String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16)));
    }
  }
};

const _sfc_main$2t = {};
const Plates = /*#__PURE__*/_export_sfc(_sfc_main$2t, [['__file',"Plates.vue"]]);

const ECONOMIC_QUEUE_STATUS = Object.freeze({
  QUEUED: "QUEUED",
  PROCESSING: "PROCESSING",
  COMPLETED: "COMPLETED",
  FAILED: "FAILED",
});

const DEFAULT_ECONOMIC_QUEUE_POLL_INTERVAL_MS = 2000;
const ECONOMIC_QUEUE_MONITOR_ACTIVE_POLL_INTERVAL_MS = 4000;
const ECONOMIC_QUEUE_MONITOR_IDLE_POLL_INTERVAL_MS = 30000;

const ACTIVE_STATUSES = new Set([
  ECONOMIC_QUEUE_STATUS.QUEUED,
  ECONOMIC_QUEUE_STATUS.PROCESSING,
]);

const TERMINAL_STATUSES = new Set([
  ECONOMIC_QUEUE_STATUS.COMPLETED,
  ECONOMIC_QUEUE_STATUS.FAILED,
]);

const isEconomicQueueStatusActive = (status) => ACTIVE_STATUSES.has(status);
const isEconomicQueueStatusTerminal = (status) => TERMINAL_STATUSES.has(status);

const parsePositiveInteger = (value) => {
  const parsed = Number.parseInt(String(value), 10);
  return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
};

const parseNonNegativeInteger = (value) => {
  const parsed = Number.parseInt(String(value), 10);
  return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
};

const firstPositiveInteger = (...values) => {
  for (const value of values) {
    const parsed = parsePositiveInteger(value);
    if (parsed) {
      return parsed;
    }
  }

  return null;
};

const getEconomicApiErrorMessage = (error, fallback = "Request failed.") => {
  if (typeof error === "string" && error.trim() !== "") {
    return error;
  }

  const response = error?.response;
  const responseData = response?.data;

  if (typeof responseData?.data?.message === "string" && responseData.data.message.trim() !== "") {
    return responseData.data.message;
  }

  if (typeof responseData?.message === "string" && responseData.message.trim() !== "") {
    return responseData.message;
  }

  if (typeof response?.statusText === "string" && response.statusText.trim() !== "") {
    return response.statusText;
  }

  if (typeof error?.message === "string" && error.message.trim() !== "") {
    return error.message;
  }

  return fallback;
};

const normalizeQueueJob = (
  rawJob,
  {
    fallbackStatus = null,
    fallbackProgressMessage = null,
    fallbackIdCandidates = [],
  } = {},
) => {
  if (!rawJob || typeof rawJob !== "object") {
    return null;
  }

  const id = firstPositiveInteger(
    rawJob.id,
    rawJob.job_id,
    rawJob.queue_job_id,
    ...(Array.isArray(fallbackIdCandidates) ? fallbackIdCandidates : []),
  );
  const progressPercent = Number(rawJob.progress_percent);

  return {
    ...rawJob,
    id,
    status: rawJob.status ?? fallbackStatus ?? null,
    progress_percent: Number.isFinite(progressPercent) ? progressPercent : 0,
    progress_message: rawJob.progress_message ?? fallbackProgressMessage ?? null,
    error_message: rawJob.error_message ?? null,
    result: rawJob.result ?? null,
  };
};

const ensureQueueJob = (
  rawJob,
  source = "queue response",
  {
    fallbackStatus = null,
    fallbackProgressMessage = null,
    fallbackIdCandidates = [],
  } = {},
) => {
  const normalized = normalizeQueueJob(rawJob, {
    fallbackStatus,
    fallbackProgressMessage,
    fallbackIdCandidates,
  });

  if (!normalized || !normalized.id) {
    throw new Error(`Missing queue job id in ${source}.`);
  }

  return normalized;
};

const getQueueEnvelope = (response) => {
  const envelope = response?.data?.data;
  return envelope && typeof envelope === "object" ? envelope : null;
};

const getQueueJobFromEnvelope = (envelope) => {
  if (!envelope || typeof envelope !== "object") {
    return null;
  }

  if (envelope.job && typeof envelope.job === "object") {
    return envelope.job;
  }

  return envelope;
};

const parseQueueJobFromEnqueueResponse = (response) => {
  const envelope = getQueueEnvelope(response);
  return ensureQueueJob(
    getQueueJobFromEnvelope(envelope),
    "enqueue response",
    {
      fallbackStatus: ECONOMIC_QUEUE_STATUS.QUEUED,
      fallbackProgressMessage: envelope?.message ?? null,
      fallbackIdCandidates: [envelope?.job_id, envelope?.queue_job_id, envelope?.id],
    },
  );
};

const parseQueueJobFromStatusResponse = (response) => {
  const envelope = getQueueEnvelope(response);
  return ensureQueueJob(
    getQueueJobFromEnvelope(envelope),
    "status response",
    {
      fallbackProgressMessage: envelope?.message ?? null,
      fallbackIdCandidates: [envelope?.job_id, envelope?.queue_job_id, envelope?.id],
    },
  );
};

const parseQueueJobFromRetryResponse = (response) => {
  const envelope = getQueueEnvelope(response);
  return ensureQueueJob(
    getQueueJobFromEnvelope(envelope),
    "retry response",
    {
      fallbackStatus: ECONOMIC_QUEUE_STATUS.QUEUED,
      fallbackProgressMessage: envelope?.message ?? null,
      fallbackIdCandidates: [envelope?.job_id, envelope?.queue_job_id, envelope?.id],
    },
  );
};

const normalizeQueueListJob = (rawJob) => {
  if (!rawJob || typeof rawJob !== "object") {
    return null;
  }

  const normalized = normalizeQueueJob(rawJob, {
    fallbackIdCandidates: [rawJob?.payload?.job_id],
  });

  if (!normalized?.id) {
    return null;
  }

  return {
    ...normalized,
    attempts: parseNonNegativeInteger(rawJob?.attempts) ?? 0,
    max_attempts: parseNonNegativeInteger(rawJob?.max_attempts) ?? 0,
    transfer_type: rawJob?.transfer_type ?? null,
    created_by: parseNonNegativeInteger(rawJob?.created_by) ?? 0,
    created_at: rawJob?.created_at ?? null,
    updated_at: rawJob?.updated_at ?? null,
    started_at: rawJob?.started_at ?? null,
    completed_at: rawJob?.completed_at ?? null,
    next_retry_at: rawJob?.next_retry_at ?? null,
    payload: rawJob?.payload ?? null,
    details_summary: rawJob?.details_summary ?? null,
  };
};

const parseEconomicTransferQueueListResponse = (
  response,
  {
    defaultLimit = 50,
    defaultOffset = 0,
  } = {},
) => {
  const envelope = getQueueEnvelope(response) ?? response?.data ?? {};
  const rawItems = Array.isArray(envelope)
    ? envelope
    : (Array.isArray(envelope?.items)
      ? envelope.items
      : (Array.isArray(envelope?.jobs) ? envelope.jobs : []));
  const items = rawItems
    .map((rawJob) => normalizeQueueListJob(rawJob))
    .filter(Boolean);
  const count = parseNonNegativeInteger(
    envelope?.count ?? envelope?.pagination?.count,
  ) ?? items.length;
  const total = parseNonNegativeInteger(
    envelope?.total ?? envelope?.pagination?.total,
  ) ?? count;
  const limit = parsePositiveInteger(
    envelope?.limit ?? envelope?.pagination?.limit,
  ) ?? parsePositiveInteger(defaultLimit) ?? 50;
  const offset = parseNonNegativeInteger(
    envelope?.offset ?? envelope?.pagination?.offset,
  ) ?? parseNonNegativeInteger(defaultOffset) ?? 0;
  const hasMore = typeof envelope?.has_more === "boolean"
    ? envelope.has_more
    : typeof envelope?.hasMore === "boolean"
      ? envelope.hasMore
      : (offset + count) < total;

  return {
    items,
    count,
    total,
    limit,
    offset,
    hasMore,
  };
};

const clampPercent = (value) => {
  const parsed = Number(value);
  if (!Number.isFinite(parsed)) {
    return 0;
  }
  return Math.max(0, Math.min(100, Math.round(parsed)));
};

const calculateEconomicTransferQueueProgress = (jobs = []) => {
  if (!Array.isArray(jobs) || jobs.length === 0) {
    return 0;
  }

  const progressSum = jobs.reduce((sum, job) => {
    const status = String(job?.status ?? "").toUpperCase();
    if (status === ECONOMIC_QUEUE_STATUS.QUEUED) {
      return sum;
    }
    if (status === ECONOMIC_QUEUE_STATUS.PROCESSING) {
      return sum + clampPercent(job?.progress_percent);
    }
    if (status === ECONOMIC_QUEUE_STATUS.COMPLETED || status === ECONOMIC_QUEUE_STATUS.FAILED) {
      return sum + 100;
    }
    return sum + clampPercent(job?.progress_percent);
  }, 0);

  return clampPercent(progressSum / jobs.length);
};

const getEconomicQueueMonitorPollIntervalMs = (monitor) => {
  const counts = monitor?.counts ?? {};
  const activeCount = Number(counts.queued ?? 0) + Number(counts.in_progress ?? counts.processing ?? 0);
  return activeCount > 0
    ? ECONOMIC_QUEUE_MONITOR_ACTIVE_POLL_INTERVAL_MS
    : ECONOMIC_QUEUE_MONITOR_IDLE_POLL_INTERVAL_MS;
};

const isCollectedInvoiceQueueMonitorRoute = (path = "") => {
  const normalizedPath = String(path ?? "");
  return normalizedPath === "/superuser/invoices" || normalizedPath.startsWith("/superuser/invoices/");
};

const normalizeMonitorCounts = (rawCounts, jobs) => {
  const fallbackCounts = {
    queued: 0,
    in_progress: 0,
    failed: 0,
    completed: 0,
    total: Array.isArray(jobs) ? jobs.length : 0,
  };

  if (Array.isArray(jobs)) {
    jobs.forEach((job) => {
      const status = String(job?.status ?? "").toUpperCase();
      if (status === ECONOMIC_QUEUE_STATUS.QUEUED) {
        fallbackCounts.queued += 1;
      } else if (status === ECONOMIC_QUEUE_STATUS.PROCESSING) {
        fallbackCounts.in_progress += 1;
      } else if (status === ECONOMIC_QUEUE_STATUS.FAILED) {
        fallbackCounts.failed += 1;
      } else if (status === ECONOMIC_QUEUE_STATUS.COMPLETED) {
        fallbackCounts.completed += 1;
      }
    });
  }

  if (!rawCounts || typeof rawCounts !== "object") {
    return fallbackCounts;
  }

  const counts = {
    queued: parseNonNegativeInteger(rawCounts.queued) ?? fallbackCounts.queued,
    in_progress: parseNonNegativeInteger(rawCounts.in_progress ?? rawCounts.processing) ?? fallbackCounts.in_progress,
    failed: parseNonNegativeInteger(rawCounts.failed) ?? fallbackCounts.failed,
    completed: parseNonNegativeInteger(rawCounts.completed) ?? fallbackCounts.completed,
    total: parseNonNegativeInteger(rawCounts.total) ?? fallbackCounts.total,
  };

  return counts;
};

const parseEconomicTransferQueueMonitorResponse = (response) => {
  const envelope = getQueueEnvelope(response) ?? response?.data ?? {};
  const rawJobs = Array.isArray(envelope?.jobs)
    ? envelope.jobs
    : (Array.isArray(envelope?.items) ? envelope.items : []);
  const jobs = rawJobs
    .map((rawJob) => normalizeQueueListJob(rawJob))
    .filter(Boolean)
    .map((job) => ({
      ...job,
      status: String(job.status ?? "").toUpperCase(),
      progress_percent: clampPercent(job.progress_percent),
    }));
  const counts = normalizeMonitorCounts(envelope?.counts, jobs);
  const responseProgress = parseNonNegativeInteger(envelope?.progress_percent);

  return {
    jobs,
    counts,
    progress_percent: responseProgress === null
      ? calculateEconomicTransferQueueProgress(jobs)
      : clampPercent(responseProgress),
    limit: parsePositiveInteger(envelope?.limit) ?? 50,
  };
};

const parseQueueRunResponse = (response) => {
  const envelope = getQueueEnvelope(response) ?? response?.data ?? {};
  return {
    message: typeof envelope?.message === "string" && envelope.message.trim() !== ""
      ? envelope.message
      : "Collected invoice queue batch processed",
    processed: parseNonNegativeInteger(envelope?.processed) ?? 0,
    completed: parseNonNegativeInteger(envelope?.completed) ?? 0,
    failed: parseNonNegativeInteger(envelope?.failed) ?? 0,
    jobs: (Array.isArray(envelope?.jobs) ? envelope.jobs : [])
      .map((jobId) => parsePositiveInteger(jobId))
      .filter(Boolean),
    limit: parsePositiveInteger(envelope?.limit) ?? 10,
    transfer_type: typeof envelope?.transfer_type === "string" && envelope.transfer_type.trim() !== ""
      ? envelope.transfer_type
      : null,
    fallback: envelope?.fallback === true,
  };
};

const enqueueEconomicTransferJob = async ({
  endpoint,
  payload,
  requestFn = authenticatedRequest,
}) => {
  const response = await requestFn(endpoint, "POST", payload);
  return {
    response,
    job: parseQueueJobFromEnqueueResponse(response),
  };
};

const fetchEconomicTransferJobStatus = async ({
  endpoint,
  jobId,
  requestFn = authenticatedRequest,
}) => {
  const parsedJobId = parsePositiveInteger(jobId);
  if (!parsedJobId) {
    throw new TypeError("job_id must be a positive integer.");
  }

  const response = await requestFn(endpoint, "GET", { job_id: parsedJobId });
  return {
    response,
    job: parseQueueJobFromStatusResponse(response),
  };
};

const retryEconomicTransferJob = async ({
  endpoint,
  jobId,
  requestFn = authenticatedRequest,
}) => {
  const parsedJobId = parsePositiveInteger(jobId);
  if (!parsedJobId) {
    throw new TypeError("job_id must be a positive integer.");
  }

  const response = await requestFn(endpoint, "POST", { job_id: parsedJobId });
  return {
    response,
    job: parseQueueJobFromRetryResponse(response),
  };
};

const runEconomicTransferQueueBatch = async ({
  endpoint,
  limit = 10,
  requestFn = authenticatedRequest,
}) => {
  const parsedLimit = parsePositiveInteger(limit) ?? 10;
  const response = await requestFn(endpoint, "POST", {
    limit: Math.max(1, Math.min(10, parsedLimit)),
  });
  return {
    response,
    run: parseQueueRunResponse(response),
  };
};

const fetchEconomicTransferQueueMonitor = async ({
  limit = 50,
  requestFn = authenticatedRequest,
} = {}) => {
  const parsedLimit = parsePositiveInteger(limit) ?? 50;
  const response = await requestFn("/collected-invoices/economic/queue/monitor", "GET", {
    limit: Math.max(1, Math.min(100, parsedLimit)),
  });
  return {
    response,
    monitor: parseEconomicTransferQueueMonitorResponse(response),
  };
};

const dismissEconomicTransferQueueJob = async ({
  jobId,
  requestFn = authenticatedRequest,
}) => {
  const parsedJobId = parsePositiveInteger(jobId);
  if (!parsedJobId) {
    throw new TypeError("job_id must be a positive integer.");
  }

  return requestFn("/collected-invoices/economic/queue/dismiss", "POST", {
    job_id: parsedJobId,
  });
};

const dismissTerminalEconomicTransferQueueJobs = async ({
  requestFn = authenticatedRequest,
} = {}) => requestFn("/collected-invoices/economic/queue/dismiss-terminal", "POST", {});

const wait$1 = (durationMs) => new Promise((resolve) => {
  setTimeout(resolve, durationMs);
});

const pollEconomicTransferJobUntilTerminal = async ({
  statusEndpoint,
  jobId,
  pollIntervalMs = DEFAULT_ECONOMIC_QUEUE_POLL_INTERVAL_MS,
  requestFn = authenticatedRequest,
  onUpdate = null,
  shouldContinue = null,
}) => {
  let latestJob = null;

  while (typeof shouldContinue !== "function" || shouldContinue()) {
    const { job } = await fetchEconomicTransferJobStatus({
      endpoint: statusEndpoint,
      jobId,
      requestFn,
    });

    latestJob = job;

    if (typeof onUpdate === "function") {
      onUpdate(job);
    }

    if (isEconomicQueueStatusTerminal(job.status)) {
      return job;
    }

    await wait$1(pollIntervalMs);
  }

  return latestJob;
};

const ensureStrictBoolean = (value, fieldName = "value") => {
  if (typeof value !== "boolean") {
    throw new TypeError(`${fieldName} must be a boolean.`);
  }

  return value;
};

const buildCollectedInvoiceEconomicPayload = ({
  id,
  send_as_is = false,
} = {}) => {
  const parsedId = parsePositiveInteger(id);
  if (!parsedId) {
    throw new TypeError("id must be a positive integer.");
  }

  return {
    id: parsedId,
    send_as_is: ensureStrictBoolean(send_as_is, "send_as_is"),
  };
};

const getEconomicQueueJobMessage = (job) => {
  if (!job) {
    return "";
  }

  if (job.status === ECONOMIC_QUEUE_STATUS.FAILED) {
    return job.error_message || "Queue job failed.";
  }

  if (job.status === ECONOMIC_QUEUE_STATUS.COMPLETED) {
    if (typeof job?.result?.message === "string" && job.result.message.trim() !== "") {
      return job.result.message;
    }

    return job.progress_message || "Queue job completed.";
  }

  return job.progress_message || "";
};

/**
 * The invoices object
 */
const invoices = {
  draft: {
    get: async (draftId) => {
      return authenticatedRequest(
          "/invoices/draft?id=" + draftId,
          "GET")
    },
    close: async (draftId) => {
      return authenticatedRequest(
          "/invoices/draft/close",
          "POST",
          {
            id: parseInt(draftId)
          })
    },
  },
  exportOrderToDraft: async (order_id) => {
    return enqueueEconomicTransferJob({
      endpoint: '/economic/invoice/draft/export',
      payload: {
        order_id: parseInt(order_id)
      },
      requestFn: authenticatedRequest,
    }).catch((error) => {
      handleEconomicError(error);
      throw error;
    });
  },
  exportOrderToDraftStatus: async (job_id) => {
    return fetchEconomicTransferJobStatus({
      endpoint: '/economic/invoice/draft/export/status',
      jobId: job_id,
      requestFn: authenticatedRequest,
    }).catch((error) => {
      handleEconomicError(error);
      throw error;
    });
  },
  retryExportOrderToDraft: async (job_id) => {
    return retryEconomicTransferJob({
      endpoint: '/economic/invoice/draft/export/retry',
      jobId: job_id,
      requestFn: authenticatedRequest,
    }).catch((error) => {
      handleEconomicError(error);
      throw error;
    });
  },
};


const _sfc_main$2s = {};
const Invoices = /*#__PURE__*/_export_sfc(_sfc_main$2s, [['__file',"Invoices.vue"]]);

/**
 * The fromCustomerNumber object
 * This object is used to get, create and update customer data by customer number
 */
const fromCustomerNumber = {
  getUserId: async (customerNumber) => {
    return authenticatedRequest(
        "/admin/customer/getUserId?customer_number=" + customerNumber,
        "GET")
  },
};


const _sfc_main$2r = {};
const fromCustomerNumber_default = /*#__PURE__*/_export_sfc(_sfc_main$2r, [['__file',"fromCustomerNumber.vue"]]);

/**
 * The admin user object
 */
const AdminUserObject = {
  customers: {
    code: code,
    fromCustomerNumber: fromCustomerNumber,
  },
  statistics: statistics,
  plates: plates,
  invoices: invoices,
};

const _sfc_main$2q = {};
const AdminUserObject_default = /*#__PURE__*/_export_sfc(_sfc_main$2q, [['__file',"AdminUserObject.vue"]]);

/**
 * The EditFieldForm object
 * This object is used to edit an objects field
 */
const EditFieldForm = {
  /**
   * The object
   */
  object: ref(0),
  /**
   * The field
   */
  field: ref(''),
  /**
   * The value
   */
  value: ref(''),
  /**
   * The edit field function
   * @returns {Promise<void>}
   */
  editFormField: async (endpoint, objectId, field, value) => {
    return await authenticatedRequest(endpoint, "PUT", {
      id: objectId,
      field: field,
      value: value
    })
        .then(
            (response) => {
              // Success
            }
        )
        .catch(
            (error) => {
              parseError(error, 'universalEditField');
            }
        );
  },
  showEditFieldForm: async (endpoint, objectId, field, value, displayName = null, functionAfter = null) => {
    // If the display name is not defined, use the field name
    if (displayName === null) {
      displayName = field;
    }
    // Set the object
    EditFieldForm.object.value = objectId;
    // Set the field
    EditFieldForm.field.value = field;
    // Show the edit field form
    return await Swal.fire({
      title: 'Edit ' + displayName,
      html: `
        <input type="text" class="swal2-input" id="editField" value="${value}">
      `,
      showCancelButton: true,
      confirmButtonText: 'Save',
      cancelButtonText: 'Cancel',
      allowOutsideClick: false,
      allowEscapeKey: false,
      allowEnterKey: false
    }).then((result) => {
      if (result.isConfirmed) {
        // Set the value
        EditFieldForm.value.value = document.getElementById('editField').value;
        // Edit the field
        EditFieldForm.editFormField(endpoint, objectId, field, EditFieldForm.value.value).finally(() => {
          // If a function after is defined, run it
          if (functionAfter !== null && functionAfter !== undefined) {
            functionAfter();
          }
        });
      }
    });
  }

};

const _sfc_main$2p = {};
const EditFieldForm_default = /*#__PURE__*/_export_sfc(_sfc_main$2p, [['__file',"EditFieldForm.vue"]]);

const unauthenticatedRequest = (url, method, data) => {
  return axios({
    method,
    url: resolveReleaseApiUrl(url),
    data,
    headers: buildCurrentReleaseHeaders(),
  });
};

const _sfc_main$2o = {};
const unauthenticatedRequest_default = /*#__PURE__*/_export_sfc(_sfc_main$2o, [['__file',"unauthenticatedRequest.vue"]]);

/**
 * The reCAPTCHA object
 */
const reCAPTCHA = {
  preCheck: {
    get: async () => {
      return unauthenticatedRequest(
          "/auth/reCAPTCHA/public",
          "GET")
    },
  }
};


const _sfc_main$2n = {};
const reCAPTCHA_default = /*#__PURE__*/_export_sfc(_sfc_main$2n, [['__file',"reCAPTCHA.vue"]]);

const SYSTEM_USER_IDS = [1857];

const normalizePositiveInteger$4 = (value) => {
  const parsedValue = Number.parseInt(String(value ?? ""), 10);
  return Number.isInteger(parsedValue) && parsedValue > 0 ? parsedValue : null;
};

const getSystemUserIds = () => {
  return SYSTEM_USER_IDS.map((userId) => normalizePositiveInteger$4(userId)).filter((userId) => userId !== null);
};

const isSystemUserId = (userId) => {
  const normalizedUserId = normalizePositiveInteger$4(userId);
  return normalizedUserId !== null && getSystemUserIds().includes(normalizedUserId);
};

// Helper function to get i18n translation
const t$n = (key) => i18n.global.t(key);

const escapeHtml$5 = (value = "") => String(value)
  .replaceAll("&", "&amp;")
  .replaceAll("<", "&lt;")
  .replaceAll(">", "&gt;")
  .replaceAll("\"", "&quot;")
  .replaceAll("'", "&#39;");

const normalizeDateTimeLocalValue = (value) => {
  if (value === null || value === undefined || value === '') {
    return '';
  }

  const normalized = String(value).trim();
  if (normalized.includes('T')) {
    return normalized.slice(0, 16);
  }

  const [datePart, timePart = ''] = normalized.split(' ');
  if (!datePart || !timePart) {
    return normalized;
  }

  return `${datePart}T${timePart.slice(0, 5)}`;
};

const sanitizeQueryParams = (params = {}) => {
  if (!params || typeof params !== 'object') {
    return {};
  }

  return Object.fromEntries(
    Object.entries(params).filter(([, value]) => value !== null && value !== undefined)
  );
};

const buildQueryString = (params = {}) => {
  const queryParams = sanitizeQueryParams(params);
  const queryString = new URLSearchParams(queryParams).toString();

  return queryString ? `?${queryString}` : '';
};

/**
 * The Global Objects object, which contains global functions for objects.
 */
const ObjectsGlobal = {
  icons: {
    delete: 'fas fa-trash',
    info: 'fas fa-info',
    import: 'fas fa-file-import',
  },
  system_user_ids: getSystemUserIds(), // The system user ids, used by e.g. OrdersTable to highlight system orders
  cache: new Map(),
  clearCache: () => {
    ObjectsGlobal.cache.clear();
  },
  // Language object now uses i18n for translations
  get language() {
    return {
      title: (object) => {
        return `Opret ${object.meta.labels.single.toLowerCase()}`;
      },
      field: (object, column) => {
        return `Rediger ${object.columns[column].label.toLowerCase()}`;
      },
      get compare() { return t$n('global.compare'); },
      get generate_wash_certificate() { return t$n('global.generate_wash_certificate'); },
      get download_wash_certificate() { return t$n('global.download_wash_certificate'); },
      get not_configured() { return t$n('global.not_configured'); },
      get information() { return t$n('global.information'); },
      get login() { return t$n('global.login'); },
      get ready_to_wash() { return t$n('global.ready_to_wash'); },
      get register() { return t$n('global.register'); },
      get total_price_amount() { return t$n('global.total_price_amount'); },
      get change_customer() { return t$n('global.change_customer'); },
      get settings() { return t$n('common.settings'); },
      get view_order() { return t$n('global.view_order'); },
      get collection() { return t$n('global.collection'); },
      get generated() { return t$n('global.generated'); },
      get login_with_qr_code() { return t$n('global.login_with_qr_code'); },
      get logout() { return t$n('common.logout'); },
      get wash_multiple() { return t$n('global.wash_multiple'); },
      get homepage() { return t$n('global.homepage'); },
      get error_loading_transaction() { return t$n('global.error_loading_transaction'); },
      get requires_action() { return t$n('global.requires_action'); },
      get unknown_error() { return t$n('common.unknown_error'); },
      get expand() { return t$n('global.expand'); },
      get no_transactions_yet() { return t$n('global.no_transactions_yet'); },
      get add_other_product() { return t$n('global.add_other_product'); },
      get no_additional_items() { return t$n('global.no_additional_items'); },
      get additional_items() { return t$n('global.additional_items'); },
      get handheld_pending_order() { return t$n('global.handheld_pending_order'); },
      get confirmation_needed() { return t$n('global.confirmation_needed'); },
      get showing_of_separator() { return t$n('global.showing_of_separator'); },
      get scanning() { return t$n('global.scanning'); },
      get next() { return t$n('common.next'); },
      get send_as_is() { return t$n('global.send_as_is'); },
      get ignore_customer_arrangements() { return t$n('global.ignore_customer_arrangements'); },
      get recommended() { return t$n('global.recommended'); },
      get unlink() { return t$n('global.unlink'); },
      get link() { return t$n('global.link'); },
      get include_all_items_on_invoice() { return t$n('global.include_all_items_on_invoice'); },
      get to_department_and_customer_defaults() { return t$n('global.to_department_and_customer_defaults'); },
      get non_included_products() { return t$n('global.non_included_products'); },
      get invoice_now() { return t$n('global.invoice_now'); },
      get draft() { return t$n('pos.order.badges.draft'); },
      get all_booked() { return t$n('global.all_booked'); },
      get defaults() { return t$n('global.defaults'); },
      get prices() { return t$n('global.prices'); },
      get processing() { return t$n('global.processing'); },
      get abnormal() { return t$n('global.abnormal'); },
      get regret() { return t$n('global.regret'); },
      get search() { return t$n('global.search'); },
      get date_from() { return t$n('global.date_from'); },
      get date_to() { return t$n('global.date_to'); },
      get price_match() { return t$n('global.price_match'); },
      get price_unmatch() { return t$n('global.price_unmatch'); },
      get complete() { return t$n('global.complete'); },
      get lane() { return t$n('global.lane'); },
      get invoice_per_order() { return t$n('global.invoice_per_order'); },
      get price() { return t$n('common.price'); },
      get collapse() { return t$n('global.collapse'); },
      get edit() { return t$n('global.edit'); },
      get home() { return t$n('global.home'); },
      get configuration() { return t$n('global.configuration'); },
      get statistics() { return t$n('global.statistics'); },
      get booked() { return t$n('global.booked'); },
      get not_synchronized() { return t$n('global.not_synchronized'); },
      get only_tank_cleaning() { return t$n('global.only_tank_cleaning'); },
      get reject() { return t$n('global.reject'); },
      get history() { return t$n('global.history'); },
      get emphasis() { return t$n('global.emphasis'); },
      get special_arrangements() { return t$n('global.special_arrangements'); },
      get fixed_price_arrangements() { return t$n('global.fixed_price_arrangements'); },
      get split() { return t$n('global.split'); },
      get recent() { return t$n('global.recent'); },
      get possible_duplicates() { return t$n('global.possible_duplicates'); },
      get successful_syncs() { return t$n('global.successful_syncs'); },
      get save() { return t$n('common.save'); },
      get mark_as_not_duplicate() { return t$n('global.mark_as_not_duplicate'); },
      get my() { return t$n('global.my'); },
      get attach_to_order() { return t$n('global.attach_to_order'); },
      get synchronized() { return t$n('global.synchronized'); },
      get warnings() { return t$n('global.warnings'); },
      get warning() { return t$n('common.warning'); },
      get tank_cleaning() { return t$n('global.tank_cleaning'); },
      get none() { return t$n('global.none'); },
      get default() { return t$n('global.default'); },
      get required() { return t$n('global.required'); },
      get no_applicable_booking_types() { return t$n('global.no_applicable_booking_types'); },
      get optional() { return t$n('global.optional'); },
      get rows() { return t$n('global.rows'); },
      get auto_start_on_lpr() { return t$n('global.auto_start_on_lpr'); },
      get close() { return t$n('common.close'); },
      get no_slots_available() { return t$n('global.no_slots_available'); },
      get past() { return t$n('global.past'); },
      get closed() { return t$n('global.closed'); },
      get related_service() { return t$n('global.related_service'); },
      get usage_log() { return t$n('global.usage_log'); },
      get import_all() { return t$n('global.import_all'); },
      get note() { return t$n('global.note'); },
      get or_scan_plates() { return t$n('global.or_scan_plates'); },
      get import() { return t$n('global.import'); },
      get phone_country_code() { return t$n('global.phone_country_code'); },
      get succeeded() { return t$n('global.succeeded'); },
      get summary() { return t$n('global.summary'); },
      get opening_hours() { return t$n('global.opening_hours'); },
      get customers() { return t$n('global.customers'); },
      get selected() { return t$n('global.selected'); },
      get weekday() { return t$n('global.weekday'); },
      get opening_hour() { return t$n('global.opening_hour'); },
      get closing_hour() { return t$n('global.closing_hour'); },
      get found() { return t$n('global.found'); },
      get waiting() { return t$n('global.waiting'); },
      get selected_multiple() { return t$n('global.selected_multiple'); },
      get queue() { return t$n('global.queue'); },
      get in_progress() { return t$n('global.in_progress'); },
      get failed() { return t$n('global.failed'); },
      get barred() { return t$n('global.barred'); },
      get invalid() { return t$n('global.invalid'); },
      get last_wash() { return t$n('global.last_wash'); },
      get have_not() { return t$n('global.have_not'); },
      get clear() { return t$n('common.clear'); },
      get have() { return t$n('global.have'); },
      get hide() { return t$n('common.hide'); },
      get cancel() { return t$n('common.cancel'); },
      get previous() { return t$n('global.previous'); },
      get unselect() { return t$n('global.unselect'); },
      get select() { return t$n('common.select'); },
      get month() { return t$n('global.month'); },
      get all() { return t$n('common.all'); },
      get copy() { return t$n('global.copy'); },
      get yes() { return t$n('common.yes'); },
      get no() { return t$n('common.no'); },
      get email() { return t$n('common.email'); },
      get subscriptions() { return t$n('global.subscriptions'); },
      get invoice_already_created() { return t$n('global.invoice_already_created'); },
      get active() { return t$n('common.active'); },
      get inactive() { return t$n('common.inactive'); },
      get password() { return t$n('global.password'); },
      get customer() { return t$n('global.customer'); },
      get other_period() { return t$n('global.other_period'); },
      get phone_number() { return t$n('global.phone_number'); },
      get take_picture() { return t$n('global.take_picture'); },
      get no_data() { return t$n('global.no_data'); },
      get confirm_delete() { return t$n('global.confirm_delete'); },
      get clear_all() { return t$n('global.clear_all'); },
      get customer_notes() { return t$n('global.customer_notes'); },
      get done() { return t$n('common.done'); },
      get stop() { return t$n('global.stop'); },
      get confirm_delete_message() { return t$n('global.confirm_delete_message'); },
      get actions() { return t$n('common.actions'); },
      get update() { return t$n('global.update'); },
      get loading() { return t$n('global.loading'); },
      get error() { return t$n('common.error'); },
      get completed() { return t$n('global.completed'); },
      get not_completed() { return t$n('global.not_completed'); },
      get nothing_to_do_all_set() { return t$n('global.nothing_to_do_all_set'); },
      get mark_as_completed() { return t$n('global.mark_as_completed'); },
      get delete() { return t$n('global.delete'); },
      get submit() { return t$n('global.submit'); },
      get reset() { return t$n('global.reset'); },
      get customer_name() { return t$n('global.customer_name'); },
      get total() { return t$n('global.total'); },
      get status() { return t$n('common.status'); },
      get other() { return t$n('global.other'); },
      get remove() { return t$n('common.remove'); },
      get showing() { return t$n('global.showing'); },
      get add() { return t$n('global.add'); },
      get reload() { return t$n('global.reload'); },
      get time() {
        return {
          get at_hour() { return t$n('global.time.at_hour'); },
          get today() { return t$n('common.today'); },
          get anytime() { return t$n('global.text.anytime'); },
          get yesterday() { return t$n('global.time.yesterday'); },
          get this_month() { return t$n('global.time.this_month'); },
          get last_month() { return t$n('global.time.last_month'); },
          get this_year() { return t$n('global.time.this_year'); },
          get all() { return t$n('global.time.all'); },
          get date() { return t$n('common.date'); },
        };
      },
      get error_messages() {
        return {
          get not_array() { return t$n('global.error_messages.not_array'); },
          get not_object() { return t$n('global.error_messages.not_object'); },
          get not_string() { return t$n('global.error_messages.not_string'); },
        };
      },
      get in() { return t$n('global.in'); },
      get nothing_left_to_show() { return t$n('global.nothing_left_to_show'); },
      get pending() { return t$n('global.pending'); },
      get cancelled() { return t$n('global.cancelled'); },
      get show_content() { return t$n('global.show_content'); },
      get show() { return t$n('common.show'); },
      get hide_content() { return t$n('global.hide_content'); },
      get quantity() { return t$n('common.quantity'); },
      get manage() { return t$n('global.manage'); },
      get customer_number() { return t$n('global.customer_number'); },
      get payment() {
        return {
          get method() { return t$n('global.payment.method'); },
          get fixed_pricing() { return t$n('global.payment.fixed_pricing'); },
          get status() {
            return {
              get pending() { return t$n('global.payment.status.pending'); },
              get succeeded() { return t$n('global.payment.status.succeeded'); },
              get failed() { return t$n('global.payment.status.failed'); },
              get cancelled() { return t$n('global.payment.status.cancelled'); },
            };
          },
          get type() {
            return {
              get card() { return t$n('global.payment.type.card'); },
              get bank_transfer() { return t$n('global.payment.type.bank_transfer'); },
              get cash() { return t$n('global.payment.type.cash'); },
              get other() { return t$n('global.payment.type.other'); },
            };
          },
          get payment_recieved() { return t$n('global.payment.payment_recieved'); },
          get amount() { return t$n('global.payment.amount'); },
          get date() { return t$n('common.date'); },
          get reference() { return t$n('common.reference'); },
          get transaction_id() { return t$n('global.payment.transaction_id'); },
          get payment_intent() { return t$n('global.payment.payment_intent'); },
          get receipt() { return t$n('global.payment.receipt'); },
          get receipt_url() { return t$n('global.payment.receipt_url'); },
          get discount() { return t$n('common.discount'); },
        };
      },
      get invoice() { return t$n('common.invoice'); },
      get text() {
        return {
          get anytime() { return t$n('global.text.anytime'); },
          get today() { return t$n('common.today'); },
          get yesterday() { return t$n('global.text.yesterday'); },
          get this_week() { return t$n('global.text.this_week'); },
          get last_7_days() { return t$n('global.text.last_7_days'); },
          get last_week() { return t$n('global.text.last_week'); },
          get this_month() { return t$n('global.text.this_month'); },
          get last_month() { return t$n('global.text.last_month'); },
          get other_month() { return t$n('global.text.other_month'); },
          get this_year() { return t$n('global.text.this_year'); },
          get same_week_last_year() { return t$n('global.text.same_week_last_year'); },
          get same_month_last_year() { return t$n('global.text.same_month_last_year'); },
          get all() { return t$n('global.text.all'); },
          get year() { return t$n('common.year'); },
          get month() { return t$n('global.text.month'); },
          get search_in() { return t$n('global.text.search_in'); },
        };
      },
      get capture() { return t$n('global.capture'); },
    };
  },
  requestOptions: {
    defaultOptions: {
      authenticated: true,
    },
    applyOptions: (optionsObject) => {
      return {
        ...ObjectsGlobal.requestOptions.defaultOptions,
        ...optionsObject
      };
    },
  },
  parse: {
    boolean: (value) => {
      return value === 'true' || value === '1' || value === true || value === 1;
    },
    number: (value) => {
      return parseInt(value);
    },
    string: (value) => {
      return value;
    },
  },
  set: {
    /**
     * Set a column in an object
     * @param {string} endpoint The endpoint of the object
     * @param {number} id The id of the object
     * @param {string} column The column to set
     * @param {string} value The value to set
     * @returns {Promise} The promise
     */
    column: async (endpoint, id, column, value) => {
      ObjectsGlobal.clearCache();
      return authenticatedRequest(
          endpoint,
          "PUT",
          {
            id: id,
            [column]: value,
          },
          (error) => {
            ObjectsGlobal.errorHandler.handleError(error);
          }
      ).then((response) => {
        ObjectsGlobal.clearCache();
        return response;
      });
    }
  },
  errorHandler: {
    /**
     * Handle an error
     * @param {object} error The error object
     */
    handleError: (error) => {
      console.error(error);
      let message = ObjectsGlobal.language.unknown_error;
      if (error.response && error.response.data && error.response.data.data.message) {
        message = error.response.data.data.message;
      }
      Swal.fire({
        icon: 'error',
        title: ObjectsGlobal.language.error,
        text: message,
      });
    }
  },
  add: {
    /**
     * Add an object
     * @param {string} endpoint The endpoint of the object
     * @param {object} data The data (columns) of the object to add (e.g. [name = "Test", description = "Test"])
     * @param {object} optionsObject The options (e.g. {authenticated: false})
     * @returns {Promise} The promise
     */
    object: async (endpoint, data, optionsObject = {}) => {
      ObjectsGlobal.clearCache();
      let options = ObjectsGlobal.requestOptions.applyOptions(optionsObject);
      let promise;
      if (options.authenticated) {
        promise = authenticatedRequest(
            endpoint,
            "POST",
            data
        );
      } else {
        promise = unauthenticatedRequest$1(
            endpoint,
            "POST",
            data
        );
      }
      return promise.then((response) => {
        ObjectsGlobal.clearCache();
        return response;
      });
    }
  },
  delete: {
    /**
     * Delete an object
     * @param {string} endpoint The endpoint of the object
     * @param {number} id The id of the object
     * @returns {Promise} The promise
     */
    object: async (endpoint, id, optionsObject = {}) => {
      ObjectsGlobal.clearCache();
      const params = new URLSearchParams({ id: String(id) });
      if (optionsObject?.confirmed === true) {
        params.set("confirmed", "true");
      }
      return authenticatedRequest(
          `${endpoint}?${params.toString()}`,
          "DELETE"
      ).then((response) => {
        ObjectsGlobal.clearCache();
        return response;
      });
    }
  },
  get: {
    /**
     * Get an object
     * @param {string} endpoint The endpoint of the object
     * @param {number|array} id The id of the object, OR an array of get parameters (e.g. {id: 1, department_id: 2})
     * @param {object} optionsObject The options (e.g. {authenticated: false})
     * @returns {Promise} The promise
     */
    object: async (endpoint, id, optionsObject = {}) => {
      const requestParams = typeof id === 'object' && id !== null
        ? sanitizeQueryParams(id)
        : {id};
      const cacheKey = JSON.stringify({endpoint, id: requestParams, optionsObject});
      if (ObjectsGlobal.cache.has(cacheKey)) {
        return ObjectsGlobal.cache.get(cacheKey);
      }

      const requestEndpoint = `${endpoint}${buildQueryString(requestParams)}`;
      let options = ObjectsGlobal.requestOptions.applyOptions(optionsObject);
      let promise;
      if (options.authenticated) {
        promise = authenticatedRequest(
            requestEndpoint,
            "GET"
        ).then((response) => {
          return response.data.data;
        }).catch((error) => {
          ObjectsGlobal.cache.delete(cacheKey);
        });
      } else {
        promise = unauthenticatedRequest$1(
            requestEndpoint,
            "GET"
        ).then((response) => {
          return response.data.data;
        }).catch((error) => {
          ObjectsGlobal.cache.delete(cacheKey);
        });
      }

      ObjectsGlobal.cache.set(cacheKey, promise);
      return promise;
    },
    list: async (endpoint, optionsObject = {filters: {}, pagination: {page: 1, limit: 100, order: 'id:DESC'}}) => {
      return await authenticatedRequest(
          endpoint,
          "GET",
          {
            // Map the filters as: filter1:value1,filter2:value2,filter3:value3
            filters: Object.entries(optionsObject.filters).flatMap(([key, value]) => {
              if (Array.isArray(value)) {
                return value.map(v => `${key}:${v}`);
              }
              return `${key}:${value}`;
            }).join(','),
            page: optionsObject.pagination.page,
            limit: optionsObject.pagination.limit,
            search: optionsObject.search || '',
            order: optionsObject.pagination.order || 'id:DESC',
          }).then((response) => {
        return response.data.data;
      }).catch((error) => {
        return [];
      });
    },
    /**
     * Get all objects
     * @param {string} endpoint The endpoint of the object
     * @param data The filters to apply to the objects (e.g. {filters: "department_id:1"})
     * @returns {Promise} The promise
     */
    objects: async (endpoint, data = {}) => {
      const requestData = sanitizeQueryParams(data);
      if (requestData.filters && typeof requestData.filters === 'object') {
        requestData.filters = Object.entries(requestData.filters).flatMap(([key, value]) => {
          if (Array.isArray(value)) {
            return value.map(v => `${key}:${v}`);
          }
          return `${key}:${value}`;
        }).join(',');
      }
      const cacheKey = JSON.stringify({endpoint, data: requestData});
      if (ObjectsGlobal.cache.has(cacheKey)) {
        return ObjectsGlobal.cache.get(cacheKey);
      }

      const promise = authenticatedRequest(
          endpoint,
          "GET",
          requestData
      ).then((response) => {
        return response.data.data;
      }).catch((error) => {
        ObjectsGlobal.cache.delete(cacheKey);
      });

      ObjectsGlobal.cache.set(cacheKey, promise);
      return promise;
    },
    /**
     * Get multiple objects by their ids
     * @param {string} endpoint The endpoint of the object
     * @param {array} ids The ids of the objects
     * @returns {Promise} The promise
     */
    objectsByIds(endpoint, ids) {
      return Promise.all(ids.map(id => this.object(endpoint, id)));
    }
  },
  /**
   * Show the create object form
   * @param {object} object The object
   * @param {function} onAfterSubmit The function to call after the form is submitted
   * @param {object} lockedValues The locked values of the object (e.g. {department_id: 1})
   * @returns {Promise} The promise
   */
  showCreateObjectForm: async (object, onAfterSubmit = null, lockedValues = {}) => {
    let html = await ObjectsGlobal.generateCreateObjectForm(object.columns, lockedValues);
    return Swal.fire({
      title: ObjectsGlobal.language.title(object),
      html: html,
      showCancelButton: true,
      confirmButtonText: ObjectsGlobal.language.save,
      cancelButtonText: ObjectsGlobal.language.cancel,
      didOpen: () => {
        const helpers = {
          getFieldValue: (id) => document.getElementById(id)?.value,
          setFieldValue: (id, value) => {
            const el = document.getElementById(id);
            if (el) el.value = value;
          },
        };
        // Attach onchange listeners if defined in the object configuration
        for (const column in object.columns) {
          const config = object.columns[column].creation;
          if (config && typeof config.onchange === 'function') {
            const element = document.getElementById(column);
            if (element) {
              element.addEventListener('change', (event) => {
                config.onchange(event, helpers);
              });
              // Trigger once on load if there's an initial value
              if (element.value) {
                config.onchange({ target: element }, helpers);
              }
            }
          }
        }
      },
      preConfirm: () => {
        // For each column in the object, get the value from the input field and add it to the object
        const argument_array = [];
        // Add the object add arguments in the same order as the add function
        for (const column in object.columns) {
          if (object.columns[column].creation.required) {
            const fieldValue = lockedValues[column] !== undefined
                ? lockedValues[column]
                : document.getElementById(column)?.value;
            try {
              if (fieldValue === undefined || fieldValue === null || fieldValue === '') {
                throw new Error('Feltet ' + object.columns[column].label + ' er påkrævet.');
              }
            } catch (error) {
              Swal.showValidationMessage(
                  `${error}`
              );
              return false;
            }
            argument_array.push(fieldValue);
          }
        }
        // Call the add function with the arguments
        return object.add(...argument_array).then(() => {
          if (onAfterSubmit !== null) {
            return Promise.resolve(onAfterSubmit());
          }
        }).catch((error) => {
          Swal.showValidationMessage(
              `Fejl: ${error.message || error}`
          );
        });
      }
    });
  },
  generateCreateObjectForm: async (columns, lockedValues) => {
    let html = '';
    // Check if the column is a locked value
    function isLockedValue(column) {
      return lockedValues[column] !== undefined;
    }
    // If it is a locked value, set the value to the locked value
    function getLockedValue(column, defaultValue = '') {
      return lockedValues[column] !== undefined ? lockedValues[column] : '';
    }
    function getCreationDefaultValue(column, defaultValue = '') {
      return columns[column].creation.default !== undefined ? columns[column].creation.default : defaultValue;
    }
    function isBooleanDefault(column, value) {
      const defaultValue = getCreationDefaultValue(column, true);
      return String(defaultValue) === String(value);
    }
    // Add the form fields
    for (const column in columns) {
      if (columns[column].creation.required) {
        switch (columns[column].type) {
          case 'string':
            html += `<div class="field">
              <label class="label has-text-black">${columns[column].label}</label>
              <div class="control">
                <input class="input has-background-light has-text-black" type="text" id="${column}">
              </div>
            </div>`;
            break;
          case 'number':
            html += `<div class="field" style="display: ${isLockedValue(column) ? 'none' : 'block'}">
              <label class="label has-text-black">${columns[column].label}</label>
              <div class="control">
                <input class="input has-background-light has-text-black" type="number" id="${column}" value="${getLockedValue(column)}" ${isLockedValue(column) ? 'disabled' : ''}>
              </div>
            </div>`;
            break;
          case 'boolean':
            html += `<div class="field">
              <label class="label has-text-black">${columns[column].label}</label>
              <div class="control">
              <!-- Select -->
              <div class="select is-fullwidth">
                <select id="${column}" class="has-background-light has-text-black">
                  <option value="true" ${isBooleanDefault(column, true) ? 'selected' : ''}>Ja</option>
                  <option value="false" ${isBooleanDefault(column, false) ? 'selected' : ''}>Nej</option>
                </select>
              </div>
            </div>`;
            break;
          case 'datetime':
            html += `<div class="field">
              <label class="label has-text-black">${columns[column].label}</label>
              <div class="control">
                <input class="input has-background-light has-text-black" type="datetime-local" id="${column}">
              </div>
            </div>`;
            break;
          case 'select':
            //var isLocked = lockedValues[column] !== undefined;
            html += `<div class="field">
                <label class="label has-text-black">${columns[column].label}</label>
                <div class="control">
                <!-- Select -->
                <div class="select is-fullwidth">
                  <select id="${column}" class="has-background-light has-text-black" ${isLockedValue(column) ? 'disabled' : ''} >`;
            // Check if the columns options are a function, if so, call it (and wait for it to finish). Otherwise, make the array awaitable
            var awaitOptions = columns[column].options;
            if (typeof columns[column].options === 'function') {
              awaitOptions = columns[column].options(lockedValues);
            } else {
              awaitOptions = new Promise((resolve) => {
                resolve(columns[column].options);
              });
            }
            // Wait for the options to be ready
            await awaitOptions.then((response) => {
              // How long are the list of options
              for (let i = 0; i < response.length; i++) {
                var tmp = response[i];
                // Check if the column exists in the locked values
                //var lockedValue = lockedValues[column] === tmp.id ? 'selected' : '';
                //html += `<option value="${tmp.id}" ${lockedValue}>`;
                html += `<option value="${tmp.id}" ${getLockedValue(column) == tmp.id ? 'selected' : ''}>`;
                html += `${tmp.name}`;
                html += `</option>`;
              }
            });
            html += `</select>
                </div>
              </div>`;
            break;
        }
      }
    }
    // Return the form
    return html;
  },
  async generateEditObjectFieldForm(object, column, value, options = { filters: {
      //customer_id: 12345679,
      //department_id: 2
    }, pagination: { limit: 10, page: 1 } }) {
    let html = '';
    function ifNullDefault(value, defaultValue) {
      return value === null ? defaultValue : value;
    }
    switch (object.columns[column].type) {
      case 'string':
        html += `<div class="field">
          <label class="label has-text-black">${object.columns[column].label}</label>
          <div class="control">
            <input class="input has-background-light has-text-black" type="text" id="${column}" value="${ifNullDefault(value, '')}">
          </div>
        </div>`;
        break;
      case 'number':
        html += `<div class="field">
          <label class="label has-text-black">${object.columns[column].label}</label>
          <div class="control">
            <input class="input has-background-light has-text-black" type="number" id="${column}" value="${value}">
          </div>
        </div>`;
        break;
      case 'boolean':
        html += `<div class="field">
          <label class="label has-text-black">${object.columns[column].label}</label>
          <div class="control">
          <!-- Select -->
          <div class="select is-fullwidth">
            <select id="${column}" class="has-background-light has-text-black">
              <option value="true" ${value === true ? 'selected' : ''}>${ObjectsGlobal.language.yes}</option>
              <option value="false" ${value === false ? 'selected' : ''}>${ObjectsGlobal.language.no}</option>
            </select>
          </div>
        </div>`;
        break;
      case 'datetime':
        html += `<div class="field">
          <label class="label has-text-black">${object.columns[column].label}</label>
          <div class="control">
            <input class="input has-background-light has-text-black" type="datetime-local" id="${column}" value="${normalizeDateTimeLocalValue(value)}">
          </div>
        </div>`;
        break;
      case 'multi-select':
        html += `<div class="field">
            <label class="label has-text-black">${object.columns[column].label}</label>
            <div class="control" id="${column}-container">`;
        await object.columns[column].options(options).then((response) => {
          const currentValues = Array.isArray(value) ? value : [];
          for (let i = 0; i < response.length; i++) {
            const tmp = response[i];
            const isChecked = currentValues.includes(tmp.id);
            html += `<label class="checkbox is-block has-text-black" style="margin-bottom: 0.5rem;">
              <input type="checkbox" name="${column}" value="${tmp.id}" ${isChecked ? 'checked' : ''}>
              ${tmp.name ? tmp.name : tmp.id}
            </label>`;
          }
        });
        html += `</div></div>`;
        break;
      case 'select':
        html += `<div class="field">
            <label class="label has-text-black">${object.columns[column].label}</label>
            <div class="control">
            <!-- Select -->
            <div class="select is-fullwidth">
              <select id="${column}" class="has-background-light has-text-black">`;
        await object.columns[column].options(options).then((response) => {
          console.log(response);
          // How long are the list of options
          for (let i = 0; i < response.length; i++) {
            const tmp = response[i];
            const optionValue = tmp?.id ?? "";
            const optionLabel = tmp?.name ? tmp.name : optionValue;
            console.log(tmp);
            html += `<option value="${escapeHtml$5(optionValue)}" ${(value == optionValue || (value === null && optionValue === 0)) ? 'selected' : ''}>${escapeHtml$5(optionLabel)}</option>`;
          }
        });
        html += `</select>
            </div>
          </div>`;
        break;
    }
    return html;
  },
  showEditObjectFieldForm: async (object, id, column, value, onAfterSubmit = null, options = {}) => {
    let html = await ObjectsGlobal.generateEditObjectFieldForm(object, column, value, options);
    const isMultiSelect = object.columns[column].type === 'multi-select';
    return Swal.fire({
      title: ObjectsGlobal.language.field(object, column),
      html: html,
      showCancelButton: true,
      confirmButtonText: ObjectsGlobal.language.save,
      cancelButtonText: ObjectsGlobal.language.cancel,
      preConfirm: () => {
        try {
          let newValue;
          if (isMultiSelect) {
            // Collect all checked checkbox values for multi-select
            const checkboxes = document.querySelectorAll(`input[name="${column}"]:checked`);
            newValue = Array.from(checkboxes).map(cb => cb.value);
          } else {
            newValue = document.getElementById(column).value;
          }
          // Call the set function with the arguments
          return object.set[column](id, newValue).then(() => {
            if (onAfterSubmit !== null) {
              return Promise.resolve(onAfterSubmit());
            }
          }).catch((error) => {
            console.error('Unable to edit object field', error);
            // Show an error message
            Swal.showValidationMessage(
                `Fejl: ${error.message || error}`
            );
          });
        } catch (error) {
          console.error('Unable to edit object field', error);
          // Show an error message
          Swal.showValidationMessage(
              `Fejl: ${error}`
          );
        }
      }
    });
  },
  showObjects: async (object, displayColumns = null, filters = {}, displayActions = false) => {
    let html = '';
    // Get the objects
    await object.get.all().then((objects) => {
      // Filter the objects
      if (Object.keys(filters).length > 0) {
        objects = objects.filter((object) => {
          for (const filter in filters) {
            if (object[filter] !== filters[filter]) {
              return false;
            }
          }
          return true;
        });
      }
      // Add the table
      html += `<table class="table is-fullwidth has-text-left has-background-light">
        <thead>
        <tr>`;
      // Add the table headers
      if (displayColumns === null) {
        for (const column in object.columns) {
          html += `<th class="has-text-black">${object.columns[column].label}</th>`;
        }
      } else {
        for (const column in displayColumns) {
          html += `<th class="has-text-black">${object.columns[column].label}</th>`;
        }
      }
      if (displayActions) {
        html += `<th  class="has-text-black">Handlinger</th>`;
      }
      html += `
        </tr>
        </thead>
        <tbody>`;
      // Add the table rows
      for (let i = 0; i < objects.length; i++) {
        html += `<tr>`;
        // Add the table columns
        if (displayColumns === null) {
          for (const column in object.columns) {
            html += `<td class="has-text-black">${objects[i][column]}</td>`;
          }
        } else {
          for (const column in displayColumns) {
            html += `<td class="has-text-black">${objects[i][column]}</td>`;
          }
        }
        // Add the actions column
        if (displayActions) {
          html += `<td>
          <button class="button is-small is-info" @click="showEditObjectFieldForm(${objects[i].id}, 'name', '${objects[i].name}')">Rediger</button>
          <button class="button is-small is-danger" @click="deleteObject(${objects[i].id})">Slet</button>
        </td>`;
          html += `</tr>`;
        }
      }
      // If the list is empty
      if (objects.length === 0) {
        html += `<tr>
          <td colspan="${Object.keys(object.columns).length + 1}">${ObjectsGlobal.language.no_data}</td>
        </tr>`;
      }
      html += `</tbody>
      </table>`;
    });
    return Swal.fire({
      title: object.meta.title,
      html: html,
      showCancelButton: !displayActions,
      showConfirmButton: displayActions,
      confirmButtonText: ObjectsGlobal.language.save,
      cancelButtonText: ObjectsGlobal.language.cancel,
    });
  },
  showDeleteObjectForm: async (object, id, onAfterSubmit = null) => {
    return Swal.fire({
      title: `Fjern ${object.meta.labels.single}?`,
      text: ObjectsGlobal.language.confirm_delete_message,
      showCancelButton: true,
      showConfirmButton: true,
      confirmButtonText: ObjectsGlobal.language.confirm_delete,
      cancelButtonText: ObjectsGlobal.language.cancel,
      showLoaderOnConfirm: true,
      preConfirm: () => {
        return object.delete(id).then(() => {
          if (onAfterSubmit !== null) {
            return Promise.resolve(onAfterSubmit());
          }
        }).catch((error) => {
          Swal.showValidationMessage(
              `Fejl: ${error.message || error}`
          );
        });
      }
    });
  },
  showDeleteConfirmationModal: async (object, id, onAfterSubmit = null) => {
    return Swal.fire({
      title: `Fjern ${object.meta.labels.single}?`,
      text: ObjectsGlobal.language.confirm_delete_message,
      showCancelButton: true,
      showConfirmButton: true,
      confirmButtonText: ObjectsGlobal.language.confirm_delete,
      cancelButtonText: ObjectsGlobal.language.cancel,
      showLoaderOnConfirm: true,
      preConfirm: () => {
        return object.delete.single(id).then(() => {
          if (onAfterSubmit !== null) {
            onAfterSubmit();
          }
        }).catch((error) => {
          Swal.showValidationMessage(
              `Fejl: ${error.message || error}`
          );
        });
      }
    })
  },
  performAction: async (endpoint, id, action, data = {}, onAfterSubmit = null) => {
    ObjectsGlobal.clearCache();
    return authenticatedRequest(
        `${endpoint}/${action}`,
        "POST",
        {
          id: parseInt(id),
          ...data
        }
    ).then((response) => {
      ObjectsGlobal.clearCache();
      if (onAfterSubmit !== null) {
        onAfterSubmit();
      }
      return response;
    });
  },
  functions: {
    /**
     * Format a date to a local string
     * @param date
     * @returns {string}
     */
    formatDate: (date) => {
      return new Date(date).toLocaleString('da-DK');
    }
  }
};

const _sfc_main$2m = {};
const ObjectsGlobal_default = /*#__PURE__*/_export_sfc(_sfc_main$2m, [['__file',"ObjectsGlobal.vue"]]);

const t$m = (key) => i18n.global.t(key);

/**
 * Local categories cache
 * @type {ref<null>}
 */
const categories_cache = ref(null);

/**
 * Get the category name
 * @param id
 * @returns {string}
 */
const getCategoryName = (id) => {
  if (categories_cache.value === null) {
    categories_cache.value = [];
    SessionUser.objects.categories.get.all().then((categories) => {
      categories_cache.value = categories;
    });
  }
  const category = categories_cache.value.find((category) => category.id === parseInt(id));
  return category ? category.name : SessionUser.objects.global.language.no_data;
};

/**
 * The Categories object
 */
const Categories = {
  get meta() {
    return {
      title: t$m('objects.categories.title'),
      icon: "fas fa-list",
      description: t$m('objects.categories.description'),
      endpoint: "/categories",
      labels: {
        single: t$m('objects.categories.single'),
        multiple: t$m('objects.categories.multiple')
      }
    };
  },
  get columns() {
    return {
      id: {
        label: t$m('objects.columns.id'),
        type: "number",
        sortable: true,
        creation: {
          required: false
        }
      },
      name: {
        label: t$m('common.name'),
        type: "string",
        sortable: true,
        creation: {
          required: true
        }
      },
      description: {
        label: t$m('common.description'),
        type: "string",
        sortable: true,
        creation: {
          required: false
        }
      },
    };
  },
  add: async (name, description) => {
    return ObjectsGlobal.add.object(
        Categories.meta.endpoint,
        {
          name: name,
          description: description
        }
    );
  },
  set: {
    name: async (id, name) => {
      return ObjectsGlobal.set.column(
        Categories.meta.endpoint,
        id,
        "name",
        name
      )
    },
    description: async (id, description) => {
      return ObjectsGlobal.set.column(
        Categories.meta.endpoint,
        id,
        "description",
        description
      )
    },
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(Categories.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(Categories.meta.endpoint, id);
    }
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(Categories.meta.endpoint, id);
  },
  functions: {
    getCategoryName: getCategoryName,
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(Categories, id, onAfterSubmit);
    },
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(Categories, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        Categories,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$2l = {};
const Categories_default = /*#__PURE__*/_export_sfc(_sfc_main$2l, [['__file',"Categories.vue"]]);

const t$l = (key) => i18n.global.t(key);

const normalizeProductQueryOptions = (options = {}) => {
  const queryOptions = { ...options };
  if (!Object.prototype.hasOwnProperty.call(queryOptions, "final_price")) {
    queryOptions.final_price = false;
  }

  return Object.fromEntries(
    Object.entries(queryOptions).filter(([, value]) => value !== null && value !== undefined)
  );
};

/**
 * Local products cache
 * @type {ref<null>}
 */
const products_cache = ref(null);

/**
 * Get the product name
 * @param id
 * @param fallback
 * @returns {string}
 */
const getProductName = (id, fallback = null) => {
  if (products_cache.value === null) {
    products_cache.value = [];
    SessionUser.objects.products.get.all().then((products) => {
      products_cache.value = products;
    });
  }
  const product = products_cache.value.find((product) => product.id === parseInt(id));
  return product ? product.name : fallback === null ? SessionUser.objects.global.language.no_data : fallback;
};

/**
 * The Products object
 */
const Products = {
  get meta() {
    return {
      title: t$l('common.products'),
      icon: "fas fa-list",
      description: t$l('objects.products.description'),
      endpoint: "/products",
      labels: {
        single: t$l('objects.products.single'),
        multiple: t$l('objects.products.multiple')
      }
    };
  },
  get columns() {
    return {
      id: {
        label: t$l('objects.columns.id'),
        type: "number",
        sortable: true,
        creation: {
          required: false
        }
      },
      name: {
        label: t$l('common.name'),
        type: "string",
        sortable: true,
        creation: {
          required: true
        }
      },
      description: {
        label: t$l('common.description'),
        type: "string",
        sortable: true,
        creation: {
          required: false
        }
      },
      price: {
        label: t$l('common.price'),
        type: "number",
        sortable: true,
        creation: {
          required: true
        }
      },
      subscription_allowed: {
        label: t$l('objects.products.columns.subscription_allowed'),
        type: "boolean",
        sortable: true,
        creation: {
          required: false
        }
      },
      category: {
        label: t$l('objects.products.columns.category'),
        type: "select",
        sortable: true,
        creation: {
          required: false
        },
        options: async () => {
          return SessionUser.objects.categories.get.all();
        }
      },
      piktogram: {
        label: t$l('objects.products.columns.piktogram'),
        type: "number",
        sortable: true,
        creation: {
          required: false
        }
      },
      economic_product_id: {
        label: t$l('objects.products.columns.economic_product'),
        type: "select",
        sortable: true,
        creation: {
          required: false
        },
        options: async () => {
          return SessionUser.objects.economic_products.get.all();
        }
      },
      apply_category_discount: {
        label: t$l('objects.products.columns.use_category_discount'),
        type: "boolean",
        sortable: true,
        creation: {
          required: false
        }
      },
      requires_note: {
        label: t$l('objects.products.columns.requires_note'),
        type: "boolean",
        sortable: true,
        creation: {
          required: false
        }
      },
      is_wash: {
        label: t$l('objects.products.columns.is_wash'),
        type: "boolean",
        sortable: true,
        creation: {
          required: false
        }
      },
      display_in_booking_form: {
        label: t$l('objects.products.columns.show_in_booking_form'),
        type: "boolean",
        sortable: true,
        creation: {
          required: false
        }
      },
      order_priority: {
        label: t$l('objects.products.columns.sort_priority'),
        type: "number",
        sortable: true,
        creation: {
          required: false
        }
      }
    };
  },
  add: async (name, price) => {
    return ObjectsGlobal.add.object(
        Products.meta.endpoint,
        {
          name: name,
          price: price
        }
    );
  },
  set: {
    name: async (id, name) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "name",
        name
      )
    },
    description: async (id, description) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "description",
        description
      )
    },
    price: async (id, price) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "price",
          ObjectsGlobal.parse.number(price)
      )
    },
    subscription_allowed: async (id, subscription_allowed) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "subscription_allowed",
        ObjectsGlobal.parse.boolean(subscription_allowed)
      )
    },
    category: async (id, category) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "category",
        category
      )
    },
    piktogram: async (id, piktogram) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "piktogram",
        piktogram
      )
    },
    economic_product_id: async (id, economic_product_id) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "economic_product_id",
          ObjectsGlobal.parse.number(economic_product_id)
      )
    },
    apply_category_discount: async (id, apply_category_discount) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "apply_category_discount",
        ObjectsGlobal.parse.boolean(apply_category_discount)
      )
    },
    requires_note: async (id, requires_note) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "requires_note",
        ObjectsGlobal.parse.boolean(requires_note)
      )
    },
    is_wash: async (id, is_wash) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "is_wash",
        ObjectsGlobal.parse.boolean(is_wash)
      )
    },
    display_in_booking_form: async (id, display_in_booking_form) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "display_in_booking_form",
        ObjectsGlobal.parse.boolean(display_in_booking_form)
      )
    },
    order_priority: async (id, order_priority) => {
      return ObjectsGlobal.set.column(
        Products.meta.endpoint,
        id,
        "order_priority",
          ObjectsGlobal.parse.number(order_priority)
      )
    },
  },
  get: {
    all: async (options = {}) => {
      return ObjectsGlobal.get.objects(Products.meta.endpoint, normalizeProductQueryOptions(options));
    },
    single: async (id, options = {}) => {
      return ObjectsGlobal.get.object(Products.meta.endpoint, {id: id, ...normalizeProductQueryOptions(options)});
    },
    category: async (category_id, department_id, customer_id = null, final_price = false) => {
      return ObjectsGlobal.get.object(Products.meta.endpoint, normalizeProductQueryOptions({
        category: category_id,
        department_id: department_id,
        ...(customer_id !== null ? {customer_id: customer_id} : {}),
        ...{final_price: final_price}
      }));
    },
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(Products.meta.endpoint, id);
  },
  functions: {
    getProductName: getProductName,
    showCategoryProducts: async (category_id) => {
      console.log(category_id);
      return ObjectsGlobal.showObjects(Products, {
        id: true,
        name: true,
      }, {category: category_id}, false
      );
    }
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(Products, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        Products,
        id,
        column,
        value,
        onAfterSubmit
    );
  },
};

const _sfc_main$2k = {};
const Products_default = /*#__PURE__*/_export_sfc(_sfc_main$2k, [['__file',"Products.vue"]]);

const t$k = (key) => i18n.global.t(key);

/**
 * Local product options cache
 * @type {ref<null>}
 */
const product_options_cache = ref(null);

/**
 * Get the product options
 * @param id {number}
 * @returns {string}
 */
const getProductOptions = async (id) => {
  if (product_options_cache.value === null) {
    product_options_cache.value = [];
    await SessionUser.objects.product_options.get.all().then((product_options) => {
      product_options_cache.value = product_options;
    });
  }
  const product_option = product_options_cache.value.find((product_option) => product_option.id === parseInt(id));
  return product_option ? product_option.name : SessionUser.objects.global.language.no_data;
};



    /**
     * The Product Options object
     */
    const ProductOptions = {
      get meta() {
        return {
          title: t$k('objects.product_options.title'),
          icon: "fas fa-list",
          description: t$k('objects.product_options.description'),
          endpoint: "/product/options",
          labels: {
            single: t$k('objects.product_options.single'),
            multiple: t$k('objects.product_options.multiple')
          }
        };
      },
      get columns() {
        return {
          id: {
            label: t$k('objects.columns.id'),
            type: "number",
            sortable: true,
            creation: {
              required: false
            }
          },
          product_id: {
            label: t$k('objects.columns.product_id'),
            type: "select",
            sortable: true,
            creation: {
              required: true
            },
            options: async () => {
              console.log("Getting products");
              return SessionUser.objects.products.get.all();
            }
          },
          option_id: {
            label: t$k('objects.columns.product_id'),
            type: "select",
            sortable: true,
            creation: {
              required: true
            },
            options: async () => {
              console.log("Getting product options");
              return SessionUser.objects.products.get.all();
            }
          },
          name: {
            label: t$k('common.name'),
            type: "string",
            sortable: true,
            creation: {
              required: false
            }
          },
          min: {
            label: t$k('objects.columns.min'),
            type: "number",
            sortable: true,
            creation: {
              required: false
            }
          },
          max: {
            label: t$k('objects.columns.max'),
            type: "number",
            sortable: true,
            creation: {
              required: false
            }
          },
        };
      },
      add: async (product_id, option_id) => {
        return ObjectsGlobal.add.object(
            ProductOptions.meta.endpoint,
            {
              product_id: parseInt(product_id),
              option_id: parseInt(option_id)
            }
        );
      },
      set: {
        name: async (id, name) => {
          return ObjectsGlobal.set.column(
              ProductOptions.meta.endpoint,
              id,
              "name",
              name
          )
        },
        min: async (id, min) => {
          return ObjectsGlobal.set.column(
              ProductOptions.meta.endpoint,
              id,
              "min",
              parseInt(min)
          )
        },
        max: async (id, max) => {
          return ObjectsGlobal.set.column(
              ProductOptions.meta.endpoint,
              id,
              "max",
              parseInt(max)
          )
        },
        product_id: async (id, product_id) => {
          return ObjectsGlobal.set.column(
              ProductOptions.meta.endpoint,
              id,
              "product_id",
              product_id
          )
        },
        option_id: async (id, option_id) => {
          return ObjectsGlobal.set.column(
              ProductOptions.meta.endpoint,
              id,
              "option_id",
              option_id
          )
        },
      },
      get: {
        all: async () => {
          return ObjectsGlobal.get.objects(ProductOptions.meta.endpoint);
        },
        single: async (id) => {
          return ObjectsGlobal.get.object(ProductOptions.meta.endpoint, id);
        }
      },
      delete: async (id) => {
        return ObjectsGlobal.delete.object(ProductOptions.meta.endpoint, id);
      },
      functions: {
        getProductOptions: getProductOptions,
        getProductOptionName: (id) => {
          return getProductOptions(id);
        }
      },
      /**
       * Show the create object form
       * @param onAfterSubmit {function}
       * @param lockedValues {object}
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showCreateObjectForm: (onAfterSubmit = null, lockedValues = {}) => {
        return ObjectsGlobal.showCreateObjectForm(ProductOptions, onAfterSubmit, lockedValues);
      },
      /**
       * Show the edit object field form
       * @param id
       * @param column
       * @param value
       * @param onAfterSubmit
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
        return ObjectsGlobal.showEditObjectFieldForm(
            ProductOptions,
            id,
            column,
            value,
            onAfterSubmit
        );
      }
    };

const _sfc_main$2j = {};
const ProductOptions_default = /*#__PURE__*/_export_sfc(_sfc_main$2j, [['__file',"ProductOptions.vue"]]);

const normalizeDepartmentLabel = (label) => {
  if (typeof label !== "string") {
    return "";
  }

  return label.trim().toLocaleLowerCase();
};

const isDepartmentLabelValid = (label) => {
  const normalizedLabel = normalizeDepartmentLabel(label);
  if (!normalizedLabel) {
    return false;
  }

  const noDataLabel = normalizeDepartmentLabel(String(i18n.global.t("global.no_data") || ""));
  return normalizedLabel !== noDataLabel;
};

const hasValidDepartmentName = (department) => {
  return isDepartmentLabelValid(department?.name);
};

const isDepartmentArchived = (department) => {
  return (
    department?.archived === true ||
    department?.archived === 1 ||
    department?.archived === "1" ||
    department?.archived === "true"
  );
};

const isDepartmentVisible = (department) => {
  return (
    !isDepartmentArchived(department) &&
    !(
      department?.visible === false ||
      department?.visible === 0 ||
      department?.visible === "0" ||
      department?.visible === "false"
    )
  );
};

const isAccessibleVisibleDepartment = (department, canAccessDepartment = () => true) => {
  return Boolean(department) && canAccessDepartment(department.id) && isDepartmentVisible(department);
};

const isAccessibleVisibleNamedDepartment = (department, canAccessDepartment = () => true) => {
  return isAccessibleVisibleDepartment(department, canAccessDepartment) && hasValidDepartmentName(department);
};

const normalizeDepartmentPriorityOrder = (department) => {
  const parsedPriorityOrder = Number.parseInt(
    String(
      department?.order_priority ??
        department?.orderPriority ??
        department?.priority_order ??
        department?.priorityOrder ??
        ""
    ),
    10
  );

  return Number.isInteger(parsedPriorityOrder) ? parsedPriorityOrder : Number.POSITIVE_INFINITY;
};

const sortByDepartmentPriorityOrder = (items = []) => {
  return [...items].sort((left, right) => {
    const leftPriorityOrder = normalizeDepartmentPriorityOrder(left);
    const rightPriorityOrder = normalizeDepartmentPriorityOrder(right);

    if (leftPriorityOrder !== rightPriorityOrder) {
      return leftPriorityOrder - rightPriorityOrder;
    }

    return 0;
  });
};

const t$j = (key) => i18n.global.t(key);

/**
 * Local departments cache
 * @type {ref<null>}
 */
const departments_cache$1 = ref(null);

/**
 * Get the department name
 * @param id {number}
 * @returns {string}
 */
const getDepartmentName$2 = async (id) => {
  if (departments_cache$1.value === null) {
    departments_cache$1.value = [];
    await SessionUser.objects.departments.get.all().then((departments) => {
      departments_cache$1.value = departments;
    });
  }
  const department = departments_cache$1.value.find((department) => department.id === parseInt(id));
  return department ? department.name : SessionUser.objects.global.language.no_data;
};

/**
 * The Departments object
 */
const Departments = {
  get meta() {
    return {
      title: t$j("common.departments"),
      icon: "fas fa-list",
      description: t$j("objects.departments.description"),
      endpoint: "/departments",
      labels: {
        single: t$j("objects.departments.single"),
        multiple: t$j("objects.departments.multiple"),
      },
    };
  },
  get columns() {
    return {
      id: {
        label: t$j("objects.columns.id"),
        type: "number",
        sortable: true,
        creation: {
          required: false,
        },
      },
      name: {
        label: t$j("common.name"),
        type: "string",
        sortable: true,
        creation: {
          required: true,
        },
      },
      description: {
        label: t$j("common.description"),
        type: "string",
        sortable: true,
        creation: {
          required: false,
        },
      },
      economic_department_id: {
        label: t$j("objects.departments.columns.economic_department"),
        type: "select",
        sortable: true,
        creation: {
          required: true,
        },
        options: async () => {
          return SessionUser.objects.economic_departments.get.all();
        },
      },
      slack_webhook: {
        label: t$j("objects.departments.columns.slack_webhook"),
        type: "string",
        sortable: true,
        creation: {
          required: false,
        },
      },
      dimension: {
        label: t$j("objects.departments.columns.dimension"),
        type: "number",
        sortable: true,
        creation: {
          required: false,
        },
      },
      archived: {
        label: t$j("objects.departments.columns.archived"),
        type: "boolean",
        sortable: true,
        creation: {
          required: false,
        },
      },
      custom_pricing_only: {
        label: t$j("objects.departments.columns.custom_pricing_only"),
        type: "boolean",
        sortable: true,
        creation: {
          required: false,
        },
      },
      longitude: {
        label: t$j("objects.departments.columns.longitude"),
        type: "number",
        sortable: true,
        creation: {
          required: false,
        },
      },
      latitude: {
        label: t$j("objects.departments.columns.latitude"),
        type: "number",
        sortable: true,
        creation: {
          required: false,
        },
      },
      order_priority: {
        label: t$j("objects.columns.sort_order"),
        type: "number",
        sortable: true,
        creation: {
          required: false,
        },
      },
    };
  },
  add: async (name, economic_department_id) => {
    return ObjectsGlobal.add.object(Departments.meta.endpoint, {
      name: name,
      economic_department_id: economic_department_id,
    });
  },
  set: {
    name: async (id, name) => {
      return ObjectsGlobal.set.column(Departments.meta.endpoint, id, "name", name);
    },
    description: async (id, description) => {
      return ObjectsGlobal.set.column(Departments.meta.endpoint, id, "description", description);
    },
    economic_department_id: async (id, economic_department_id) => {
      return ObjectsGlobal.set.column(
        Departments.meta.endpoint,
        id,
        "economic_department_id",
        parseInt(economic_department_id)
      );
    },
    slack_webhook: async (id, slack_webhook) => {
      return ObjectsGlobal.set.column(Departments.meta.endpoint, id, "slack_webhook", slack_webhook);
    },
    dimension: async (id, dimension) => {
      return ObjectsGlobal.set.column(Departments.meta.endpoint, id, "dimension", parseInt(dimension));
    },
    archived: async (id, archived) => {
      return ObjectsGlobal.set.column(Departments.meta.endpoint, id, "archived", ObjectsGlobal.parse.boolean(archived));
    },
    custom_pricing_only: async (id, custom_pricing_only) => {
      return ObjectsGlobal.set.column(
        Departments.meta.endpoint,
        id,
        "custom_pricing_only",
        ObjectsGlobal.parse.boolean(custom_pricing_only)
      );
    },
    longitude: async (id, longitude) => {
      return ObjectsGlobal.set.column(Departments.meta.endpoint, id, "longitude", parseFloat(longitude));
    },
    latitude: async (id, latitude) => {
      return ObjectsGlobal.set.column(Departments.meta.endpoint, id, "latitude", parseFloat(latitude));
    },
    order_priority: async (id, order_priority) => {
      return ObjectsGlobal.set.column(Departments.meta.endpoint, id, "order_priority", parseInt(order_priority));
    },
  },
  get: {
    all: async (options = {}) => {
      return ObjectsGlobal.get.objects(Departments.meta.endpoint, options).then((departments) => {
        return sortByDepartmentPriorityOrder(departments || []);
      });
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(Departments.meta.endpoint, id);
    },
  },
  functions: {},
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(Departments, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(Departments, id, column, value, onAfterSubmit);
  },
};

const _sfc_main$2i = {};
const Departments_default = /*#__PURE__*/_export_sfc(_sfc_main$2i, [['__file',"Departments.vue"]]);

const t$i = (key) => i18n.global.t(key);

    /**
     * The Department Categories object
     */
    const DepartmentCategories = {
      get meta() {
        return {
          title: t$i('objects.department_categories.title'),
          icon: "fas fa-list",
          description: t$i('objects.department_categories.description'),
          endpoint: "/departments/categories",
          labels: {
            single: t$i('objects.department_categories.single'),
            multiple: t$i('objects.department_categories.multiple')
          }
        };
      },
      get columns() {
        return {
          id: {
            label: t$i('objects.columns.id'),
            type: "number",
            sortable: true,
            creation: {
              required: false
            }
          },
          department_id: {
            label: t$i('objects.columns.department_id'),
            type: "select",
            sortable: true,
            creation: {
              required: true
            },
            options: async () => {
              console.log("Getting departments");
              return SessionUser.objects.departments.get.all();
            }
          },
          category_id: {
            label: t$i('objects.columns.category_id'),
            type: "select",
            sortable: true,
            creation: {
              required: true
            },
            options: async () => {
              console.log("Getting categories");
              return SessionUser.objects.categories.get.all();
            }
          },
        };
      },
      add: async (department_id, category_id) => {
        return ObjectsGlobal.add.object(
            DepartmentCategories.meta.endpoint,
            {
              department_id: parseInt(department_id),
              category_id: parseInt(category_id)
            }
        );
      },
      set: {
        department_id: async (id, department_id) => {
          return ObjectsGlobal.set.column(
              DepartmentCategories.meta.endpoint,
              id,
              "department_id",
              parseInt(department_id)
          )
        },
        category_id: async (id, category_id) => {
          return ObjectsGlobal.set.column(
              DepartmentCategories.meta.endpoint,
              id,
              "category_id",
              parseInt(category_id)
          )
        },
      },
      get: {
        all: async () => {
          return ObjectsGlobal.get.objects(DepartmentCategories.meta.endpoint);
        },
        single: async (id) => {
          return ObjectsGlobal.get.object(DepartmentCategories.meta.endpoint, parseInt(id));
        }
      },
      delete: async (id) => {
        return ObjectsGlobal.delete.object(DepartmentCategories.meta.endpoint, parseInt(id));
      },
      functions: {
        showCreateObjectFormDepartment: async (department_id, onAfterSubmit = null) => {
          return ObjectsGlobal.showCreateObjectForm(DepartmentCategories, onAfterSubmit, {department_id: department_id});
        },
        showDeleteObjectForm: (id, onAfterSubmit = null) => {
          return ObjectsGlobal.showDeleteObjectForm(DepartmentCategories, id, onAfterSubmit);
        },
        orderCategories: (categories) => {
          /**
           * Rules:
           * 1. Exterior wash (category id 6) is always first
           * 2. Interior wash (category id 2) is always second
           * 3. All other categories are ordered by amound of products in the category
           */
          let orderedObjects = [];
          let exteriorWash = null;
          let interiorWash = null;
          let otherCategories = [];
          for (let i = 0; i < categories.length; i++) {
            if (categories[i].category.id === 6) {
              exteriorWash = categories[i];
            } else if (categories[i].category.id === 2) {
              interiorWash = categories[i];
            } else {
              otherCategories.push(categories[i]);
            }
          }
          // Sort other categories by amount of products
          otherCategories.sort((a, b) => {
            return b.category.meta.products.length - a.category.meta.products.length;
          });
          // Add exterior wash first
          if (exteriorWash) {
            orderedObjects.push(exteriorWash);
          }
          // Add interior wash second
          if (interiorWash) {
            orderedObjects.push(interiorWash);
          }
          // Add other categories in the order they were received
          orderedObjects = orderedObjects.concat(otherCategories);
          return orderedObjects;
        }
      },
      /**
       * Show the create object form
       * @param onAfterSubmit
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showCreateObjectForm: (onAfterSubmit = null) => {
        return ObjectsGlobal.showCreateObjectForm(DepartmentCategories, onAfterSubmit);
      },
      /**
       * Show the edit object field form
       * @param id
       * @param column
       * @param value
       * @param onAfterSubmit
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
        return ObjectsGlobal.showEditObjectFieldForm(
            DepartmentCategories,
            id,
            column,
            value,
            onAfterSubmit
        );
      }
    };

const _sfc_main$2h = {};
const DepartmentCategories_default = /*#__PURE__*/_export_sfc(_sfc_main$2h, [['__file',"DepartmentCategories.vue"]]);

const t$h = (key) => i18n.global.t(key);

/**
 * Local departments cache
 * @type {ref<null>}
 */
const economic_departments_cache = ref(null);

/**
 * Get the Economic Department name
 * @param id
 * @returns {string}
 */
const getEconomicDepartmentName = (id) => {
  if (economic_departments_cache.value === null) {
    economic_departments_cache.value = [];
    SessionUser.objects.economic_departments.get.all().then((departments) => {
      economic_departments_cache.value = departments;
    });
  }
  const department = economic_departments_cache.value.find((category) => category.departmentNumber === parseInt(id));
  return department ? department.name : SessionUser.objects.global.language.no_data;
};

/**
 * Local departments cache
 * @type {ref<null>}
 */
const departments_cache = ref(null);

/**
 * Get the Department name
 * @param id
 * @returns {string}
 */
const getDepartmentName$1 = (id) => {
  if (departments_cache.value === null) {
    departments_cache.value = [];
    SessionUser.objects.departments.get.all().then((departments) => {
      departments_cache.value = departments;
    });
  }
  const department = departments_cache.value.find((category) => category.id === parseInt(id));
  return department ? department.name : SessionUser.objects.global.language.no_data;
};

/**
 * The Economic Departments object
 */
const EconomicDepartments = {
  get meta() {
    return {
      title: t$h('objects.economic_departments.title'),
      icon: "fas fa-list",
      description: t$h('objects.economic_departments.description'),
      endpoint: "/economic/departments",
      labels: {
        single: t$h('objects.economic_departments.single'),
        multiple: t$h('objects.economic_departments.multiple')
      }
    };
  },
  get columns() {
    return {
      name: {
        label: t$h('common.name'),
        type: "string",
        sortable: true,
        creation: {
          required: true
        }
      },
      departmentNumber: {
        label: t$h('objects.economic_departments.columns.department_number'),
        type: "string",
        sortable: true,
        creation: {
          required: true
        }
      },
    };
  },
  add: async (name, description) => {
    return ObjectsGlobal.add.object(
        EconomicDepartments.meta.endpoint,
        {
          name: name,
          description: description
        }
    );
  },
  set: {
    name: async (id, name) => {
      return ObjectsGlobal.set.column(
        EconomicDepartments.meta.endpoint,
        id,
        "name",
        name
      )
    },
    description: async (id, description) => {
      return ObjectsGlobal.set.column(
        EconomicDepartments.meta.endpoint,
        id,
        "description",
        description
      )
    },
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(EconomicDepartments.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(EconomicDepartments.meta.endpoint, id);
    }
  },
  functions: {
    getEconomicDepartmentName: getEconomicDepartmentName,
    getDepartmentName: getDepartmentName$1,
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(EconomicDepartments, id, onAfterSubmit);
    },
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(EconomicDepartments, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        EconomicDepartments,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$2g = {};
const economicDepartments = /*#__PURE__*/_export_sfc(_sfc_main$2g, [['__file',"economicDepartments.vue"]]);

const t$g = (key) => i18n.global.t(key);

/**
 * Local economic product cache
 * @type {ref<null>}
 */
const economic_products_cache = ref(null);

/**
 * Get the Economic Product name
 * @param id
 * @returns {string}
 */
const getEconomicProductName = (id) => {
  if (economic_products_cache.value === null) {
    economic_products_cache.value = [];
    SessionUser.objects.economic_products.get.all().then((departments) => {
      economic_products_cache.value = departments;
    });
  }
  const object = economic_products_cache.value.find((object) => object.id === parseInt(id));
  return object ? object.name : SessionUser.objects.global.language.no_data;
};

/**
 * The Economic Products object
 */
const EconomicProducts = {
  get meta() {
    return {
      title: t$g('objects.economic_products.title'),
      icon: "fas fa-list",
      description: t$g('objects.economic_products.description'),
      endpoint: "/economic/products",
      labels: {
        single: t$g('objects.economic_products.single'),
        multiple: t$g('objects.economic_products.multiple')
      }
    };
  },
  get columns() {
    return {
      id: {
        label: t$g('objects.columns.id'),
        type: "number",
        sortable: true,
        creation: {
          required: true
        }
      },
      name: {
        label: t$g('common.name'),
        type: "string",
        sortable: true,
        creation: {
          required: true
        }
      },
    };
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(EconomicProducts.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(EconomicProducts.meta.endpoint, id);
    }
  },
  functions: {
    getEconomicProductName: getEconomicProductName,
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(EconomicProducts, id, onAfterSubmit);
    },
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(EconomicProducts, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        EconomicProducts,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$2f = {};
const economicProducts = /*#__PURE__*/_export_sfc(_sfc_main$2f, [['__file',"economicProducts.vue"]]);

const t$f = (key) => i18n.global.t(key);

/**
 * Local roles cache
 * @type {ref<null>}
 */
const roles_cache = ref(null);

/**
 * Get the role name
 * @param id
 * @returns {string}
 */
const getRoleName = (id) => {
  if (roles_cache.value === null) {
    roles_cache.value = [];
    SessionUser.objects.roles.get.all().then((roles) => {
      roles_cache.value = roles;
    });
  }
  const role = roles_cache.value.find((role) => role.id === parseInt(id));
  return role ? role.name : SessionUser.objects.global.language.no_data;
};

/**
 * The Roles object
 */
const Roles = {
  get meta() {
    return {
      title: t$f('objects.roles.title'),
      icon: "fas fa-list",
      description: t$f('objects.roles.description'),
      endpoint: "/roles",
      labels: {
        single: t$f('objects.roles.single'),
        multiple: t$f('objects.roles.multiple')
      }
    };
  },
  get columns() {
    return {
      id: {
        label: t$f('objects.columns.id'),
        type: "number",
        sortable: true,
        creation: {
          required: false
        }
      },
      name: {
        label: t$f('common.name'),
        type: "string",
        sortable: true,
        creation: {
          required: true
        }
      },
      description: {
        label: t$f('common.description'),
        type: "string",
        sortable: true,
        creation: {
          required: true
        }
      },
    };
  },
  add: async (name, description) => {
    return ObjectsGlobal.add.object(
        Roles.meta.endpoint,
        {
          name: name,
          description: description
        }
    );
  },
  set: {
    name: async (id, name) => {
      return ObjectsGlobal.set.column(
        Roles.meta.endpoint,
        id,
        "name",
        name
      )
    },
    description: async (id, description) => {
      return ObjectsGlobal.set.column(
        Roles.meta.endpoint,
        id,
        "description",
        description
      )
    },
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(Roles.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(Roles.meta.endpoint, id);
    }
  },
  functions: {
    getRoleName: getRoleName,
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(Roles, id, onAfterSubmit);
    },
    /**
     * Show the clone object form
     * @param id
     */
    cloneObject: async (id) => {
      return authenticatedRequest("/roles/clone", "POST", {
        id: id
      });
    },
    getLimitedBackofficePermissionTemplates: async () => {
      const response = await authenticatedRequest("/roles/limited-backoffice-permission-templates", "GET");
      return response?.data?.data ?? response?.data ?? [];
    },
    permissions: {
      add: async (roleId, permissionId) => {
        return authenticatedRequest("/roles/permissions", "POST", {
          group_id: parseInt(roleId),
          permission_id: permissionId
        });
      },
      remove: async (roleId, permissionId) => {
        return authenticatedRequest("/roles/permissions?group_id=" + roleId + "&permission_id=" + permissionId, "DELETE");
      }
    }
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(Roles, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        Roles,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$2e = {};
const Roles_default = /*#__PURE__*/_export_sfc(_sfc_main$2e, [['__file',"Roles.vue"]]);

const t$e = (key) => i18n.global.t(key);

    /**
     * The Permissions object
     */
    const Permissions = {
      get meta() {
        return {
          title: t$e('objects.permissions.title'),
          icon: "fas fa-list",
          description: t$e('objects.permissions.description'),
          endpoint: "/permissions",
          labels: {
            single: t$e('objects.permissions.single'),
            multiple: t$e('objects.permissions.multiple')
          }
        };
      },
      get columns() {
        return {
          id: {
            label: t$e('objects.columns.id'),
            type: "number",
            sortable: true,
            creation: {
              required: false
            }
          },
          name: {
            label: t$e('common.name'),
            type: "text",
            sortable: true,
            creation: {
              required: true
            }
          },
          description: {
            label: t$e('common.description'),
            type: "text",
            sortable: true,
            creation: {
              required: true
            }
          },
        };
      },
        get: {
          all: async () => {
            return ObjectsGlobal.get.objects(Permissions.meta.endpoint);
          },
          single: async (id) => {
            return ObjectsGlobal.get.object(Permissions.meta.endpoint, parseInt(id));
          }
        },
    };

const _sfc_main$2d = {};
const Permissions_default = /*#__PURE__*/_export_sfc(_sfc_main$2d, [['__file',"Permissions.vue"]]);

/*! xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
/* vim: set ts=2: */
/*exported XLSX */
/*global process:false, Buffer:false, ArrayBuffer:false, DataView:false, Deno:false */
var XLSX = {};
XLSX.version = '0.18.5';
var current_codepage = 1200, current_ansi = 1252;

var VALID_ANSI = [ 874, 932, 936, 949, 950, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 10000 ];
/* ECMA-376 Part I 18.4.1 charset to codepage mapping */
var CS2CP = ({
	/*::[*/0/*::]*/:    1252, /* ANSI */
	/*::[*/1/*::]*/:   65001, /* DEFAULT */
	/*::[*/2/*::]*/:   65001, /* SYMBOL */
	/*::[*/77/*::]*/:  10000, /* MAC */
	/*::[*/128/*::]*/:   932, /* SHIFTJIS */
	/*::[*/129/*::]*/:   949, /* HANGUL */
	/*::[*/130/*::]*/:  1361, /* JOHAB */
	/*::[*/134/*::]*/:   936, /* GB2312 */
	/*::[*/136/*::]*/:   950, /* CHINESEBIG5 */
	/*::[*/161/*::]*/:  1253, /* GREEK */
	/*::[*/162/*::]*/:  1254, /* TURKISH */
	/*::[*/163/*::]*/:  1258, /* VIETNAMESE */
	/*::[*/177/*::]*/:  1255, /* HEBREW */
	/*::[*/178/*::]*/:  1256, /* ARABIC */
	/*::[*/186/*::]*/:  1257, /* BALTIC */
	/*::[*/204/*::]*/:  1251, /* RUSSIAN */
	/*::[*/222/*::]*/:   874, /* THAI */
	/*::[*/238/*::]*/:  1250, /* EASTEUROPE */
	/*::[*/255/*::]*/:  1252, /* OEM */
	/*::[*/69/*::]*/:   6969  /* MISC */
}/*:any*/);

var set_ansi = function(cp/*:number*/) { if(VALID_ANSI.indexOf(cp) == -1) return; current_ansi = CS2CP[0] = cp; };
function reset_ansi() { set_ansi(1252); }

var set_cp = function(cp/*:number*/) { current_codepage = cp; set_ansi(cp); };
function reset_cp() { set_cp(1200); reset_ansi(); }

function char_codes(data/*:string*/)/*:Array<number>*/ { var o/*:Array<number>*/ = []; for(var i = 0, len = data.length; i < len; ++i) o[i] = data.charCodeAt(i); return o; }

function utf16leread(data/*:string*/)/*:string*/ {
	var o/*:Array<string>*/ = [];
	for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i) + (data.charCodeAt(2*i+1)<<8));
	return o.join("");
}
function utf16beread(data/*:string*/)/*:string*/ {
	var o/*:Array<string>*/ = [];
	for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i+1) + (data.charCodeAt(2*i)<<8));
	return o.join("");
}

var debom = function(data/*:string*/)/*:string*/ {
	var c1 = data.charCodeAt(0), c2 = data.charCodeAt(1);
	if(c1 == 0xFF && c2 == 0xFE) return utf16leread(data.slice(2));
	if(c1 == 0xFE && c2 == 0xFF) return utf16beread(data.slice(2));
	if(c1 == 0xFEFF) return data.slice(1);
	return data;
};

var _getchar = function _gc1(x/*:number*/)/*:string*/ { return String.fromCharCode(x); };
var _getansi = function _ga1(x/*:number*/)/*:string*/ { return String.fromCharCode(x); };

var $cptable;
function set_cptable(cptable) {
	$cptable = cptable;
	set_cp = function(cp/*:number*/) { current_codepage = cp; set_ansi(cp); };
	debom = function(data/*:string*/) {
		if(data.charCodeAt(0) === 0xFF && data.charCodeAt(1) === 0xFE) { return $cptable.utils.decode(1200, char_codes(data.slice(2))); }
		return data;
	};
	_getchar = function _gc2(x/*:number*/)/*:string*/ {
		if(current_codepage === 1200) return String.fromCharCode(x);
		return $cptable.utils.decode(current_codepage, [x&255,x>>8])[0];
	};
	_getansi = function _ga2(x/*:number*/)/*:string*/ {
		return $cptable.utils.decode(current_ansi, [x])[0];
	};
	cpdoit();
}
var DENSE = null;
var DIF_XL = true;
var Base64_map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function Base64_encode(input) {
  var o = "";
  var c1 = 0, c2 = 0, c3 = 0, e1 = 0, e2 = 0, e3 = 0, e4 = 0;
  for (var i = 0; i < input.length; ) {
    c1 = input.charCodeAt(i++);
    e1 = c1 >> 2;
    c2 = input.charCodeAt(i++);
    e2 = (c1 & 3) << 4 | c2 >> 4;
    c3 = input.charCodeAt(i++);
    e3 = (c2 & 15) << 2 | c3 >> 6;
    e4 = c3 & 63;
    if (isNaN(c2)) {
      e3 = e4 = 64;
    } else if (isNaN(c3)) {
      e4 = 64;
    }
    o += Base64_map.charAt(e1) + Base64_map.charAt(e2) + Base64_map.charAt(e3) + Base64_map.charAt(e4);
  }
  return o;
}
function Base64_decode(input) {
  var o = "";
  var c1 = 0, c2 = 0, c3 = 0, e1 = 0, e2 = 0, e3 = 0, e4 = 0;
  input = input.replace(/[^\w\+\/\=]/g, "");
  for (var i = 0; i < input.length; ) {
    e1 = Base64_map.indexOf(input.charAt(i++));
    e2 = Base64_map.indexOf(input.charAt(i++));
    c1 = e1 << 2 | e2 >> 4;
    o += String.fromCharCode(c1);
    e3 = Base64_map.indexOf(input.charAt(i++));
    c2 = (e2 & 15) << 4 | e3 >> 2;
    if (e3 !== 64) {
      o += String.fromCharCode(c2);
    }
    e4 = Base64_map.indexOf(input.charAt(i++));
    c3 = (e3 & 3) << 6 | e4;
    if (e4 !== 64) {
      o += String.fromCharCode(c3);
    }
  }
  return o;
}
var has_buf = /*#__PURE__*/(function() { return typeof Buffer !== 'undefined' && typeof process !== 'undefined' && typeof process.versions !== 'undefined' && !!process.versions.node; })();

var Buffer_from = /*#__PURE__*/(function() {
	if(typeof Buffer !== 'undefined') {
		var nbfs = !Buffer.from;
		if(!nbfs) try { Buffer.from("foo", "utf8"); } catch(e) { nbfs = true; }
		return nbfs ? function(buf, enc) { return (enc) ? new Buffer(buf, enc) : new Buffer(buf); } : Buffer.from.bind(Buffer);
	}
	return function() {};
})();


function new_raw_buf(len/*:number*/) {
	/* jshint -W056 */
	if(has_buf) return Buffer.alloc ? Buffer.alloc(len) : new Buffer(len);
	return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
	/* jshint +W056 */
}

function new_unsafe_buf(len/*:number*/) {
	/* jshint -W056 */
	if(has_buf) return Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : new Buffer(len);
	return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
	/* jshint +W056 */
}

var s2a = function s2a(s/*:string*/)/*:any*/ {
	if(has_buf) return Buffer_from(s, "binary");
	return s.split("").map(function(x/*:string*/)/*:number*/{ return x.charCodeAt(0) & 0xff; });
};

function s2ab(s/*:string*/)/*:any*/ {
	if(typeof ArrayBuffer === 'undefined') return s2a(s);
	var buf = new ArrayBuffer(s.length), view = new Uint8Array(buf);
	for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
	return buf;
}

function a2s(data/*:any*/)/*:string*/ {
	if(Array.isArray(data)) return data.map(function(c) { return String.fromCharCode(c); }).join("");
	var o/*:Array<string>*/ = []; for(var i = 0; i < data.length; ++i) o[i] = String.fromCharCode(data[i]); return o.join("");
}

function a2u(data/*:Array<number>*/)/*:Uint8Array*/ {
	if(typeof Uint8Array === 'undefined') throw new Error("Unsupported");
	return new Uint8Array(data);
}

function ab2a(data/*:ArrayBuffer|Uint8Array*/)/*:Array<number>*/ {
	if(typeof ArrayBuffer == 'undefined') throw new Error("Unsupported");
	if(data instanceof ArrayBuffer) return ab2a(new Uint8Array(data));
	/*:: if(data instanceof ArrayBuffer) throw new Error("unreachable"); */
	var o = new Array(data.length);
	for(var i = 0; i < data.length; ++i) o[i] = data[i];
	return o;
}

var bconcat = has_buf ? function(bufs) { return Buffer.concat(bufs.map(function(buf) { return Buffer.isBuffer(buf) ? buf : Buffer_from(buf); })); } : function(bufs) {
	if(typeof Uint8Array !== "undefined") {
		var i = 0, maxlen = 0;
		for(i = 0; i < bufs.length; ++i) maxlen += bufs[i].length;
		var o = new Uint8Array(maxlen);
		var len = 0;
		for(i = 0, maxlen = 0; i < bufs.length; maxlen += len, ++i) {
			len = bufs[i].length;
			if(bufs[i] instanceof Uint8Array) o.set(bufs[i], maxlen);
			else if(typeof bufs[i] == "string") { throw "wtf"; }
			else o.set(new Uint8Array(bufs[i]), maxlen);
		}
		return o;
	}
	return [].concat.apply([], bufs.map(function(buf) { return Array.isArray(buf) ? buf : [].slice.call(buf); }));
};

function utf8decode(content/*:string*/) {
	var out = [], widx = 0, L = content.length + 250;
	var o = new_raw_buf(content.length + 255);
	for(var ridx = 0; ridx < content.length; ++ridx) {
		var c = content.charCodeAt(ridx);
		if(c < 0x80) o[widx++] = c;
		else if(c < 0x800) {
			o[widx++] = (192|((c>>6)&31));
			o[widx++] = (128|(c&63));
		} else if(c >= 0xD800 && c < 0xE000) {
			c = (c&1023)+64;
			var d = content.charCodeAt(++ridx)&1023;
			o[widx++] = (240|((c>>8)&7));
			o[widx++] = (128|((c>>2)&63));
			o[widx++] = (128|((d>>6)&15)|((c&3)<<4));
			o[widx++] = (128|(d&63));
		} else {
			o[widx++] = (224|((c>>12)&15));
			o[widx++] = (128|((c>>6)&63));
			o[widx++] = (128|(c&63));
		}
		if(widx > L) {
			out.push(o.slice(0, widx));
			widx = 0;
			o = new_raw_buf(65535);
			L = 65530;
		}
	}
	out.push(o.slice(0, widx));
	return bconcat(out);
}

var chr0 = /\u0000/g, chr1 = /[\u0001-\u0006]/g;
/*::
declare type Block = any;
declare type BufArray = {
	newblk(sz:number):Block;
	next(sz:number):Block;
	end():any;
	push(buf:Block):void;
};

type RecordHopperCB = {(d:any, Rn:string, RT:number):?boolean;};

type EvertType = {[string]:string};
type EvertNumType = {[string]:number};
type EvertArrType = {[string]:Array<string>};

type StringConv = {(string):string};

*/
/* ssf.js (C) 2013-present SheetJS -- http://sheetjs.com */
/*jshint -W041 */
function _strrev(x/*:string*/)/*:string*/ { var o = "", i = x.length-1; while(i>=0) o += x.charAt(i--); return o; }
function pad0(v/*:any*/,d/*:number*/)/*:string*/{var t=""+v; return t.length>=d?t:fill$1('0',d-t.length)+t;}
function pad_(v/*:any*/,d/*:number*/)/*:string*/{var t=""+v;return t.length>=d?t:fill$1(' ',d-t.length)+t;}
function rpad_(v/*:any*/,d/*:number*/)/*:string*/{var t=""+v; return t.length>=d?t:t+fill$1(' ',d-t.length);}
function pad0r1(v/*:any*/,d/*:number*/)/*:string*/{var t=""+Math.round(v); return t.length>=d?t:fill$1('0',d-t.length)+t;}
function pad0r2(v/*:any*/,d/*:number*/)/*:string*/{var t=""+v; return t.length>=d?t:fill$1('0',d-t.length)+t;}
var p2_32 = /*#__PURE__*/Math.pow(2,32);
function pad0r(v/*:any*/,d/*:number*/)/*:string*/{if(v>p2_32||v<-p2_32) return pad0r1(v,d); var i = Math.round(v); return pad0r2(i,d); }
/* yes, in 2022 this is still faster than string compare */
function SSF_isgeneral(s/*:string*/, i/*:?number*/)/*:boolean*/ { i = i || 0; return s.length >= 7 + i && (s.charCodeAt(i)|32) === 103 && (s.charCodeAt(i+1)|32) === 101 && (s.charCodeAt(i+2)|32) === 110 && (s.charCodeAt(i+3)|32) === 101 && (s.charCodeAt(i+4)|32) === 114 && (s.charCodeAt(i+5)|32) === 97 && (s.charCodeAt(i+6)|32) === 108; }
var days/*:Array<Array<string> >*/ = [
	['Sun', 'Sunday'],
	['Mon', 'Monday'],
	['Tue', 'Tuesday'],
	['Wed', 'Wednesday'],
	['Thu', 'Thursday'],
	['Fri', 'Friday'],
	['Sat', 'Saturday']
];
var months/*:Array<Array<string> >*/ = [
	['J', 'Jan', 'January'],
	['F', 'Feb', 'February'],
	['M', 'Mar', 'March'],
	['A', 'Apr', 'April'],
	['M', 'May', 'May'],
	['J', 'Jun', 'June'],
	['J', 'Jul', 'July'],
	['A', 'Aug', 'August'],
	['S', 'Sep', 'September'],
	['O', 'Oct', 'October'],
	['N', 'Nov', 'November'],
	['D', 'Dec', 'December']
];
function SSF_init_table(t/*:any*/) {
	if(!t) t = {};
	t[0]=  'General';
	t[1]=  '0';
	t[2]=  '0.00';
	t[3]=  '#,##0';
	t[4]=  '#,##0.00';
	t[9]=  '0%';
	t[10]= '0.00%';
	t[11]= '0.00E+00';
	t[12]= '# ?/?';
	t[13]= '# ??/??';
	t[14]= 'm/d/yy';
	t[15]= 'd-mmm-yy';
	t[16]= 'd-mmm';
	t[17]= 'mmm-yy';
	t[18]= 'h:mm AM/PM';
	t[19]= 'h:mm:ss AM/PM';
	t[20]= 'h:mm';
	t[21]= 'h:mm:ss';
	t[22]= 'm/d/yy h:mm';
	t[37]= '#,##0 ;(#,##0)';
	t[38]= '#,##0 ;[Red](#,##0)';
	t[39]= '#,##0.00;(#,##0.00)';
	t[40]= '#,##0.00;[Red](#,##0.00)';
	t[45]= 'mm:ss';
	t[46]= '[h]:mm:ss';
	t[47]= 'mmss.0';
	t[48]= '##0.0E+0';
	t[49]= '@';
	t[56]= '"上午/下午 "hh"時"mm"分"ss"秒 "';
	return t;
}
/* repeated to satiate webpack */
var table_fmt = {
	0:  'General',
	1:  '0',
	2:  '0.00',
	3:  '#,##0',
	4:  '#,##0.00',
	9:  '0%',
	10: '0.00%',
	11: '0.00E+00',
	12: '# ?/?',
	13: '# ??/??',
	14: 'm/d/yy',
	15: 'd-mmm-yy',
	16: 'd-mmm',
	17: 'mmm-yy',
	18: 'h:mm AM/PM',
	19: 'h:mm:ss AM/PM',
	20: 'h:mm',
	21: 'h:mm:ss',
	22: 'm/d/yy h:mm',
	37: '#,##0 ;(#,##0)',
	38: '#,##0 ;[Red](#,##0)',
	39: '#,##0.00;(#,##0.00)',
	40: '#,##0.00;[Red](#,##0.00)',
	45: 'mm:ss',
	46: '[h]:mm:ss',
	47: 'mmss.0',
	48: '##0.0E+0',
	49: '@',
	56: '"上午/下午 "hh"時"mm"分"ss"秒 "'
};

/* Defaults determined by systematically testing in Excel 2019 */

/* These formats appear to default to other formats in the table */
var SSF_default_map = {
	5:  37, 6:  38, 7:  39, 8:  40,         //  5 -> 37 ...  8 -> 40

	23:  0, 24:  0, 25:  0, 26:  0,         // 23 ->  0 ... 26 ->  0

	27: 14, 28: 14, 29: 14, 30: 14, 31: 14, // 27 -> 14 ... 31 -> 14

	50: 14, 51: 14, 52: 14, 53: 14, 54: 14, // 50 -> 14 ... 58 -> 14
	55: 14, 56: 14, 57: 14, 58: 14,
	59:  1, 60:  2, 61:  3, 62:  4,         // 59 ->  1 ... 62 ->  4

	67:  9, 68: 10,                         // 67 ->  9 ... 68 -> 10
	69: 12, 70: 13, 71: 14,                 // 69 -> 12 ... 71 -> 14
	72: 14, 73: 15, 74: 16, 75: 17,         // 72 -> 14 ... 75 -> 17
	76: 20, 77: 21, 78: 22,                 // 76 -> 20 ... 78 -> 22
	79: 45, 80: 46, 81: 47,                 // 79 -> 45 ... 81 -> 47
	82: 0                                   // 82 ->  0 ... 65536 -> 0 (omitted)
};


/* These formats technically refer to Accounting formats with no equivalent */
var SSF_default_str = {
	//  5 -- Currency,   0 decimal, black negative
	5:  '"$"#,##0_);\\("$"#,##0\\)',
	63: '"$"#,##0_);\\("$"#,##0\\)',

	//  6 -- Currency,   0 decimal, red   negative
	6:  '"$"#,##0_);[Red]\\("$"#,##0\\)',
	64: '"$"#,##0_);[Red]\\("$"#,##0\\)',

	//  7 -- Currency,   2 decimal, black negative
	7:  '"$"#,##0.00_);\\("$"#,##0.00\\)',
	65: '"$"#,##0.00_);\\("$"#,##0.00\\)',

	//  8 -- Currency,   2 decimal, red   negative
	8:  '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
	66: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',

	// 41 -- Accounting, 0 decimal, No Symbol
	41: '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',

	// 42 -- Accounting, 0 decimal, $  Symbol
	42: '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)',

	// 43 -- Accounting, 2 decimal, No Symbol
	43: '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',

	// 44 -- Accounting, 2 decimal, $  Symbol
	44: '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)'
};

function SSF_frac(x/*:number*/, D/*:number*/, mixed/*:?boolean*/)/*:Array<number>*/ {
	var sgn = x < 0 ? -1 : 1;
	var B = x * sgn;
	var P_2 = 0, P_1 = 1, P = 0;
	var Q_2 = 1, Q_1 = 0, Q = 0;
	var A = Math.floor(B);
	while(Q_1 < D) {
		A = Math.floor(B);
		P = A * P_1 + P_2;
		Q = A * Q_1 + Q_2;
		if((B - A) < 0.00000005) break;
		B = 1 / (B - A);
		P_2 = P_1; P_1 = P;
		Q_2 = Q_1; Q_1 = Q;
	}
	if(Q > D) { if(Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } }
	if(!mixed) return [0, sgn * P, Q];
	var q = Math.floor(sgn * P/Q);
	return [q, sgn*P - q*Q, Q];
}
function SSF_parse_date_code(v/*:number*/,opts/*:?any*/,b2/*:?boolean*/) {
	if(v > 2958465 || v < 0) return null;
	var date = (v|0), time = Math.floor(86400 * (v - date)), dow=0;
	var dout=[];
	var out={D:date, T:time, u:86400*(v-date)-time,y:0,m:0,d:0,H:0,M:0,S:0,q:0};
	if(Math.abs(out.u) < 1e-6) out.u = 0;
	if(opts && opts.date1904) date += 1462;
	if(out.u > 0.9999) {
		out.u = 0;
		if(++time == 86400) { out.T = time = 0; ++date; ++out.D; }
	}
	if(date === 60) {dout = b2 ? [1317,10,29] : [1900,2,29]; dow=3;}
	else if(date === 0) {dout = b2 ? [1317,8,29] : [1900,1,0]; dow=6;}
	else {
		if(date > 60) --date;
		/* 1 = Jan 1 1900 in Gregorian */
		var d = new Date(1900, 0, 1);
		d.setDate(d.getDate() + date - 1);
		dout = [d.getFullYear(), d.getMonth()+1,d.getDate()];
		dow = d.getDay();
		if(date < 60) dow = (dow + 6) % 7;
		if(b2) dow = SSF_fix_hijri(d, dout);
	}
	out.y = dout[0]; out.m = dout[1]; out.d = dout[2];
	out.S = time % 60; time = Math.floor(time / 60);
	out.M = time % 60; time = Math.floor(time / 60);
	out.H = time;
	out.q = dow;
	return out;
}
var SSFbasedate = /*#__PURE__*/new Date(1899, 11, 31, 0, 0, 0);
var SSFdnthresh = /*#__PURE__*/SSFbasedate.getTime();
var SSFbase1904 = /*#__PURE__*/new Date(1900, 2, 1, 0, 0, 0);
function datenum_local(v/*:Date*/, date1904/*:?boolean*/)/*:number*/ {
	var epoch = /*#__PURE__*/v.getTime();
	if(date1904) epoch -= 1461*24*60*60*1000;
	else if(v >= SSFbase1904) epoch += 24*60*60*1000;
	return (epoch - (SSFdnthresh + (/*#__PURE__*/v.getTimezoneOffset() - /*#__PURE__*/SSFbasedate.getTimezoneOffset()) * 60000)) / (24 * 60 * 60 * 1000);
}
/* ECMA-376 18.8.30 numFmt*/
/* Note: `toPrecision` uses standard form when prec > E and E >= -6 */
/* exponent >= -9 and <= 9 */
function SSF_strip_decimal(o/*:string*/)/*:string*/ {
	return (o.indexOf(".") == -1) ? o : o.replace(/(?:\.0*|(\.\d*[1-9])0+)$/, "$1");
}

/* General Exponential always shows 2 digits exp and trims the mantissa */
function SSF_normalize_exp(o/*:string*/)/*:string*/ {
	if(o.indexOf("E") == -1) return o;
	return o.replace(/(?:\.0*|(\.\d*[1-9])0+)[Ee]/,"$1E").replace(/(E[+-])(\d)$/,"$10$2");
}

/* exponent >= -9 and <= 9 */
function SSF_small_exp(v/*:number*/)/*:string*/ {
	var w = (v<0?12:11);
	var o = SSF_strip_decimal(v.toFixed(12)); if(o.length <= w) return o;
	o = v.toPrecision(10); if(o.length <= w) return o;
	return v.toExponential(5);
}

/* exponent >= 11 or <= -10 likely exponential */
function SSF_large_exp(v/*:number*/)/*:string*/ {
	var o = SSF_strip_decimal(v.toFixed(11));
	return (o.length > (v<0?12:11) || o === "0" || o === "-0") ? v.toPrecision(6) : o;
}

function SSF_general_num(v/*:number*/)/*:string*/ {
	var V = Math.floor(Math.log(Math.abs(v))*Math.LOG10E), o;

	if(V >= -4 && V <= -1) o = v.toPrecision(10+V);
	else if(Math.abs(V) <= 9) o = SSF_small_exp(v);
	else if(V === 10) o = v.toFixed(10).substr(0,12);
	else o = SSF_large_exp(v);

	return SSF_strip_decimal(SSF_normalize_exp(o.toUpperCase()));
}


/*
	"General" rules:
	- text is passed through ("@")
	- booleans are rendered as TRUE/FALSE
	- "up to 11 characters" displayed for numbers
	- Default date format (code 14) used for Dates

	The longest 32-bit integer text is "-2147483648", exactly 11 chars
	TODO: technically the display depends on the width of the cell
*/
function SSF_general(v/*:any*/, opts/*:any*/) {
	switch(typeof v) {
		case 'string': return v;
		case 'boolean': return v ? "TRUE" : "FALSE";
		case 'number': return (v|0) === v ? v.toString(10) : SSF_general_num(v);
		case 'undefined': return "";
		case 'object':
			if(v == null) return "";
			if(v instanceof Date) return SSF_format(14, datenum_local(v, opts && opts.date1904), opts);
	}
	throw new Error("unsupported value in General format: " + v);
}

function SSF_fix_hijri(date/*:Date*/, o/*:[number, number, number]*/) {
  /* TODO: properly adjust y/m/d and  */
  o[0] -= 581;
  var dow = date.getDay();
  if(date < 60) dow = (dow + 6) % 7;
  return dow;
}
//var THAI_DIGITS = "\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59".split("");
function SSF_write_date(type/*:number*/, fmt/*:string*/, val, ss0/*:?number*/)/*:string*/ {
	var o="", ss=0, tt=0, y = val.y, out, outl = 0;
	switch(type) {
		case 98: /* 'b' buddhist year */
			y = val.y + 543;
			/* falls through */
		case 121: /* 'y' year */
		switch(fmt.length) {
			case 1: case 2: out = y % 100; outl = 2; break;
			default: out = y % 10000; outl = 4; break;
		} break;
		case 109: /* 'm' month */
		switch(fmt.length) {
			case 1: case 2: out = val.m; outl = fmt.length; break;
			case 3: return months[val.m-1][1];
			case 5: return months[val.m-1][0];
			default: return months[val.m-1][2];
		} break;
		case 100: /* 'd' day */
		switch(fmt.length) {
			case 1: case 2: out = val.d; outl = fmt.length; break;
			case 3: return days[val.q][0];
			default: return days[val.q][1];
		} break;
		case 104: /* 'h' 12-hour */
		switch(fmt.length) {
			case 1: case 2: out = 1+(val.H+11)%12; outl = fmt.length; break;
			default: throw 'bad hour format: ' + fmt;
		} break;
		case 72: /* 'H' 24-hour */
		switch(fmt.length) {
			case 1: case 2: out = val.H; outl = fmt.length; break;
			default: throw 'bad hour format: ' + fmt;
		} break;
		case 77: /* 'M' minutes */
		switch(fmt.length) {
			case 1: case 2: out = val.M; outl = fmt.length; break;
			default: throw 'bad minute format: ' + fmt;
		} break;
		case 115: /* 's' seconds */
			if(fmt != 's' && fmt != 'ss' && fmt != '.0' && fmt != '.00' && fmt != '.000') throw 'bad second format: ' + fmt;
			if(val.u === 0 && (fmt == "s" || fmt == "ss")) return pad0(val.S, fmt.length);
			/*::if(!ss0) ss0 = 0; */
			if(ss0 >= 2) tt = ss0 === 3 ? 1000 : 100;
			else tt = ss0 === 1 ? 10 : 1;
			ss = Math.round((tt)*(val.S + val.u));
			if(ss >= 60*tt) ss = 0;
			if(fmt === 's') return ss === 0 ? "0" : ""+ss/tt;
			o = pad0(ss,2 + ss0);
			if(fmt === 'ss') return o.substr(0,2);
			return "." + o.substr(2,fmt.length-1);
		case 90: /* 'Z' absolute time */
		switch(fmt) {
			case '[h]': case '[hh]': out = val.D*24+val.H; break;
			case '[m]': case '[mm]': out = (val.D*24+val.H)*60+val.M; break;
			case '[s]': case '[ss]': out = ((val.D*24+val.H)*60+val.M)*60+Math.round(val.S+val.u); break;
			default: throw 'bad abstime format: ' + fmt;
		} outl = fmt.length === 3 ? 1 : 2; break;
		case 101: /* 'e' era */
			out = y; outl = 1; break;
	}
	var outstr = outl > 0 ? pad0(out, outl) : "";
	return outstr;
}


/*jshint -W086 */
/*jshint +W086 */
function commaify(s/*:string*/)/*:string*/ {
	var w = 3;
	if(s.length <= w) return s;
	var j = (s.length % w), o = s.substr(0,j);
	for(; j!=s.length; j+=w) o+=(o.length > 0 ? "," : "") + s.substr(j,w);
	return o;
}
var pct1 = /%/g;
function write_num_pct(type/*:string*/, fmt/*:string*/, val/*:number*/)/*:string*/{
	var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
	return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill$1("%",mul);
}

function write_num_cm(type/*:string*/, fmt/*:string*/, val/*:number*/)/*:string*/{
	var idx = fmt.length - 1;
	while(fmt.charCodeAt(idx-1) === 44) --idx;
	return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
}

function write_num_exp(fmt/*:string*/, val/*:number*/)/*:string*/{
	var o/*:string*/;
	var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
	if(fmt.match(/^#+0.0E\+0$/)) {
		if(val == 0) return "0.0E+0";
		else if(val < 0) return "-" + write_num_exp(fmt, -val);
		var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
		var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
		if(ee < 0) ee += period;
		o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
		if(o.indexOf("e") === -1) {
			var fakee = Math.floor(Math.log(val)*Math.LOG10E);
			if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
			else o += "E+" + (fakee - ee);
			while(o.substr(0,2) === "0.") {
				o = o.charAt(0) + o.substr(2,period) + "." + o.substr(2+period);
				o = o.replace(/^0+([1-9])/,"$1").replace(/^0+\./,"0.");
			}
			o = o.replace(/\+-/,"-");
		}
		o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
	} else o = val.toExponential(idx);
	if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
	if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
	return o.replace("e","E");
}
var frac1 = /# (\?+)( ?)\/( ?)(\d+)/;
function write_num_f1(r/*:Array<string>*/, aval/*:number*/, sign/*:string*/)/*:string*/ {
	var den = parseInt(r[4],10), rr = Math.round(aval * den), base = Math.floor(rr/den);
	var myn = (rr - base*den), myd = den;
	return sign + (base === 0 ? "" : ""+base) + " " + (myn === 0 ? fill$1(" ", r[1].length + 1 + r[4].length) : pad_(myn,r[1].length) + r[2] + "/" + r[3] + pad0(myd,r[4].length));
}
function write_num_f2(r/*:Array<string>*/, aval/*:number*/, sign/*:string*/)/*:string*/ {
	return sign + (aval === 0 ? "" : ""+aval) + fill$1(" ", r[1].length + 2 + r[4].length);
}
var dec1 = /^#*0*\.([0#]+)/;
var closeparen = /\).*[0#]/;
var phone = /\(###\) ###\\?-####/;
function hashq(str/*:string*/)/*:string*/ {
	var o = "", cc;
	for(var i = 0; i != str.length; ++i) switch((cc=str.charCodeAt(i))) {
		case 35: break;
		case 63: o+= " "; break;
		case 48: o+= "0"; break;
		default: o+= String.fromCharCode(cc);
	}
	return o;
}
function rnd(val/*:number*/, d/*:number*/)/*:string*/ { var dd = Math.pow(10,d); return ""+(Math.round(val * dd)/dd); }
function dec(val/*:number*/, d/*:number*/)/*:number*/ {
	var _frac = val - Math.floor(val), dd = Math.pow(10,d);
	if (d < ('' + Math.round(_frac * dd)).length) return 0;
	return Math.round(_frac * dd);
}
function carry(val/*:number*/, d/*:number*/)/*:number*/ {
	if (d < ('' + Math.round((val-Math.floor(val))*Math.pow(10,d))).length) {
		return 1;
	}
	return 0;
}
function flr(val/*:number*/)/*:string*/ {
	if(val < 2147483647 && val > -2147483648) return ""+(val >= 0 ? (val|0) : (val-1|0));
	return ""+Math.floor(val);
}
function write_num_flt(type/*:string*/, fmt/*:string*/, val/*:number*/)/*:string*/ {
	if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
		var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
		if(val >= 0) return write_num_flt('n', ffmt, val);
		return '(' + write_num_flt('n', ffmt, -val) + ')';
	}
	if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm(type, fmt, val);
	if(fmt.indexOf('%') !== -1) return write_num_pct(type, fmt, val);
	if(fmt.indexOf('E') !== -1) return write_num_exp(fmt, val);
	if(fmt.charCodeAt(0) === 36) return "$"+write_num_flt(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
	var o;
	var r/*:?Array<string>*/, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
	if(fmt.match(/^00+$/)) return sign + pad0r(aval,fmt.length);
	if(fmt.match(/^[#?]+$/)) {
		o = pad0r(val,0); if(o === "0") o = "";
		return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
	}
	if((r = fmt.match(frac1))) return write_num_f1(r, aval, sign);
	if(fmt.match(/^#+0+$/)) return sign + pad0r(aval,fmt.length - fmt.indexOf("0"));
	if((r = fmt.match(dec1))) {
		o = rnd(val, r[1].length).replace(/^([^\.]+)$/,"$1."+hashq(r[1])).replace(/\.$/,"."+hashq(r[1])).replace(/\.(\d*)$/,function($$, $1) { return "." + $1 + fill$1("0", hashq(/*::(*/r/*::||[""])*/[1]).length-$1.length); });
		return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
	}
	fmt = fmt.replace(/^#+([0.])/, "$1");
	if((r = fmt.match(/^(0*)\.(#*)$/))) {
		return sign + rnd(aval, r[2].length).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
	}
	if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify(pad0r(aval,0));
	if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
		return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(""+(Math.floor(val) + carry(val, r[1].length))) + "." + pad0(dec(val, r[1].length),r[1].length);
	}
	if((r = fmt.match(/^#,#*,#0/))) return write_num_flt(type,fmt.replace(/^#,#*,/,""),val);
	if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
		o = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g,""), val));
		ri = 0;
		return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
	}
	if(fmt.match(phone)) {
		o = write_num_flt(type, "##########", val);
		return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
	}
	var oa = "";
	if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
		ri = Math.min(/*::String(*/r[4]/*::)*/.length,7);
		ff = SSF_frac(aval, Math.pow(10,ri)-1, false);
		o = "" + sign;
		oa = write_num("n", /*::String(*/r[1]/*::)*/, ff[1]);
		if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
		o += oa + /*::String(*/r[2]/*::)*/ + "/" + /*::String(*/r[3]/*::)*/;
		oa = rpad_(ff[2],ri);
		if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
		o += oa;
		return o;
	}
	if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
		ri = Math.min(Math.max(r[1].length, r[4].length),7);
		ff = SSF_frac(aval, Math.pow(10,ri)-1, true);
		return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill$1(" ", 2*ri+1 + r[2].length + r[3].length));
	}
	if((r = fmt.match(/^[#0?]+$/))) {
		o = pad0r(val, 0);
		if(fmt.length <= o.length) return o;
		return hashq(fmt.substr(0,fmt.length-o.length)) + o;
	}
	if((r = fmt.match(/^([#0?]+)\.([#0]+)$/))) {
		o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
		ri = o.indexOf(".");
		var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
		return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
	}
	if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
		ri = dec(val, r[1].length);
		return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(flr(val)).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(ri,r[1].length);
	}
	switch(fmt) {
		case "###,##0.00": return write_num_flt(type, "#,##0.00", val);
		case "###,###":
		case "##,###":
		case "#,###": var x = commaify(pad0r(aval,0)); return x !== "0" ? sign + x : "";
		case "###,###.00": return write_num_flt(type, "###,##0.00",val).replace(/^0\./,".");
		case "#,###.00": return write_num_flt(type, "#,##0.00",val).replace(/^0\./,".");
		default:
	}
	throw new Error("unsupported format |" + fmt + "|");
}
function write_num_cm2(type/*:string*/, fmt/*:string*/, val/*:number*/)/*:string*/{
	var idx = fmt.length - 1;
	while(fmt.charCodeAt(idx-1) === 44) --idx;
	return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
}
function write_num_pct2(type/*:string*/, fmt/*:string*/, val/*:number*/)/*:string*/{
	var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
	return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill$1("%",mul);
}
function write_num_exp2(fmt/*:string*/, val/*:number*/)/*:string*/{
	var o/*:string*/;
	var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
	if(fmt.match(/^#+0.0E\+0$/)) {
		if(val == 0) return "0.0E+0";
		else if(val < 0) return "-" + write_num_exp2(fmt, -val);
		var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
		var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
		if(ee < 0) ee += period;
		o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
		if(!o.match(/[Ee]/)) {
			var fakee = Math.floor(Math.log(val)*Math.LOG10E);
			if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
			else o += "E+" + (fakee - ee);
			o = o.replace(/\+-/,"-");
		}
		o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
	} else o = val.toExponential(idx);
	if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
	if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
	return o.replace("e","E");
}
function write_num_int(type/*:string*/, fmt/*:string*/, val/*:number*/)/*:string*/ {
	if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
		var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
		if(val >= 0) return write_num_int('n', ffmt, val);
		return '(' + write_num_int('n', ffmt, -val) + ')';
	}
	if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm2(type, fmt, val);
	if(fmt.indexOf('%') !== -1) return write_num_pct2(type, fmt, val);
	if(fmt.indexOf('E') !== -1) return write_num_exp2(fmt, val);
	if(fmt.charCodeAt(0) === 36) return "$"+write_num_int(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
	var o;
	var r/*:?Array<string>*/, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
	if(fmt.match(/^00+$/)) return sign + pad0(aval,fmt.length);
	if(fmt.match(/^[#?]+$/)) {
		o = (""+val); if(val === 0) o = "";
		return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
	}
	if((r = fmt.match(frac1))) return write_num_f2(r, aval, sign);
	if(fmt.match(/^#+0+$/)) return sign + pad0(aval,fmt.length - fmt.indexOf("0"));
	if((r = fmt.match(dec1))) {
		/*:: if(!Array.isArray(r)) throw new Error("unreachable"); */
		o = (""+val).replace(/^([^\.]+)$/,"$1."+hashq(r[1])).replace(/\.$/,"."+hashq(r[1]));
		o = o.replace(/\.(\d*)$/,function($$, $1) {
		/*:: if(!Array.isArray(r)) throw new Error("unreachable"); */
			return "." + $1 + fill$1("0", hashq(r[1]).length-$1.length); });
		return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
	}
	fmt = fmt.replace(/^#+([0.])/, "$1");
	if((r = fmt.match(/^(0*)\.(#*)$/))) {
		return sign + (""+aval).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
	}
	if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify((""+aval));
	if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
		return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify((""+val)) + "." + fill$1('0',r[1].length);
	}
	if((r = fmt.match(/^#,#*,#0/))) return write_num_int(type,fmt.replace(/^#,#*,/,""),val);
	if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
		o = _strrev(write_num_int(type, fmt.replace(/[\\-]/g,""), val));
		ri = 0;
		return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
	}
	if(fmt.match(phone)) {
		o = write_num_int(type, "##########", val);
		return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
	}
	var oa = "";
	if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
		ri = Math.min(/*::String(*/r[4]/*::)*/.length,7);
		ff = SSF_frac(aval, Math.pow(10,ri)-1, false);
		o = "" + sign;
		oa = write_num("n", /*::String(*/r[1]/*::)*/, ff[1]);
		if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
		o += oa + /*::String(*/r[2]/*::)*/ + "/" + /*::String(*/r[3]/*::)*/;
		oa = rpad_(ff[2],ri);
		if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
		o += oa;
		return o;
	}
	if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
		ri = Math.min(Math.max(r[1].length, r[4].length),7);
		ff = SSF_frac(aval, Math.pow(10,ri)-1, true);
		return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill$1(" ", 2*ri+1 + r[2].length + r[3].length));
	}
	if((r = fmt.match(/^[#0?]+$/))) {
		o = "" + val;
		if(fmt.length <= o.length) return o;
		return hashq(fmt.substr(0,fmt.length-o.length)) + o;
	}
	if((r = fmt.match(/^([#0]+)\.([#0]+)$/))) {
		o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
		ri = o.indexOf(".");
		var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
		return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
	}
	if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
		return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify(""+val).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(0,r[1].length);
	}
	switch(fmt) {
		case "###,###":
		case "##,###":
		case "#,###": var x = commaify(""+aval); return x !== "0" ? sign + x : "";
		default:
			if(fmt.match(/\.[0#?]*$/)) return write_num_int(type, fmt.slice(0,fmt.lastIndexOf(".")), val) + hashq(fmt.slice(fmt.lastIndexOf(".")));
	}
	throw new Error("unsupported format |" + fmt + "|");
}
function write_num(type/*:string*/, fmt/*:string*/, val/*:number*/)/*:string*/ {
	return (val|0) === val ? write_num_int(type, fmt, val) : write_num_flt(type, fmt, val);
}
function SSF_split_fmt(fmt/*:string*/)/*:Array<string>*/ {
	var out/*:Array<string>*/ = [];
	var in_str = false/*, cc*/;
	for(var i = 0, j = 0; i < fmt.length; ++i) switch((/*cc=*/fmt.charCodeAt(i))) {
		case 34: /* '"' */
			in_str = !in_str; break;
		case 95: case 42: case 92: /* '_' '*' '\\' */
			++i; break;
		case 59: /* ';' */
			out[out.length] = fmt.substr(j,i-j);
			j = i+1;
	}
	out[out.length] = fmt.substr(j);
	if(in_str === true) throw new Error("Format |" + fmt + "| unterminated string ");
	return out;
}

var SSF_abstime = /\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/;
function fmt_is_date(fmt/*:string*/)/*:boolean*/ {
	var i = 0, /*cc = 0,*/ c = "", o = "";
	while(i < fmt.length) {
		switch((c = fmt.charAt(i))) {
			case 'G': if(SSF_isgeneral(fmt, i)) i+= 6; i++; break;
			case '"': for(;(/*cc=*/fmt.charCodeAt(++i)) !== 34 && i < fmt.length;){/*empty*/} ++i; break;
			case '\\': i+=2; break;
			case '_': i+=2; break;
			case '@': ++i; break;
			case 'B': case 'b':
				if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") return true;
				/* falls through */
			case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
				/* falls through */
			case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g': return true;
			case 'A': case 'a': case '上':
				if(fmt.substr(i, 3).toUpperCase() === "A/P") return true;
				if(fmt.substr(i, 5).toUpperCase() === "AM/PM") return true;
				if(fmt.substr(i, 5).toUpperCase() === "上午/下午") return true;
				++i; break;
			case '[':
				o = c;
				while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
				if(o.match(SSF_abstime)) return true;
				break;
			case '.':
				/* falls through */
			case '0': case '#':
				while(i < fmt.length && ("0#?.,E+-%".indexOf(c=fmt.charAt(++i)) > -1 || (c=='\\' && fmt.charAt(i+1) == "-" && "0#".indexOf(fmt.charAt(i+2))>-1))){/* empty */}
				break;
			case '?': while(fmt.charAt(++i) === c){/* empty */} break;
			case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break;
			case '(': case ')': ++i; break;
			case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
				while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1){/* empty */} break;
			case ' ': ++i; break;
			default: ++i; break;
		}
	}
	return false;
}

function eval_fmt(fmt/*:string*/, v/*:any*/, opts/*:any*/, flen/*:number*/) {
	var out = [], o = "", i = 0, c = "", lst='t', dt, j, cc;
	var hr='H';
	/* Tokenize */
	while(i < fmt.length) {
		switch((c = fmt.charAt(i))) {
			case 'G': /* General */
				if(!SSF_isgeneral(fmt, i)) throw new Error('unrecognized character ' + c + ' in ' +fmt);
				out[out.length] = {t:'G', v:'General'}; i+=7; break;
			case '"': /* Literal text */
				for(o="";(cc=fmt.charCodeAt(++i)) !== 34 && i < fmt.length;) o += String.fromCharCode(cc);
				out[out.length] = {t:'t', v:o}; ++i; break;
			case '\\': var w = fmt.charAt(++i), t = (w === "(" || w === ")") ? w : 't';
				out[out.length] = {t:t, v:w}; ++i; break;
			case '_': out[out.length] = {t:'t', v:" "}; i+=2; break;
			case '@': /* Text Placeholder */
				out[out.length] = {t:'T', v:v}; ++i; break;
			case 'B': case 'b':
				if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") {
					if(dt==null) { dt=SSF_parse_date_code(v, opts, fmt.charAt(i+1) === "2"); if(dt==null) return ""; }
					out[out.length] = {t:'X', v:fmt.substr(i,2)}; lst = c; i+=2; break;
				}
				/* falls through */
			case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
				c = c.toLowerCase();
				/* falls through */
			case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g':
				if(v < 0) return "";
				if(dt==null) { dt=SSF_parse_date_code(v, opts); if(dt==null) return ""; }
				o = c; while(++i < fmt.length && fmt.charAt(i).toLowerCase() === c) o+=c;
				if(c === 'm' && lst.toLowerCase() === 'h') c = 'M';
				if(c === 'h') c = hr;
				out[out.length] = {t:c, v:o}; lst = c; break;
			case 'A': case 'a': case '上':
				var q={t:c, v:c};
				if(dt==null) dt=SSF_parse_date_code(v, opts);
				if(fmt.substr(i, 3).toUpperCase() === "A/P") { if(dt!=null) q.v = dt.H >= 12 ? "P" : "A"; q.t = 'T'; hr='h';i+=3;}
				else if(fmt.substr(i,5).toUpperCase() === "AM/PM") { if(dt!=null) q.v = dt.H >= 12 ? "PM" : "AM"; q.t = 'T'; i+=5; hr='h'; }
				else if(fmt.substr(i,5).toUpperCase() === "上午/下午") { if(dt!=null) q.v = dt.H >= 12 ? "下午" : "上午"; q.t = 'T'; i+=5; hr='h'; }
				else { q.t = "t"; ++i; }
				if(dt==null && q.t === 'T') return "";
				out[out.length] = q; lst = c; break;
			case '[':
				o = c;
				while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
				if(o.slice(-1) !== ']') throw 'unterminated "[" block: |' + o + '|';
				if(o.match(SSF_abstime)) {
					if(dt==null) { dt=SSF_parse_date_code(v, opts); if(dt==null) return ""; }
					out[out.length] = {t:'Z', v:o.toLowerCase()};
					lst = o.charAt(1);
				} else if(o.indexOf("$") > -1) {
					o = (o.match(/\$([^-\[\]]*)/)||[])[1]||"$";
					if(!fmt_is_date(fmt)) out[out.length] = {t:'t',v:o};
				}
				break;
			/* Numbers */
			case '.':
				if(dt != null) {
					o = c; while(++i < fmt.length && (c=fmt.charAt(i)) === "0") o += c;
					out[out.length] = {t:'s', v:o}; break;
				}
				/* falls through */
			case '0': case '#':
				o = c; while(++i < fmt.length && "0#?.,E+-%".indexOf(c=fmt.charAt(i)) > -1) o += c;
				out[out.length] = {t:'n', v:o}; break;
			case '?':
				o = c; while(fmt.charAt(++i) === c) o+=c;
				out[out.length] = {t:c, v:o}; lst = c; break;
			case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break; // **
			case '(': case ')': out[out.length] = {t:(flen===1?'t':c), v:c}; ++i; break;
			case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
				o = c; while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1) o+=fmt.charAt(i);
				out[out.length] = {t:'D', v:o}; break;
			case ' ': out[out.length] = {t:c, v:c}; ++i; break;
			case '$': out[out.length] = {t:'t', v:'$'}; ++i; break;
			default:
				if(",$-+/():!^&'~{}<>=€acfijklopqrtuvwxzP".indexOf(c) === -1) throw new Error('unrecognized character ' + c + ' in ' + fmt);
				out[out.length] = {t:'t', v:c}; ++i; break;
		}
	}

	/* Scan for date/time parts */
	var bt = 0, ss0 = 0, ssm;
	for(i=out.length-1, lst='t'; i >= 0; --i) {
		switch(out[i].t) {
			case 'h': case 'H': out[i].t = hr; lst='h'; if(bt < 1) bt = 1; break;
			case 's':
				if((ssm=out[i].v.match(/\.0+$/))) ss0=Math.max(ss0,ssm[0].length-1);
				if(bt < 3) bt = 3;
			/* falls through */
			case 'd': case 'y': case 'M': case 'e': lst=out[i].t; break;
			case 'm': if(lst === 's') { out[i].t = 'M'; if(bt < 2) bt = 2; } break;
			case 'X': /*if(out[i].v === "B2");*/
				break;
			case 'Z':
				if(bt < 1 && out[i].v.match(/[Hh]/)) bt = 1;
				if(bt < 2 && out[i].v.match(/[Mm]/)) bt = 2;
				if(bt < 3 && out[i].v.match(/[Ss]/)) bt = 3;
		}
	}
	/* time rounding depends on presence of minute / second / usec fields */
	switch(bt) {
		case 0: break;
		case 1:
			/*::if(!dt) break;*/
			if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
			if(dt.S >=  60) { dt.S = 0; ++dt.M; }
			if(dt.M >=  60) { dt.M = 0; ++dt.H; }
			break;
		case 2:
			/*::if(!dt) break;*/
			if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
			if(dt.S >=  60) { dt.S = 0; ++dt.M; }
			break;
	}

	/* replace fields */
	var nstr = "", jj;
	for(i=0; i < out.length; ++i) {
		switch(out[i].t) {
			case 't': case 'T': case ' ': case 'D': break;
			case 'X': out[i].v = ""; out[i].t = ";"; break;
			case 'd': case 'm': case 'y': case 'h': case 'H': case 'M': case 's': case 'e': case 'b': case 'Z':
				/*::if(!dt) throw "unreachable"; */
				out[i].v = SSF_write_date(out[i].t.charCodeAt(0), out[i].v, dt, ss0);
				out[i].t = 't'; break;
			case 'n': case '?':
				jj = i+1;
				while(out[jj] != null && (
					(c=out[jj].t) === "?" || c === "D" ||
					((c === " " || c === "t") && out[jj+1] != null && (out[jj+1].t === '?' || out[jj+1].t === "t" && out[jj+1].v === '/')) ||
					(out[i].t === '(' && (c === ' ' || c === 'n' || c === ')')) ||
					(c === 't' && (out[jj].v === '/' || out[jj].v === ' ' && out[jj+1] != null && out[jj+1].t == '?'))
				)) {
					out[i].v += out[jj].v;
					out[jj] = {v:"", t:";"}; ++jj;
				}
				nstr += out[i].v;
				i = jj-1; break;
			case 'G': out[i].t = 't'; out[i].v = SSF_general(v,opts); break;
		}
	}
	var vv = "", myv, ostr;
	if(nstr.length > 0) {
		if(nstr.charCodeAt(0) == 40) /* '(' */ {
			myv = (v<0&&nstr.charCodeAt(0) === 45 ? -v : v);
			ostr = write_num('n', nstr, myv);
		} else {
			myv = (v<0 && flen > 1 ? -v : v);
			ostr = write_num('n', nstr, myv);
			if(myv < 0 && out[0] && out[0].t == 't') {
				ostr = ostr.substr(1);
				out[0].v = "-" + out[0].v;
			}
		}
		jj=ostr.length-1;
		var decpt = out.length;
		for(i=0; i < out.length; ++i) if(out[i] != null && out[i].t != 't' && out[i].v.indexOf(".") > -1) { decpt = i; break; }
		var lasti=out.length;
		if(decpt === out.length && ostr.indexOf("E") === -1) {
			for(i=out.length-1; i>= 0;--i) {
				if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
				if(jj>=out[i].v.length-1) { jj -= out[i].v.length; out[i].v = ostr.substr(jj+1, out[i].v.length); }
				else if(jj < 0) out[i].v = "";
				else { out[i].v = ostr.substr(0, jj+1); jj = -1; }
				out[i].t = 't';
				lasti = i;
			}
			if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
		}
		else if(decpt !== out.length && ostr.indexOf("E") === -1) {
			jj = ostr.indexOf(".")-1;
			for(i=decpt; i>= 0; --i) {
				if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
				j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")-1:out[i].v.length-1;
				vv = out[i].v.substr(j+1);
				for(; j>=0; --j) {
					if(jj>=0 && (out[i].v.charAt(j) === "0" || out[i].v.charAt(j) === "#")) vv = ostr.charAt(jj--) + vv;
				}
				out[i].v = vv;
				out[i].t = 't';
				lasti = i;
			}
			if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
			jj = ostr.indexOf(".")+1;
			for(i=decpt; i<out.length; ++i) {
				if(out[i] == null || ('n?('.indexOf(out[i].t) === -1 && i !== decpt)) continue;
				j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")+1:0;
				vv = out[i].v.substr(0,j);
				for(; j<out[i].v.length; ++j) {
					if(jj<ostr.length) vv += ostr.charAt(jj++);
				}
				out[i].v = vv;
				out[i].t = 't';
				lasti = i;
			}
		}
	}
	for(i=0; i<out.length; ++i) if(out[i] != null && 'n?'.indexOf(out[i].t)>-1) {
		myv = (flen >1 && v < 0 && i>0 && out[i-1].v === "-" ? -v:v);
		out[i].v = write_num(out[i].t, out[i].v, myv);
		out[i].t = 't';
	}
	var retval = "";
	for(i=0; i !== out.length; ++i) if(out[i] != null) retval += out[i].v;
	return retval;
}

var cfregex2 = /\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/;
function chkcond(v, rr) {
	if(rr == null) return false;
	var thresh = parseFloat(rr[2]);
	switch(rr[1]) {
		case "=":  if(v == thresh) return true; break;
		case ">":  if(v >  thresh) return true; break;
		case "<":  if(v <  thresh) return true; break;
		case "<>": if(v != thresh) return true; break;
		case ">=": if(v >= thresh) return true; break;
		case "<=": if(v <= thresh) return true; break;
	}
	return false;
}
function choose_fmt(f/*:string*/, v/*:any*/) {
	var fmt = SSF_split_fmt(f);
	var l = fmt.length, lat = fmt[l-1].indexOf("@");
	if(l<4 && lat>-1) --l;
	if(fmt.length > 4) throw new Error("cannot find right format for |" + fmt.join("|") + "|");
	if(typeof v !== "number") return [4, fmt.length === 4 || lat>-1?fmt[fmt.length-1]:"@"];
	switch(fmt.length) {
		case 1: fmt = lat>-1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"]; break;
		case 2: fmt = lat>-1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"]; break;
		case 3: fmt = lat>-1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"]; break;
		case 4: break;
	}
	var ff = v > 0 ? fmt[0] : v < 0 ? fmt[1] : fmt[2];
	if(fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l, ff];
	if(fmt[0].match(/\[[=<>]/) != null || fmt[1].match(/\[[=<>]/) != null) {
		var m1 = fmt[0].match(cfregex2);
		var m2 = fmt[1].match(cfregex2);
		return chkcond(v, m1) ? [l, fmt[0]] : chkcond(v, m2) ? [l, fmt[1]] : [l, fmt[m1 != null && m2 != null ? 2 : 1]];
	}
	return [l, ff];
}
function SSF_format(fmt/*:string|number*/,v/*:any*/,o/*:?any*/) {
	if(o == null) o = {};
	var sfmt = "";
	switch(typeof fmt) {
		case "string":
			if(fmt == "m/d/yy" && o.dateNF) sfmt = o.dateNF;
			else sfmt = fmt;
			break;
		case "number":
			if(fmt == 14 && o.dateNF) sfmt = o.dateNF;
			else sfmt = (o.table != null ? (o.table/*:any*/) : table_fmt)[fmt];
			if(sfmt == null) sfmt = (o.table && o.table[SSF_default_map[fmt]]) || table_fmt[SSF_default_map[fmt]];
			if(sfmt == null) sfmt = SSF_default_str[fmt] || "General";
			break;
	}
	if(SSF_isgeneral(sfmt,0)) return SSF_general(v, o);
	if(v instanceof Date) v = datenum_local(v, o.date1904);
	var f = choose_fmt(sfmt, v);
	if(SSF_isgeneral(f[1])) return SSF_general(v, o);
	if(v === true) v = "TRUE"; else if(v === false) v = "FALSE";
	else if(v === "" || v == null) return "";
	return eval_fmt(f[1], v, o, f[0]);
}
function SSF_load(fmt/*:string*/, idx/*:?number*/)/*:number*/ {
	if(typeof idx != 'number') {
		idx = +idx || -1;
/*::if(typeof idx != 'number') return 0x188; */
		for(var i = 0; i < 0x0188; ++i) {
/*::if(typeof idx != 'number') return 0x188; */
			if(table_fmt[i] == undefined) { if(idx < 0) idx = i; continue; }
			if(table_fmt[i] == fmt) { idx = i; break; }
		}
/*::if(typeof idx != 'number') return 0x188; */
		if(idx < 0) idx = 0x187;
	}
/*::if(typeof idx != 'number') return 0x188; */
	table_fmt[idx] = fmt;
	return idx;
}
function SSF_load_table(tbl/*:SSFTable*/)/*:void*/ {
	for(var i=0; i!=0x0188; ++i)
		if(tbl[i] !== undefined) SSF_load(tbl[i], i);
}

function make_ssf() {
	table_fmt = SSF_init_table();
}

var SSF = {
	format: SSF_format,
	load: SSF_load,
	_table: table_fmt,
	load_table: SSF_load_table,
	parse_date_code: SSF_parse_date_code,
	is_date: fmt_is_date,
	get_table: function get_table() { return SSF._table = table_fmt; }
};

var SSFImplicit/*{[number]:string}*/ = ({
	"5": '"$"#,##0_);\\("$"#,##0\\)',
	"6": '"$"#,##0_);[Red]\\("$"#,##0\\)',
	"7": '"$"#,##0.00_);\\("$"#,##0.00\\)',
	"8": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
	"23": 'General', "24": 'General', "25": 'General', "26": 'General',
	"27": 'm/d/yy', "28": 'm/d/yy', "29": 'm/d/yy', "30": 'm/d/yy', "31": 'm/d/yy',
	"32": 'h:mm:ss', "33": 'h:mm:ss', "34": 'h:mm:ss', "35": 'h:mm:ss',
	"36": 'm/d/yy',
	"41": '_(* #,##0_);_(* \(#,##0\);_(* "-"_);_(@_)',
	"42": '_("$"* #,##0_);_("$"* \(#,##0\);_("$"* "-"_);_(@_)',
	"43": '_(* #,##0.00_);_(* \(#,##0.00\);_(* "-"??_);_(@_)',
	"44": '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)',
	"50": 'm/d/yy', "51": 'm/d/yy', "52": 'm/d/yy', "53": 'm/d/yy', "54": 'm/d/yy',
	"55": 'm/d/yy', "56": 'm/d/yy', "57": 'm/d/yy', "58": 'm/d/yy',
	"59": '0',
	"60": '0.00',
	"61": '#,##0',
	"62": '#,##0.00',
	"63": '"$"#,##0_);\\("$"#,##0\\)',
	"64": '"$"#,##0_);[Red]\\("$"#,##0\\)',
	"65": '"$"#,##0.00_);\\("$"#,##0.00\\)',
	"66": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
	"67": '0%',
	"68": '0.00%',
	"69": '# ?/?',
	"70": '# ??/??',
	"71": 'm/d/yy',
	"72": 'm/d/yy',
	"73": 'd-mmm-yy',
	"74": 'd-mmm',
	"75": 'mmm-yy',
	"76": 'h:mm',
	"77": 'h:mm:ss',
	"78": 'm/d/yy h:mm',
	"79": 'mm:ss',
	"80": '[h]:mm:ss',
	"81": 'mmss.0'
}/*:any*/);

/* dateNF parse TODO: move to SSF */
var dateNFregex = /[dD]+|[mM]+|[yYeE]+|[Hh]+|[Ss]+/g;
function dateNF_regex(dateNF/*:string|number*/)/*:RegExp*/ {
	var fmt = typeof dateNF == "number" ? table_fmt[dateNF] : dateNF;
	fmt = fmt.replace(dateNFregex, "(\\d+)");
	return new RegExp("^" + fmt + "$");
}
function dateNF_fix(str/*:string*/, dateNF/*:string*/, match/*:Array<string>*/)/*:string*/ {
	var Y = -1, m = -1, d = -1, H = -1, M = -1, S = -1;
	(dateNF.match(dateNFregex)||[]).forEach(function(n, i) {
		var v = parseInt(match[i+1], 10);
		switch(n.toLowerCase().charAt(0)) {
			case 'y': Y = v; break; case 'd': d = v; break;
			case 'h': H = v; break; case 's': S = v; break;
			case 'm': if(H >= 0) M = v; else m = v; break;
		}
	});
	if(S >= 0 && M == -1 && m >= 0) { M = m; m = -1; }
	var datestr = (("" + (Y>=0?Y: new Date().getFullYear())).slice(-4) + "-" + ("00" + (m>=1?m:1)).slice(-2) + "-" + ("00" + (d>=1?d:1)).slice(-2));
	if(datestr.length == 7) datestr = "0" + datestr;
	if(datestr.length == 8) datestr = "20" + datestr;
	var timestr = (("00" + (H>=0?H:0)).slice(-2) + ":" + ("00" + (M>=0?M:0)).slice(-2) + ":" + ("00" + (S>=0?S:0)).slice(-2));
	if(H == -1 && M == -1 && S == -1) return datestr;
	if(Y == -1 && m == -1 && d == -1) return timestr;
	return datestr + "T" + timestr;
}

/*::
declare var ReadShift:any;
declare var CheckField:any;
declare var prep_blob:any;
declare var __readUInt32LE:any;
declare var __readInt32LE:any;
declare var __toBuffer:any;
declare var __utf16le:any;
declare var bconcat:any;
declare var s2a:any;
declare var chr0:any;
declare var chr1:any;
declare var has_buf:boolean;
declare var new_buf:any;
declare var new_raw_buf:any;
declare var new_unsafe_buf:any;
declare var Buffer_from:any;
*/
/* cfb.js (C) 2013-present SheetJS -- http://sheetjs.com */
/* vim: set ts=2: */
/*jshint eqnull:true */
/*exported CFB */
/*global Uint8Array:false, Uint16Array:false */

/*::
type SectorEntry = {
	name?:string;
	nodes?:Array<number>;
	data:RawBytes;
};
type SectorList = {
	[k:string|number]:SectorEntry;
	name:?string;
	fat_addrs:Array<number>;
	ssz:number;
}
type CFBFiles = {[n:string]:CFBEntry};
*/
/* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */
/* vim: set ts=2: */
/*exported CRC32 */
var CRC32 = /*#__PURE__*/(function() {
var CRC32 = {};
CRC32.version = '1.2.0';
/* see perf/crc32table.js */
/*global Int32Array */
function signed_crc_table()/*:any*/ {
	var c = 0, table/*:Array<number>*/ = new Array(256);

	for(var n =0; n != 256; ++n){
		c = n;
		c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
		c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
		c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
		c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
		c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
		c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
		c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
		c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
		table[n] = c;
	}

	return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;
}

var T0 = signed_crc_table();
function slice_by_16_tables(T) {
	var c = 0, v = 0, n = 0, table/*:Array<number>*/ = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ;

	for(n = 0; n != 256; ++n) table[n] = T[n];
	for(n = 0; n != 256; ++n) {
		v = T[n];
		for(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF];
	}
	var out = [];
	for(n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== 'undefined' ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256);
	return out;
}
var TT = slice_by_16_tables(T0);
var T1 = TT[0],  T2 = TT[1],  T3 = TT[2],  T4 = TT[3],  T5 = TT[4];
var T6 = TT[5],  T7 = TT[6],  T8 = TT[7],  T9 = TT[8],  Ta = TT[9];
var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14];
function crc32_bstr(bstr/*:string*/, seed/*:number*/)/*:number*/ {
	var C = seed/*:: ? 0 : 0 */ ^ -1;
	for(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF];
	return ~C;
}

function crc32_buf(B/*:Uint8Array|Array<number>*/, seed/*:number*/)/*:number*/ {
	var C = seed/*:: ? 0 : 0 */ ^ -1, L = B.length - 15, i = 0;
	for(; i < L;) C =
		Tf[B[i++] ^ (C & 255)] ^
		Te[B[i++] ^ ((C >> 8) & 255)] ^
		Td[B[i++] ^ ((C >> 16) & 255)] ^
		Tc[B[i++] ^ (C >>> 24)] ^
		Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^
		T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^
		T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]];
	L += 15;
	while(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF];
	return ~C;
}

function crc32_str(str/*:string*/, seed/*:number*/)/*:number*/ {
	var C = seed ^ -1;
	for(var i = 0, L = str.length, c = 0, d = 0; i < L;) {
		c = str.charCodeAt(i++);
		if(c < 0x80) {
			C = (C>>>8) ^ T0[(C^c)&0xFF];
		} else if(c < 0x800) {
			C = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF];
			C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF];
		} else if(c >= 0xD800 && c < 0xE000) {
			c = (c&1023)+64; d = str.charCodeAt(i++)&1023;
			C = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF];
			C = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF];
			C = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF];
			C = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF];
		} else {
			C = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF];
			C = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF];
			C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF];
		}
	}
	return ~C;
}
CRC32.table = T0;
CRC32.bstr = crc32_bstr;
CRC32.buf = crc32_buf;
CRC32.str = crc32_str;
return CRC32;
})();
/* [MS-CFB] v20171201 */
var CFB = /*#__PURE__*/(function _CFB(){
var exports$1 = {};
exports$1.version = '1.2.1';
/* [MS-CFB] 2.6.4 */
function namecmp(l/*:string*/, r/*:string*/)/*:number*/ {
	var L = l.split("/"), R = r.split("/");
	for(var i = 0, c = 0, Z = Math.min(L.length, R.length); i < Z; ++i) {
		if((c = L[i].length - R[i].length)) return c;
		if(L[i] != R[i]) return L[i] < R[i] ? -1 : 1;
	}
	return L.length - R.length;
}
function dirname(p/*:string*/)/*:string*/ {
	if(p.charAt(p.length - 1) == "/") return (p.slice(0,-1).indexOf("/") === -1) ? p : dirname(p.slice(0, -1));
	var c = p.lastIndexOf("/");
	return (c === -1) ? p : p.slice(0, c+1);
}

function filename(p/*:string*/)/*:string*/ {
	if(p.charAt(p.length - 1) == "/") return filename(p.slice(0, -1));
	var c = p.lastIndexOf("/");
	return (c === -1) ? p : p.slice(c+1);
}
/* -------------------------------------------------------------------------- */
/* DOS Date format:
   high|YYYYYYYm.mmmddddd.HHHHHMMM.MMMSSSSS|low
   add 1980 to stored year
   stored second should be doubled
*/

/* write JS date to buf as a DOS date */
function write_dos_date(buf/*:CFBlob*/, date/*:Date|string*/) {
	if(typeof date === "string") date = new Date(date);
	var hms/*:number*/ = date.getHours();
	hms = hms << 6 | date.getMinutes();
	hms = hms << 5 | (date.getSeconds()>>>1);
	buf.write_shift(2, hms);
	var ymd/*:number*/ = (date.getFullYear() - 1980);
	ymd = ymd << 4 | (date.getMonth()+1);
	ymd = ymd << 5 | date.getDate();
	buf.write_shift(2, ymd);
}

/* read four bytes from buf and interpret as a DOS date */
function parse_dos_date(buf/*:CFBlob*/)/*:Date*/ {
	var hms = buf.read_shift(2) & 0xFFFF;
	var ymd = buf.read_shift(2) & 0xFFFF;
	var val = new Date();
	var d = ymd & 0x1F; ymd >>>= 5;
	var m = ymd & 0x0F; ymd >>>= 4;
	val.setMilliseconds(0);
	val.setFullYear(ymd + 1980);
	val.setMonth(m-1);
	val.setDate(d);
	var S = hms & 0x1F; hms >>>= 5;
	var M = hms & 0x3F; hms >>>= 6;
	val.setHours(hms);
	val.setMinutes(M);
	val.setSeconds(S<<1);
	return val;
}
function parse_extra_field(blob/*:CFBlob*/)/*:any*/ {
	prep_blob(blob, 0);
	var o = /*::(*/{}/*:: :any)*/;
	var flags = 0;
	while(blob.l <= blob.length - 4) {
		var type = blob.read_shift(2);
		var sz = blob.read_shift(2), tgt = blob.l + sz;
		var p = {};
		switch(type) {
			/* UNIX-style Timestamps */
			case 0x5455: {
				flags = blob.read_shift(1);
				if(flags & 1) p.mtime = blob.read_shift(4);
				/* for some reason, CD flag corresponds to LFH */
				if(sz > 5) {
					if(flags & 2) p.atime = blob.read_shift(4);
					if(flags & 4) p.ctime = blob.read_shift(4);
				}
				if(p.mtime) p.mt = new Date(p.mtime*1000);
			}
			break;
		}
		blob.l = tgt;
		o[type] = p;
	}
	return o;
}
var fs/*:: = require('fs'); */;
function get_fs() { return fs || (fs = {}); }
function parse(file/*:RawBytes*/, options/*:CFBReadOpts*/)/*:CFBContainer*/ {
if(file[0] == 0x50 && file[1] == 0x4b) return parse_zip(file, options);
if((file[0] | 0x20) == 0x6d && (file[1]|0x20) == 0x69) return parse_mad(file, options);
if(file.length < 512) throw new Error("CFB file size " + file.length + " < 512");
var mver = 3;
var ssz = 512;
var nmfs = 0; // number of mini FAT sectors
var difat_sec_cnt = 0;
var dir_start = 0;
var minifat_start = 0;
var difat_start = 0;

var fat_addrs/*:Array<number>*/ = []; // locations of FAT sectors

/* [MS-CFB] 2.2 Compound File Header */
var blob/*:CFBlob*/ = /*::(*/file.slice(0,512)/*:: :any)*/;
prep_blob(blob, 0);

/* major version */
var mv = check_get_mver(blob);
mver = mv[0];
switch(mver) {
	case 3: ssz = 512; break; case 4: ssz = 4096; break;
	case 0: if(mv[1] == 0) return parse_zip(file, options);
	/* falls through */
	default: throw new Error("Major Version: Expected 3 or 4 saw " + mver);
}

/* reprocess header */
if(ssz !== 512) { blob = /*::(*/file.slice(0,ssz)/*:: :any)*/; prep_blob(blob, 28 /* blob.l */); }
/* Save header for final object */
var header/*:RawBytes*/ = file.slice(0,ssz);

check_shifts(blob, mver);

// Number of Directory Sectors
var dir_cnt/*:number*/ = blob.read_shift(4, 'i');
if(mver === 3 && dir_cnt !== 0) throw new Error('# Directory Sectors: Expected 0 saw ' + dir_cnt);

// Number of FAT Sectors
blob.l += 4;

// First Directory Sector Location
dir_start = blob.read_shift(4, 'i');

// Transaction Signature
blob.l += 4;

// Mini Stream Cutoff Size
blob.chk('00100000', 'Mini Stream Cutoff Size: ');

// First Mini FAT Sector Location
minifat_start = blob.read_shift(4, 'i');

// Number of Mini FAT Sectors
nmfs = blob.read_shift(4, 'i');

// First DIFAT sector location
difat_start = blob.read_shift(4, 'i');

// Number of DIFAT Sectors
difat_sec_cnt = blob.read_shift(4, 'i');

// Grab FAT Sector Locations
for(var q = -1, j = 0; j < 109; ++j) { /* 109 = (512 - blob.l)>>>2; */
	q = blob.read_shift(4, 'i');
	if(q<0) break;
	fat_addrs[j] = q;
}

/** Break the file up into sectors */
var sectors/*:Array<RawBytes>*/ = sectorify(file, ssz);

sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs);

/** Chains */
var sector_list/*:SectorList*/ = make_sector_list(sectors, dir_start, fat_addrs, ssz);

sector_list[dir_start].name = "!Directory";
if(nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT";
sector_list[fat_addrs[0]].name = "!FAT";
sector_list.fat_addrs = fat_addrs;
sector_list.ssz = ssz;

/* [MS-CFB] 2.6.1 Compound File Directory Entry */
var files/*:CFBFiles*/ = {}, Paths/*:Array<string>*/ = [], FileIndex/*:CFBFileIndex*/ = [], FullPaths/*:Array<string>*/ = [];
read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start);

build_full_paths(FileIndex, FullPaths, Paths);
Paths.shift();

var o = {
	FileIndex: FileIndex,
	FullPaths: FullPaths
};

// $FlowIgnore
if(options && options.raw) o.raw = {header: header, sectors: sectors};
return o;
} // parse

/* [MS-CFB] 2.2 Compound File Header -- read up to major version */
function check_get_mver(blob/*:CFBlob*/)/*:[number, number]*/ {
	if(blob[blob.l] == 0x50 && blob[blob.l + 1] == 0x4b) return [0, 0];
	// header signature 8
	blob.chk(HEADER_SIGNATURE, 'Header Signature: ');

	// clsid 16
	//blob.chk(HEADER_CLSID, 'CLSID: ');
	blob.l += 16;

	// minor version 2
	var mver/*:number*/ = blob.read_shift(2, 'u');

	return [blob.read_shift(2,'u'), mver];
}
function check_shifts(blob/*:CFBlob*/, mver/*:number*/)/*:void*/ {
	var shift = 0x09;

	// Byte Order
	//blob.chk('feff', 'Byte Order: '); // note: some writers put 0xffff
	blob.l += 2;

	// Sector Shift
	switch((shift = blob.read_shift(2))) {
		case 0x09: if(mver != 3) throw new Error('Sector Shift: Expected 9 saw ' + shift); break;
		case 0x0c: if(mver != 4) throw new Error('Sector Shift: Expected 12 saw ' + shift); break;
		default: throw new Error('Sector Shift: Expected 9 or 12 saw ' + shift);
	}

	// Mini Sector Shift
	blob.chk('0600', 'Mini Sector Shift: ');

	// Reserved
	blob.chk('000000000000', 'Reserved: ');
}

/** Break the file up into sectors */
function sectorify(file/*:RawBytes*/, ssz/*:number*/)/*:Array<RawBytes>*/ {
	var nsectors = Math.ceil(file.length/ssz)-1;
	var sectors/*:Array<RawBytes>*/ = [];
	for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz);
	sectors[nsectors-1] = file.slice(nsectors*ssz);
	return sectors;
}

/* [MS-CFB] 2.6.4 Red-Black Tree */
function build_full_paths(FI/*:CFBFileIndex*/, FP/*:Array<string>*/, Paths/*:Array<string>*/)/*:void*/ {
	var i = 0, L = 0, R = 0, C = 0, j = 0, pl = Paths.length;
	var dad/*:Array<number>*/ = [], q/*:Array<number>*/ = [];

	for(; i < pl; ++i) { dad[i]=q[i]=i; FP[i]=Paths[i]; }

	for(; j < q.length; ++j) {
		i = q[j];
		L = FI[i].L; R = FI[i].R; C = FI[i].C;
		if(dad[i] === i) {
			if(L !== -1 /*NOSTREAM*/ && dad[L] !== L) dad[i] = dad[L];
			if(R !== -1 && dad[R] !== R) dad[i] = dad[R];
		}
		if(C !== -1 /*NOSTREAM*/) dad[C] = i;
		if(L !== -1 && i != dad[i]) { dad[L] = dad[i]; if(q.lastIndexOf(L) < j) q.push(L); }
		if(R !== -1 && i != dad[i]) { dad[R] = dad[i]; if(q.lastIndexOf(R) < j) q.push(R); }
	}
	for(i=1; i < pl; ++i) if(dad[i] === i) {
		if(R !== -1 /*NOSTREAM*/ && dad[R] !== R) dad[i] = dad[R];
		else if(L !== -1 && dad[L] !== L) dad[i] = dad[L];
	}

	for(i=1; i < pl; ++i) {
		if(FI[i].type === 0 /* unknown */) continue;
		j = i;
		if(j != dad[j]) do {
			j = dad[j];
			FP[i] = FP[j] + "/" + FP[i];
		} while (j !== 0 && -1 !== dad[j] && j != dad[j]);
		dad[i] = -1;
	}

	FP[0] += "/";
	for(i=1; i < pl; ++i) {
		if(FI[i].type !== 2 /* stream */) FP[i] += "/";
	}
}

function get_mfat_entry(entry/*:CFBEntry*/, payload/*:RawBytes*/, mini/*:?RawBytes*/)/*:CFBlob*/ {
	var start = entry.start, size = entry.size;
	//return (payload.slice(start*MSSZ, start*MSSZ + size)/*:any*/);
	var o = [];
	var idx = start;
	while(mini && size > 0 && idx >= 0) {
		o.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ));
		size -= MSSZ;
		idx = __readInt32LE(mini, idx * 4);
	}
	if(o.length === 0) return (new_buf(0)/*:any*/);
	return (bconcat(o).slice(0, entry.size)/*:any*/);
}

/** Chase down the rest of the DIFAT chain to build a comprehensive list
    DIFAT chains by storing the next sector number as the last 32 bits */
function sleuth_fat(idx/*:number*/, cnt/*:number*/, sectors/*:Array<RawBytes>*/, ssz/*:number*/, fat_addrs)/*:void*/ {
	var q/*:number*/ = ENDOFCHAIN;
	if(idx === ENDOFCHAIN) {
		if(cnt !== 0) throw new Error("DIFAT chain shorter than expected");
	} else if(idx !== -1 /*FREESECT*/) {
		var sector = sectors[idx], m = (ssz>>>2)-1;
		if(!sector) return;
		for(var i = 0; i < m; ++i) {
			if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break;
			fat_addrs.push(q);
		}
		sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs);
	}
}

/** Follow the linked list of sectors for a given starting point */
function get_sector_list(sectors/*:Array<RawBytes>*/, start/*:number*/, fat_addrs/*:Array<number>*/, ssz/*:number*/, chkd/*:?Array<boolean>*/)/*:SectorEntry*/ {
	var buf/*:Array<number>*/ = [], buf_chain/*:Array<any>*/ = [];
	if(!chkd) chkd = [];
	var modulus = ssz - 1, j = 0, jj = 0;
	for(j=start; j>=0;) {
		chkd[j] = true;
		buf[buf.length] = j;
		buf_chain.push(sectors[j]);
		var addr = fat_addrs[Math.floor(j*4/ssz)];
		jj = ((j*4) & modulus);
		if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
		if(!sectors[addr]) break;
		j = __readInt32LE(sectors[addr], jj);
	}
	return {nodes: buf, data:__toBuffer([buf_chain])};
}

/** Chase down the sector linked lists */
function make_sector_list(sectors/*:Array<RawBytes>*/, dir_start/*:number*/, fat_addrs/*:Array<number>*/, ssz/*:number*/)/*:SectorList*/ {
	var sl = sectors.length, sector_list/*:SectorList*/ = ([]/*:any*/);
	var chkd/*:Array<boolean>*/ = [], buf/*:Array<number>*/ = [], buf_chain/*:Array<RawBytes>*/ = [];
	var modulus = ssz - 1, i=0, j=0, k=0, jj=0;
	for(i=0; i < sl; ++i) {
		buf = ([]/*:Array<number>*/);
		k = (i + dir_start); if(k >= sl) k-=sl;
		if(chkd[k]) continue;
		buf_chain = [];
		var seen = [];
		for(j=k; j>=0;) {
			seen[j] = true;
			chkd[j] = true;
			buf[buf.length] = j;
			buf_chain.push(sectors[j]);
			var addr/*:number*/ = fat_addrs[Math.floor(j*4/ssz)];
			jj = ((j*4) & modulus);
			if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
			if(!sectors[addr]) break;
			j = __readInt32LE(sectors[addr], jj);
			if(seen[j]) break;
		}
		sector_list[k] = ({nodes: buf, data:__toBuffer([buf_chain])}/*:SectorEntry*/);
	}
	return sector_list;
}

/* [MS-CFB] 2.6.1 Compound File Directory Entry */
function read_directory(dir_start/*:number*/, sector_list/*:SectorList*/, sectors/*:Array<RawBytes>*/, Paths/*:Array<string>*/, nmfs, files, FileIndex, mini) {
	var minifat_store = 0, pl = (Paths.length?2:0);
	var sector = sector_list[dir_start].data;
	var i = 0, namelen = 0, name;
	for(; i < sector.length; i+= 128) {
		var blob/*:CFBlob*/ = /*::(*/sector.slice(i, i+128)/*:: :any)*/;
		prep_blob(blob, 64);
		namelen = blob.read_shift(2);
		name = __utf16le(blob,0,namelen-pl);
		Paths.push(name);
		var o/*:CFBEntry*/ = ({
			name:  name,
			type:  blob.read_shift(1),
			color: blob.read_shift(1),
			L:     blob.read_shift(4, 'i'),
			R:     blob.read_shift(4, 'i'),
			C:     blob.read_shift(4, 'i'),
			clsid: blob.read_shift(16),
			state: blob.read_shift(4, 'i'),
			start: 0,
			size: 0
		});
		var ctime/*:number*/ = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
		if(ctime !== 0) o.ct = read_date(blob, blob.l-8);
		var mtime/*:number*/ = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
		if(mtime !== 0) o.mt = read_date(blob, blob.l-8);
		o.start = blob.read_shift(4, 'i');
		o.size = blob.read_shift(4, 'i');
		if(o.size < 0 && o.start < 0) { o.size = o.type = 0; o.start = ENDOFCHAIN; o.name = ""; }
		if(o.type === 5) { /* root */
			minifat_store = o.start;
			if(nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData";
			/*minifat_size = o.size;*/
		} else if(o.size >= 4096 /* MSCSZ */) {
			o.storage = 'fat';
			if(sector_list[o.start] === undefined) sector_list[o.start] = get_sector_list(sectors, o.start, sector_list.fat_addrs, sector_list.ssz);
			sector_list[o.start].name = o.name;
			o.content = (sector_list[o.start].data.slice(0,o.size)/*:any*/);
		} else {
			o.storage = 'minifat';
			if(o.size < 0) o.size = 0;
			else if(minifat_store !== ENDOFCHAIN && o.start !== ENDOFCHAIN && sector_list[minifat_store]) {
				o.content = get_mfat_entry(o, sector_list[minifat_store].data, (sector_list[mini]||{}).data);
			}
		}
		if(o.content) prep_blob(o.content, 0);
		files[name] = o;
		FileIndex.push(o);
	}
}

function read_date(blob/*:RawBytes|CFBlob*/, offset/*:number*/)/*:Date*/ {
	return new Date(( ( (__readUInt32LE(blob,offset+4)/1e7)*Math.pow(2,32)+__readUInt32LE(blob,offset)/1e7 ) - 11644473600)*1000);
}

function read_file(filename/*:string*/, options/*:CFBReadOpts*/) {
	get_fs();
	return parse(fs.readFileSync(filename), options);
}

function read(blob/*:RawBytes|string*/, options/*:CFBReadOpts*/) {
	var type = options && options.type;
	if(!type) {
		if(has_buf && Buffer.isBuffer(blob)) type = "buffer";
	}
	switch(type || "base64") {
		case "file": /*:: if(typeof blob !== 'string') throw "Must pass a filename when type='file'"; */return read_file(blob, options);
		case "base64": /*:: if(typeof blob !== 'string') throw "Must pass a base64-encoded binary string when type='file'"; */return parse(s2a(Base64_decode(blob)), options);
		case "binary": /*:: if(typeof blob !== 'string') throw "Must pass a binary string when type='file'"; */return parse(s2a(blob), options);
	}
	return parse(/*::typeof blob == 'string' ? new Buffer(blob, 'utf-8') : */blob, options);
}

function init_cfb(cfb/*:CFBContainer*/, opts/*:?any*/)/*:void*/ {
	var o = opts || {}, root = o.root || "Root Entry";
	if(!cfb.FullPaths) cfb.FullPaths = [];
	if(!cfb.FileIndex) cfb.FileIndex = [];
	if(cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure");
	if(cfb.FullPaths.length === 0) {
		cfb.FullPaths[0] = root + "/";
		cfb.FileIndex[0] = ({ name: root, type: 5 }/*:any*/);
	}
	if(o.CLSID) cfb.FileIndex[0].clsid = o.CLSID;
	seed_cfb(cfb);
}
function seed_cfb(cfb/*:CFBContainer*/)/*:void*/ {
	var nm = "\u0001Sh33tJ5";
	if(CFB.find(cfb, "/" + nm)) return;
	var p = new_buf(4); p[0] = 55; p[1] = p[3] = 50; p[2] = 54;
	cfb.FileIndex.push(({ name: nm, type: 2, content:p, size:4, L:69, R:69, C:69 }/*:any*/));
	cfb.FullPaths.push(cfb.FullPaths[0] + nm);
	rebuild_cfb(cfb);
}
function rebuild_cfb(cfb/*:CFBContainer*/, f/*:?boolean*/)/*:void*/ {
	init_cfb(cfb);
	var gc = false, s = false;
	for(var i = cfb.FullPaths.length - 1; i >= 0; --i) {
		var _file = cfb.FileIndex[i];
		switch(_file.type) {
			case 0:
				if(s) gc = true;
				else { cfb.FileIndex.pop(); cfb.FullPaths.pop(); }
				break;
			case 1: case 2: case 5:
				s = true;
				if(isNaN(_file.R * _file.L * _file.C)) gc = true;
				if(_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true;
				break;
			default: gc = true; break;
		}
	}
	if(!gc && !f) return;

	var now = new Date(1987, 1, 19), j = 0;
	// Track which names exist
	var fullPaths = Object.create ? Object.create(null) : {};
	var data/*:Array<[string, CFBEntry]>*/ = [];
	for(i = 0; i < cfb.FullPaths.length; ++i) {
		fullPaths[cfb.FullPaths[i]] = true;
		if(cfb.FileIndex[i].type === 0) continue;
		data.push([cfb.FullPaths[i], cfb.FileIndex[i]]);
	}
	for(i = 0; i < data.length; ++i) {
		var dad = dirname(data[i][0]);
		s = fullPaths[dad];
		if(!s) {
			data.push([dad, ({
				name: filename(dad).replace("/",""),
				type: 1,
				clsid: HEADER_CLSID,
				ct: now, mt: now,
				content: null
			}/*:any*/)]);
			// Add name to set
			fullPaths[dad] = true;
		}
	}

	data.sort(function(x,y) { return namecmp(x[0], y[0]); });
	cfb.FullPaths = []; cfb.FileIndex = [];
	for(i = 0; i < data.length; ++i) { cfb.FullPaths[i] = data[i][0]; cfb.FileIndex[i] = data[i][1]; }
	for(i = 0; i < data.length; ++i) {
		var elt = cfb.FileIndex[i];
		var nm = cfb.FullPaths[i];

		elt.name =  filename(nm).replace("/","");
		elt.L = elt.R = elt.C = -(elt.color = 1);
		elt.size = elt.content ? elt.content.length : 0;
		elt.start = 0;
		elt.clsid = (elt.clsid || HEADER_CLSID);
		if(i === 0) {
			elt.C = data.length > 1 ? 1 : -1;
			elt.size = 0;
			elt.type = 5;
		} else if(nm.slice(-1) == "/") {
			for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==nm) break;
			elt.C = j >= data.length ? -1 : j;
			for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==dirname(nm)) break;
			elt.R = j >= data.length ? -1 : j;
			elt.type = 1;
		} else {
			if(dirname(cfb.FullPaths[i+1]||"") == dirname(nm)) elt.R = i + 1;
			elt.type = 2;
		}
	}

}

function _write(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:RawBytes|string*/ {
	var _opts = options || {};
	/* MAD is order-sensitive, skip rebuild and sort */
	if(_opts.fileType == 'mad') return write_mad(cfb, _opts);
	rebuild_cfb(cfb);
	switch(_opts.fileType) {
		case 'zip': return write_zip(cfb, _opts);
		//case 'mad': return write_mad(cfb, _opts);
	}
	var L = (function(cfb/*:CFBContainer*/)/*:Array<number>*/{
		var mini_size = 0, fat_size = 0;
		for(var i = 0; i < cfb.FileIndex.length; ++i) {
			var file = cfb.FileIndex[i];
			if(!file.content) continue;
			/*:: if(file.content == null) throw new Error("unreachable"); */
			var flen = file.content.length;
			if(flen > 0){
				if(flen < 0x1000) mini_size += (flen + 0x3F) >> 6;
				else fat_size += (flen + 0x01FF) >> 9;
			}
		}
		var dir_cnt = (cfb.FullPaths.length +3) >> 2;
		var mini_cnt = (mini_size + 7) >> 3;
		var mfat_cnt = (mini_size + 0x7F) >> 7;
		var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt;
		var fat_cnt = (fat_base + 0x7F) >> 7;
		var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
		while(((fat_base + fat_cnt + difat_cnt + 0x7F) >> 7) > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
		var L =  [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0];
		cfb.FileIndex[0].size = mini_size << 6;
		L[7] = (cfb.FileIndex[0].start=L[0]+L[1]+L[2]+L[3]+L[4]+L[5])+((L[6]+7) >> 3);
		return L;
	})(cfb);
	var o = new_buf(L[7] << 9);
	var i = 0, T = 0;
	{
		for(i = 0; i < 8; ++i) o.write_shift(1, HEADER_SIG[i]);
		for(i = 0; i < 8; ++i) o.write_shift(2, 0);
		o.write_shift(2, 0x003E);
		o.write_shift(2, 0x0003);
		o.write_shift(2, 0xFFFE);
		o.write_shift(2, 0x0009);
		o.write_shift(2, 0x0006);
		for(i = 0; i < 3; ++i) o.write_shift(2, 0);
		o.write_shift(4, 0);
		o.write_shift(4, L[2]);
		o.write_shift(4, L[0] + L[1] + L[2] + L[3] - 1);
		o.write_shift(4, 0);
		o.write_shift(4, 1<<12);
		o.write_shift(4, L[3] ? L[0] + L[1] + L[2] - 1: ENDOFCHAIN);
		o.write_shift(4, L[3]);
		o.write_shift(-4, L[1] ? L[0] - 1: ENDOFCHAIN);
		o.write_shift(4, L[1]);
		for(i = 0; i < 109; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
	}
	if(L[1]) {
		for(T = 0; T < L[1]; ++T) {
			for(; i < 236 + T * 127; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
			o.write_shift(-4, T === L[1] - 1 ? ENDOFCHAIN : T + 1);
		}
	}
	var chainit = function(w/*:number*/)/*:void*/ {
		for(T += w; i<T-1; ++i) o.write_shift(-4, i+1);
		if(w) { ++i; o.write_shift(-4, ENDOFCHAIN); }
	};
	T = i = 0;
	for(T+=L[1]; i<T; ++i) o.write_shift(-4, consts.DIFSECT);
	for(T+=L[2]; i<T; ++i) o.write_shift(-4, consts.FATSECT);
	chainit(L[3]);
	chainit(L[4]);
	var j/*:number*/ = 0, flen/*:number*/ = 0;
	var file/*:CFBEntry*/ = cfb.FileIndex[0];
	for(; j < cfb.FileIndex.length; ++j) {
		file = cfb.FileIndex[j];
		if(!file.content) continue;
		/*:: if(file.content == null) throw new Error("unreachable"); */
		flen = file.content.length;
		if(flen < 0x1000) continue;
		file.start = T;
		chainit((flen + 0x01FF) >> 9);
	}
	chainit((L[6] + 7) >> 3);
	while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
	T = i = 0;
	for(j = 0; j < cfb.FileIndex.length; ++j) {
		file = cfb.FileIndex[j];
		if(!file.content) continue;
		/*:: if(file.content == null) throw new Error("unreachable"); */
		flen = file.content.length;
		if(!flen || flen >= 0x1000) continue;
		file.start = T;
		chainit((flen + 0x3F) >> 6);
	}
	while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
	for(i = 0; i < L[4]<<2; ++i) {
		var nm = cfb.FullPaths[i];
		if(!nm || nm.length === 0) {
			for(j = 0; j < 17; ++j) o.write_shift(4, 0);
			for(j = 0; j < 3; ++j) o.write_shift(4, -1);
			for(j = 0; j < 12; ++j) o.write_shift(4, 0);
			continue;
		}
		file = cfb.FileIndex[i];
		if(i === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN;
		var _nm/*:string*/ = (i === 0 && _opts.root) || file.name;
		flen = 2*(_nm.length+1);
		o.write_shift(64, _nm, "utf16le");
		o.write_shift(2, flen);
		o.write_shift(1, file.type);
		o.write_shift(1, file.color);
		o.write_shift(-4, file.L);
		o.write_shift(-4, file.R);
		o.write_shift(-4, file.C);
		if(!file.clsid) for(j = 0; j < 4; ++j) o.write_shift(4, 0);
		else o.write_shift(16, file.clsid, "hex");
		o.write_shift(4, file.state || 0);
		o.write_shift(4, 0); o.write_shift(4, 0);
		o.write_shift(4, 0); o.write_shift(4, 0);
		o.write_shift(4, file.start);
		o.write_shift(4, file.size); o.write_shift(4, 0);
	}
	for(i = 1; i < cfb.FileIndex.length; ++i) {
		file = cfb.FileIndex[i];
		/*:: if(!file.content) throw new Error("unreachable"); */
		if(file.size >= 0x1000) {
			o.l = (file.start+1) << 9;
			if (has_buf && Buffer.isBuffer(file.content)) {
				file.content.copy(o, o.l, 0, file.size);
				// o is a 0-filled Buffer so just set next offset
				o.l += (file.size + 511) & -512;
			} else {
				for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
				for(; j & 0x1FF; ++j) o.write_shift(1, 0);
			}
		}
	}
	for(i = 1; i < cfb.FileIndex.length; ++i) {
		file = cfb.FileIndex[i];
		/*:: if(!file.content) throw new Error("unreachable"); */
		if(file.size > 0 && file.size < 0x1000) {
			if (has_buf && Buffer.isBuffer(file.content)) {
				file.content.copy(o, o.l, 0, file.size);
				// o is a 0-filled Buffer so just set next offset
				o.l += (file.size + 63) & -64;
			} else {
				for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
				for(; j & 0x3F; ++j) o.write_shift(1, 0);
			}
		}
	}
	if (has_buf) {
		o.l = o.length;
	} else {
		// When using Buffer, already 0-filled
		while(o.l < o.length) o.write_shift(1, 0);
	}
	return o;
}
/* [MS-CFB] 2.6.4 (Unicode 3.0.1 case conversion) */
function find(cfb/*:CFBContainer*/, path/*:string*/)/*:?CFBEntry*/ {
	var UCFullPaths/*:Array<string>*/ = cfb.FullPaths.map(function(x) { return x.toUpperCase(); });
	var UCPaths/*:Array<string>*/ = UCFullPaths.map(function(x) { var y = x.split("/"); return y[y.length - (x.slice(-1) == "/" ? 2 : 1)]; });
	var k/*:boolean*/ = false;
	if(path.charCodeAt(0) === 47 /* "/" */) { k = true; path = UCFullPaths[0].slice(0, -1) + path; }
	else k = path.indexOf("/") !== -1;
	var UCPath/*:string*/ = path.toUpperCase();
	var w/*:number*/ = k === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath);
	if(w !== -1) return cfb.FileIndex[w];

	var m = !UCPath.match(chr1);
	UCPath = UCPath.replace(chr0,'');
	if(m) UCPath = UCPath.replace(chr1,'!');
	for(w = 0; w < UCFullPaths.length; ++w) {
		if((m ? UCFullPaths[w].replace(chr1,'!') : UCFullPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
		if((m ? UCPaths[w].replace(chr1,'!') : UCPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
	}
	return null;
}
/** CFB Constants */
var MSSZ = 64; /* Mini Sector Size = 1<<6 */
//var MSCSZ = 4096; /* Mini Stream Cutoff Size */
/* 2.1 Compound File Sector Numbers and Types */
var ENDOFCHAIN = -2;
/* 2.2 Compound File Header */
var HEADER_SIGNATURE = 'd0cf11e0a1b11ae1';
var HEADER_SIG = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
var HEADER_CLSID = '00000000000000000000000000000000';
var consts = {
	/* 2.1 Compund File Sector Numbers and Types */
	MAXREGSECT: -6,
	DIFSECT: -4,
	FATSECT: -3,
	ENDOFCHAIN: ENDOFCHAIN,
	FREESECT: -1,
	/* 2.2 Compound File Header */
	HEADER_SIGNATURE: HEADER_SIGNATURE,
	HEADER_MINOR_VERSION: '3e00',
	MAXREGSID: -6,
	NOSTREAM: -1,
	HEADER_CLSID: HEADER_CLSID,
	/* 2.6.1 Compound File Directory Entry */
	EntryTypes: ['unknown','storage','stream','lockbytes','property','root']
};

function write_file(cfb/*:CFBContainer*/, filename/*:string*/, options/*:CFBWriteOpts*/)/*:void*/ {
	get_fs();
	var o = _write(cfb, options);
	/*:: if(typeof Buffer == 'undefined' || !Buffer.isBuffer(o) || !(o instanceof Buffer)) throw new Error("unreachable"); */
	fs.writeFileSync(filename, o);
}

function a2s(o/*:RawBytes*/)/*:string*/ {
	var out = new Array(o.length);
	for(var i = 0; i < o.length; ++i) out[i] = String.fromCharCode(o[i]);
	return out.join("");
}

function write(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:RawBytes|string*/ {
	var o = _write(cfb, options);
	switch(options && options.type || "buffer") {
		case "file": get_fs(); fs.writeFileSync(options.filename, (o/*:any*/)); return o;
		case "binary": return typeof o == "string" ? o : a2s(o);
		case "base64": return Base64_encode(typeof o == "string" ? o : a2s(o));
		case "buffer": if(has_buf) return Buffer.isBuffer(o) ? o : Buffer_from(o);
			/* falls through */
		case "array": return typeof o == "string" ? s2a(o) : o;
	}
	return o;
}
/* node < 8.1 zlib does not expose bytesRead, so default to pure JS */
var _zlib;
function use_zlib(zlib) { try {
	var InflateRaw = zlib.InflateRaw;
	var InflRaw = new InflateRaw();
	InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag);
	if(InflRaw.bytesRead) _zlib = zlib;
	else throw new Error("zlib does not expose bytesRead");
} catch(e) {console.error("cannot use native zlib: " + (e.message || e)); } }

function _inflateRawSync(payload, usz) {
	if(!_zlib) return _inflate(payload, usz);
	var InflateRaw = _zlib.InflateRaw;
	var InflRaw = new InflateRaw();
	var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag);
	payload.l += InflRaw.bytesRead;
	return out;
}

function _deflateRawSync(payload) {
	return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload);
}
var CLEN_ORDER = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];

/*  LEN_ID = [ 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285 ]; */
var LEN_LN = [   3,   4,   5,   6,   7,   8,   9,  10,  11,  13 , 15,  17,  19,  23,  27,  31,  35,  43,  51,  59,  67,  83,  99, 115, 131, 163, 195, 227, 258 ];

/*  DST_ID = [  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13,  14,  15,  16,  17,  18,  19,   20,   21,   22,   23,   24,   25,   26,    27,    28,    29 ]; */
var DST_LN = [  1,  2,  3,  4,  5,  7,  9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 ];

function bit_swap_8(n) { var t = (((((n<<1)|(n<<11)) & 0x22110) | (((n<<5)|(n<<15)) & 0x88440))); return ((t>>16) | (t>>8) |t)&0xFF; }

var use_typed_arrays = typeof Uint8Array !== 'undefined';

var bitswap8 = use_typed_arrays ? new Uint8Array(1<<8) : [];
for(var q = 0; q < (1<<8); ++q) bitswap8[q] = bit_swap_8(q);

function bit_swap_n(n, b) {
	var rev = bitswap8[n & 0xFF];
	if(b <= 8) return rev >>> (8-b);
	rev = (rev << 8) | bitswap8[(n>>8)&0xFF];
	if(b <= 16) return rev >>> (16-b);
	rev = (rev << 8) | bitswap8[(n>>16)&0xFF];
	return rev >>> (24-b);
}

/* helpers for unaligned bit reads */
function read_bits_2(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 6 ? 0 : buf[h+1]<<8))>>>w)& 0x03; }
function read_bits_3(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 5 ? 0 : buf[h+1]<<8))>>>w)& 0x07; }
function read_bits_4(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 4 ? 0 : buf[h+1]<<8))>>>w)& 0x0F; }
function read_bits_5(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 3 ? 0 : buf[h+1]<<8))>>>w)& 0x1F; }
function read_bits_7(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 1 ? 0 : buf[h+1]<<8))>>>w)& 0x7F; }

/* works up to n = 3 * 8 + 1 = 25 */
function read_bits_n(buf, bl, n) {
	var w = (bl&7), h = (bl>>>3), f = ((1<<n)-1);
	var v = buf[h] >>> w;
	if(n < 8 - w) return v & f;
	v |= buf[h+1]<<(8-w);
	if(n < 16 - w) return v & f;
	v |= buf[h+2]<<(16-w);
	if(n < 24 - w) return v & f;
	v |= buf[h+3]<<(24-w);
	return v & f;
}

/* helpers for unaligned bit writes */
function write_bits_3(buf, bl, v) { var w = bl & 7, h = bl >>> 3;
	if(w <= 5) buf[h] |= (v & 7) << w;
	else {
		buf[h] |= (v << w) & 0xFF;
		buf[h+1] = (v&7) >> (8-w);
	}
	return bl + 3;
}

function write_bits_1(buf, bl, v) {
	var w = bl & 7, h = bl >>> 3;
	v = (v&1) << w;
	buf[h] |= v;
	return bl + 1;
}
function write_bits_8(buf, bl, v) {
	var w = bl & 7, h = bl >>> 3;
	v <<= w;
	buf[h] |=  v & 0xFF; v >>>= 8;
	buf[h+1] = v;
	return bl + 8;
}
function write_bits_16(buf, bl, v) {
	var w = bl & 7, h = bl >>> 3;
	v <<= w;
	buf[h] |=  v & 0xFF; v >>>= 8;
	buf[h+1] = v & 0xFF;
	buf[h+2] = v >>> 8;
	return bl + 16;
}

/* until ArrayBuffer#realloc is a thing, fake a realloc */
function realloc(b, sz/*:number*/) {
	var L = b.length, M = 2*L > sz ? 2*L : sz + 5, i = 0;
	if(L >= sz) return b;
	if(has_buf) {
		var o = new_unsafe_buf(M);
		// $FlowIgnore
		if(b.copy) b.copy(o);
		else for(; i < b.length; ++i) o[i] = b[i];
		return o;
	} else if(use_typed_arrays) {
		var a = new Uint8Array(M);
		if(a.set) a.set(b);
		else for(; i < L; ++i) a[i] = b[i];
		return a;
	}
	b.length = M;
	return b;
}

/* zero-filled arrays for older browsers */
function zero_fill_array(n) {
	var o = new Array(n);
	for(var i = 0; i < n; ++i) o[i] = 0;
	return o;
}

/* build tree (used for literals and lengths) */
function build_tree(clens, cmap, MAX/*:number*/)/*:number*/ {
	var maxlen = 1, w = 0, i = 0, j = 0, ccode = 0, L = clens.length;

	var bl_count  = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
	for(i = 0; i < 32; ++i) bl_count[i] = 0;

	for(i = L; i < MAX; ++i) clens[i] = 0;
	L = clens.length;

	var ctree = use_typed_arrays ? new Uint16Array(L) : zero_fill_array(L); // []

	/* build code tree */
	for(i = 0; i < L; ++i) {
		bl_count[(w = clens[i])]++;
		if(maxlen < w) maxlen = w;
		ctree[i] = 0;
	}
	bl_count[0] = 0;
	for(i = 1; i <= maxlen; ++i) bl_count[i+16] = (ccode = (ccode + bl_count[i-1])<<1);
	for(i = 0; i < L; ++i) {
		ccode = clens[i];
		if(ccode != 0) ctree[i] = bl_count[ccode+16]++;
	}

	/* cmap[maxlen + 4 bits] = (off&15) + (lit<<4) reverse mapping */
	var cleni = 0;
	for(i = 0; i < L; ++i) {
		cleni = clens[i];
		if(cleni != 0) {
			ccode = bit_swap_n(ctree[i], maxlen)>>(maxlen-cleni);
			for(j = (1<<(maxlen + 4 - cleni)) - 1; j>=0; --j)
				cmap[ccode|(j<<cleni)] = (cleni&15) | (i<<4);
		}
	}
	return maxlen;
}

/* Fixed Huffman */
var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512);
var fix_dmap = use_typed_arrays ? new Uint16Array(32)  : zero_fill_array(32);
if(!use_typed_arrays) {
	for(var i = 0; i < 512; ++i) fix_lmap[i] = 0;
	for(i = 0; i < 32; ++i) fix_dmap[i] = 0;
}
(function() {
	var dlens/*:Array<number>*/ = [];
	var i = 0;
	for(;i<32; i++) dlens.push(5);
	build_tree(dlens, fix_dmap, 32);

	var clens/*:Array<number>*/ = [];
	i = 0;
	for(; i<=143; i++) clens.push(8);
	for(; i<=255; i++) clens.push(9);
	for(; i<=279; i++) clens.push(7);
	for(; i<=287; i++) clens.push(8);
	build_tree(clens, fix_lmap, 288);
})();var _deflateRaw = /*#__PURE__*/(function _deflateRawIIFE() {
	var DST_LN_RE = use_typed_arrays ? new Uint8Array(0x8000) : [];
	var j = 0, k = 0;
	for(; j < DST_LN.length - 1; ++j) {
		for(; k < DST_LN[j+1]; ++k) DST_LN_RE[k] = j;
	}
	for(;k < 32768; ++k) DST_LN_RE[k] = 29;

	var LEN_LN_RE = use_typed_arrays ? new Uint8Array(0x103) : [];
	for(j = 0, k = 0; j < LEN_LN.length - 1; ++j) {
		for(; k < LEN_LN[j+1]; ++k) LEN_LN_RE[k] = j;
	}

	function write_stored(data, out) {
		var boff = 0;
		while(boff < data.length) {
			var L = Math.min(0xFFFF, data.length - boff);
			var h = boff + L == data.length;
			out.write_shift(1, +h);
			out.write_shift(2, L);
			out.write_shift(2, (~L) & 0xFFFF);
			while(L-- > 0) out[out.l++] = data[boff++];
		}
		return out.l;
	}

	/* Fixed Huffman */
	function write_huff_fixed(data, out) {
		var bl = 0;
		var boff = 0;
		var addrs = use_typed_arrays ? new Uint16Array(0x8000) : [];
		while(boff < data.length) {
			var L = /* data.length - boff; */ Math.min(0xFFFF, data.length - boff);

			/* write a stored block for short data */
			if(L < 10) {
				bl = write_bits_3(out, bl, +!!(boff + L == data.length)); // jshint ignore:line
				if(bl & 7) bl += 8 - (bl & 7);
				out.l = (bl / 8) | 0;
				out.write_shift(2, L);
				out.write_shift(2, (~L) & 0xFFFF);
				while(L-- > 0) out[out.l++] = data[boff++];
				bl = out.l * 8;
				continue;
			}

			bl = write_bits_3(out, bl, +!!(boff + L == data.length) + 2); // jshint ignore:line
			var hash = 0;
			while(L-- > 0) {
				var d = data[boff];
				hash = ((hash << 5) ^ d) & 0x7FFF;

				var match = -1, mlen = 0;

				if((match = addrs[hash])) {
					match |= boff & ~0x7FFF;
					if(match > boff) match -= 0x8000;
					if(match < boff) while(data[match + mlen] == data[boff + mlen] && mlen < 250) ++mlen;
				}

				if(mlen > 2) {
					/* Copy Token  */
					d = LEN_LN_RE[mlen];
					if(d <= 22) bl = write_bits_8(out, bl, bitswap8[d+1]>>1) - 1;
					else {
						write_bits_8(out, bl, 3);
						bl += 5;
						write_bits_8(out, bl, bitswap8[d-23]>>5);
						bl += 3;
					}
					var len_eb = (d < 8) ? 0 : ((d - 4)>>2);
					if(len_eb > 0) {
						write_bits_16(out, bl, mlen - LEN_LN[d]);
						bl += len_eb;
					}

					d = DST_LN_RE[boff - match];
					bl = write_bits_8(out, bl, bitswap8[d]>>3);
					bl -= 3;

					var dst_eb = d < 4 ? 0 : (d-2)>>1;
					if(dst_eb > 0) {
						write_bits_16(out, bl, boff - match - DST_LN[d]);
						bl += dst_eb;
					}
					for(var q = 0; q < mlen; ++q) {
						addrs[hash] = boff & 0x7FFF;
						hash = ((hash << 5) ^ data[boff]) & 0x7FFF;
						++boff;
					}
					L-= mlen - 1;
				} else {
					/* Literal Token */
					if(d <= 143) d = d + 48;
					else bl = write_bits_1(out, bl, 1);
					bl = write_bits_8(out, bl, bitswap8[d]);
					addrs[hash] = boff & 0x7FFF;
					++boff;
				}
			}

			bl = write_bits_8(out, bl, 0) - 1;
		}
		out.l = ((bl + 7)/8)|0;
		return out.l;
	}
	return function _deflateRaw(data, out) {
		if(data.length < 8) return write_stored(data, out);
		return write_huff_fixed(data, out);
	};
})();

function _deflate(data) {
	var buf = new_buf(50+Math.floor(data.length*1.1));
	var off = _deflateRaw(data, buf);
	return buf.slice(0, off);
}
/* modified inflate function also moves original read head */

var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
var dyn_cmap = use_typed_arrays ? new Uint16Array(128)   : zero_fill_array(128);
var dyn_len_1 = 1, dyn_len_2 = 1;

/* 5.5.3 Expanding Huffman Codes */
function dyn(data, boff/*:number*/) {
	/* nomenclature from RFC1951 refers to bit values; these are offset by the implicit constant */
	var _HLIT = read_bits_5(data, boff) + 257; boff += 5;
	var _HDIST = read_bits_5(data, boff) + 1; boff += 5;
	var _HCLEN = read_bits_4(data, boff) + 4; boff += 4;
	var w = 0;

	/* grab and store code lengths */
	var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19);
	var ctree = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
	var maxlen = 1;
	var bl_count =  use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
	var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
	var L = clens.length; /* 19 */
	for(var i = 0; i < _HCLEN; ++i) {
		clens[CLEN_ORDER[i]] = w = read_bits_3(data, boff);
		if(maxlen < w) maxlen = w;
		bl_count[w]++;
		boff += 3;
	}

	/* build code tree */
	var ccode = 0;
	bl_count[0] = 0;
	for(i = 1; i <= maxlen; ++i) next_code[i] = ccode = (ccode + bl_count[i-1])<<1;
	for(i = 0; i < L; ++i) if((ccode = clens[i]) != 0) ctree[i] = next_code[ccode]++;
	/* cmap[7 bits from stream] = (off&7) + (lit<<3) */
	var cleni = 0;
	for(i = 0; i < L; ++i) {
		cleni = clens[i];
		if(cleni != 0) {
			ccode = bitswap8[ctree[i]]>>(8-cleni);
			for(var j = (1<<(7-cleni))-1; j>=0; --j) dyn_cmap[ccode|(j<<cleni)] = (cleni&7) | (i<<3);
		}
	}

	/* read literal and dist codes at once */
	var hcodes/*:Array<number>*/ = [];
	maxlen = 1;
	for(; hcodes.length < _HLIT + _HDIST;) {
		ccode = dyn_cmap[read_bits_7(data, boff)];
		boff += ccode & 7;
		switch((ccode >>>= 3)) {
			case 16:
				w = 3 + read_bits_2(data, boff); boff += 2;
				ccode = hcodes[hcodes.length - 1];
				while(w-- > 0) hcodes.push(ccode);
				break;
			case 17:
				w = 3 + read_bits_3(data, boff); boff += 3;
				while(w-- > 0) hcodes.push(0);
				break;
			case 18:
				w = 11 + read_bits_7(data, boff); boff += 7;
				while(w -- > 0) hcodes.push(0);
				break;
			default:
				hcodes.push(ccode);
				if(maxlen < ccode) maxlen = ccode;
				break;
		}
	}

	/* build literal / length trees */
	var h1 = hcodes.slice(0, _HLIT), h2 = hcodes.slice(_HLIT);
	for(i = _HLIT; i < 286; ++i) h1[i] = 0;
	for(i = _HDIST; i < 30; ++i) h2[i] = 0;
	dyn_len_1 = build_tree(h1, dyn_lmap, 286);
	dyn_len_2 = build_tree(h2, dyn_dmap, 30);
	return boff;
}

/* return [ data, bytesRead ] */
function inflate(data, usz/*:number*/) {
	/* shortcircuit for empty buffer [0x03, 0x00] */
	if(data[0] == 3 && !(data[1] & 0x3)) { return [new_raw_buf(usz), 2]; }

	/* bit offset */
	var boff = 0;

	/* header includes final bit and type bits */
	var header = 0;

	var outbuf = new_unsafe_buf(usz ? usz : (1<<18));
	var woff = 0;
	var OL = outbuf.length>>>0;
	var max_len_1 = 0, max_len_2 = 0;

	while((header&1) == 0) {
		header = read_bits_3(data, boff); boff += 3;
		if((header >>> 1) == 0) {
			/* Stored block */
			if(boff & 7) boff += 8 - (boff&7);
			/* 2 bytes sz, 2 bytes bit inverse */
			var sz = data[boff>>>3] | data[(boff>>>3)+1]<<8;
			boff += 32;
			/* push sz bytes */
			if(sz > 0) {
				if(!usz && OL < woff + sz) { outbuf = realloc(outbuf, woff + sz); OL = outbuf.length; }
				while(sz-- > 0) { outbuf[woff++] = data[boff>>>3]; boff += 8; }
			}
			continue;
		} else if((header >> 1) == 1) {
			/* Fixed Huffman */
			max_len_1 = 9; max_len_2 = 5;
		} else {
			/* Dynamic Huffman */
			boff = dyn(data, boff);
			max_len_1 = dyn_len_1; max_len_2 = dyn_len_2;
		}
		for(;;) { // while(true) is apparently out of vogue in modern JS circles
			if(!usz && (OL < woff + 32767)) { outbuf = realloc(outbuf, woff + 32767); OL = outbuf.length; }
			/* ingest code and move read head */
			var bits = read_bits_n(data, boff, max_len_1);
			var code = (header>>>1) == 1 ? fix_lmap[bits] : dyn_lmap[bits];
			boff += code & 15; code >>>= 4;
			/* 0-255 are literals, 256 is end of block token, 257+ are copy tokens */
			if(((code>>>8)&0xFF) === 0) outbuf[woff++] = code;
			else if(code == 256) break;
			else {
				code -= 257;
				var len_eb = (code < 8) ? 0 : ((code-4)>>2); if(len_eb > 5) len_eb = 0;
				var tgt = woff + LEN_LN[code];
				/* length extra bits */
				if(len_eb > 0) {
					tgt += read_bits_n(data, boff, len_eb);
					boff += len_eb;
				}

				/* dist code */
				bits = read_bits_n(data, boff, max_len_2);
				code = (header>>>1) == 1 ? fix_dmap[bits] : dyn_dmap[bits];
				boff += code & 15; code >>>= 4;
				var dst_eb = (code < 4 ? 0 : (code-2)>>1);
				var dst = DST_LN[code];
				/* dist extra bits */
				if(dst_eb > 0) {
					dst += read_bits_n(data, boff, dst_eb);
					boff += dst_eb;
				}

				/* in the common case, manual byte copy is faster than TA set / Buffer copy */
				if(!usz && OL < tgt) { outbuf = realloc(outbuf, tgt + 100); OL = outbuf.length; }
				while(woff < tgt) { outbuf[woff] = outbuf[woff - dst]; ++woff; }
			}
		}
	}
	if(usz) return [outbuf, (boff+7)>>>3];
	return [outbuf.slice(0, woff), (boff+7)>>>3];
}

function _inflate(payload, usz) {
	var data = payload.slice(payload.l||0);
	var out = inflate(data, usz);
	payload.l += out[1];
	return out[0];
}

function warn_or_throw(wrn, msg) {
	if(wrn) { if(typeof console !== 'undefined') console.error(msg); }
	else throw new Error(msg);
}

function parse_zip(file/*:RawBytes*/, options/*:CFBReadOpts*/)/*:CFBContainer*/ {
	var blob/*:CFBlob*/ = /*::(*/file/*:: :any)*/;
	prep_blob(blob, 0);

	var FileIndex/*:CFBFileIndex*/ = [], FullPaths/*:Array<string>*/ = [];
	var o = {
		FileIndex: FileIndex,
		FullPaths: FullPaths
	};
	init_cfb(o, { root: options.root });

	/* find end of central directory, start just after signature */
	var i = blob.length - 4;
	while((blob[i] != 0x50 || blob[i+1] != 0x4b || blob[i+2] != 0x05 || blob[i+3] != 0x06) && i >= 0) --i;
	blob.l = i + 4;

	/* parse end of central directory */
	blob.l += 4;
	var fcnt = blob.read_shift(2);
	blob.l += 6;
	var start_cd = blob.read_shift(4);

	/* parse central directory */
	blob.l = start_cd;

	for(i = 0; i < fcnt; ++i) {
		/* trust local file header instead of CD entry */
		blob.l += 20;
		var csz = blob.read_shift(4);
		var usz = blob.read_shift(4);
		var namelen = blob.read_shift(2);
		var efsz = blob.read_shift(2);
		var fcsz = blob.read_shift(2);
		blob.l += 8;
		var offset = blob.read_shift(4);
		var EF = parse_extra_field(/*::(*/blob.slice(blob.l+namelen, blob.l+namelen+efsz)/*:: :any)*/);
		blob.l += namelen + efsz + fcsz;

		var L = blob.l;
		blob.l = offset + 4;
		parse_local_file(blob, csz, usz, o, EF);
		blob.l = L;
	}
	return o;
}


/* head starts just after local file header signature */
function parse_local_file(blob/*:CFBlob*/, csz/*:number*/, usz/*:number*/, o/*:CFBContainer*/, EF) {
	/* [local file header] */
	blob.l += 2;
	var flags = blob.read_shift(2);
	var meth = blob.read_shift(2);
	var date = parse_dos_date(blob);

	if(flags & 0x2041) throw new Error("Unsupported ZIP encryption");
	var crc32 = blob.read_shift(4);
	var _csz = blob.read_shift(4);
	var _usz = blob.read_shift(4);

	var namelen = blob.read_shift(2);
	var efsz = blob.read_shift(2);

	// TODO: flags & (1<<11) // UTF8
	var name = ""; for(var i = 0; i < namelen; ++i) name += String.fromCharCode(blob[blob.l++]);
	if(efsz) {
		var ef = parse_extra_field(/*::(*/blob.slice(blob.l, blob.l + efsz)/*:: :any)*/);
		if((ef[0x5455]||{}).mt) date = ef[0x5455].mt;
		if(((EF||{})[0x5455]||{}).mt) date = EF[0x5455].mt;
	}
	blob.l += efsz;

	/* [encryption header] */

	/* [file data] */
	var data = blob.slice(blob.l, blob.l + _csz);
	switch(meth) {
		case 8: data = _inflateRawSync(blob, _usz); break;
		case 0: break; // TODO: scan for magic number
		default: throw new Error("Unsupported ZIP Compression method " + meth);
	}

	/* [data descriptor] */
	var wrn = false;
	if(flags & 8) {
		crc32 = blob.read_shift(4);
		if(crc32 == 0x08074b50) { crc32 = blob.read_shift(4); wrn = true; }
		_csz = blob.read_shift(4);
		_usz = blob.read_shift(4);
	}

	if(_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz);
	if(_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz);
	//var _crc32 = CRC32.buf(data, 0);
	//if((crc32>>0) != (_crc32>>0)) warn_or_throw(wrn, "Bad CRC32 checksum: " + crc32 + " != " + _crc32);
	cfb_add(o, name, data, {unsafe: true, mt: date});
}
function write_zip(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:RawBytes*/ {
	var _opts = options || {};
	var out = [], cdirs = [];
	var o/*:CFBlob*/ = new_buf(1);
	var method = (_opts.compression ? 8 : 0), flags = 0;
	var desc = false;
	if(desc) flags |= 8;
	var i = 0, j = 0;

	var start_cd = 0, fcnt = 0;
	var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
	var crcs = [];
	var sz_cd = 0;

	for(i = 1; i < cfb.FullPaths.length; ++i) {
		fp = cfb.FullPaths[i].slice(root.length); fi = cfb.FileIndex[i];
		if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
		var start = start_cd;

		/* TODO: CP437 filename */
		var namebuf = new_buf(fp.length);
		for(j = 0; j < fp.length; ++j) namebuf.write_shift(1, fp.charCodeAt(j) & 0x7F);
		namebuf = namebuf.slice(0, namebuf.l);
		crcs[fcnt] = CRC32.buf(/*::((*/fi.content/*::||[]):any)*/, 0);

		var outbuf = fi.content/*::||[]*/;
		if(method == 8) outbuf = _deflateRawSync(outbuf);

		/* local file header */
		o = new_buf(30);
		o.write_shift(4, 0x04034b50);
		o.write_shift(2, 20);
		o.write_shift(2, flags);
		o.write_shift(2, method);
		/* TODO: last mod file time/date */
		if(fi.mt) write_dos_date(o, fi.mt);
		else o.write_shift(4, 0);
		o.write_shift(-4, (flags & 8) ? 0 : crcs[fcnt]);
		o.write_shift(4,  (flags & 8) ? 0 : outbuf.length);
		o.write_shift(4,  (flags & 8) ? 0 : /*::(*/fi.content/*::||[])*/.length);
		o.write_shift(2, namebuf.length);
		o.write_shift(2, 0);

		start_cd += o.length;
		out.push(o);
		start_cd += namebuf.length;
		out.push(namebuf);

		/* TODO: extra fields? */

		/* TODO: encryption header ? */

		start_cd += outbuf.length;
		out.push(outbuf);

		/* data descriptor */
		if(flags & 8) {
			o = new_buf(12);
			o.write_shift(-4, crcs[fcnt]);
			o.write_shift(4, outbuf.length);
			o.write_shift(4, /*::(*/fi.content/*::||[])*/.length);
			start_cd += o.l;
			out.push(o);
		}

		/* central directory */
		o = new_buf(46);
		o.write_shift(4, 0x02014b50);
		o.write_shift(2, 0);
		o.write_shift(2, 20);
		o.write_shift(2, flags);
		o.write_shift(2, method);
		o.write_shift(4, 0); /* TODO: last mod file time/date */
		o.write_shift(-4, crcs[fcnt]);

		o.write_shift(4, outbuf.length);
		o.write_shift(4, /*::(*/fi.content/*::||[])*/.length);
		o.write_shift(2, namebuf.length);
		o.write_shift(2, 0);
		o.write_shift(2, 0);
		o.write_shift(2, 0);
		o.write_shift(2, 0);
		o.write_shift(4, 0);
		o.write_shift(4, start);

		sz_cd += o.l;
		cdirs.push(o);
		sz_cd += namebuf.length;
		cdirs.push(namebuf);
		++fcnt;
	}

	/* end of central directory */
	o = new_buf(22);
	o.write_shift(4, 0x06054b50);
	o.write_shift(2, 0);
	o.write_shift(2, 0);
	o.write_shift(2, fcnt);
	o.write_shift(2, fcnt);
	o.write_shift(4, sz_cd);
	o.write_shift(4, start_cd);
	o.write_shift(2, 0);

	return bconcat(([bconcat((out/*:any*/)), bconcat(cdirs), o]/*:any*/));
}
var ContentTypeMap = ({
	"htm": "text/html",
	"xml": "text/xml",

	"gif": "image/gif",
	"jpg": "image/jpeg",
	"png": "image/png",

	"mso": "application/x-mso",
	"thmx": "application/vnd.ms-officetheme",
	"sh33tj5": "application/octet-stream"
}/*:any*/);

function get_content_type(fi/*:CFBEntry*/, fp/*:string*/)/*:string*/ {
	if(fi.ctype) return fi.ctype;

	var ext = fi.name || "", m = ext.match(/\.([^\.]+)$/);
	if(m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];

	if(fp) {
		m = (ext = fp).match(/[\.\\]([^\.\\])+$/);
		if(m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];
	}

	return "application/octet-stream";
}

/* 76 character chunks TODO: intertwine encoding */
function write_base64_76(bstr/*:string*/)/*:string*/ {
	var data = Base64_encode(bstr);
	var o = [];
	for(var i = 0; i < data.length; i+= 76) o.push(data.slice(i, i+76));
	return o.join("\r\n") + "\r\n";
}

/*
Rules for QP:
	- escape =## applies for all non-display characters and literal "="
	- space or tab at end of line must be encoded
	- \r\n newlines can be preserved, but bare \r and \n must be escaped
	- lines must not exceed 76 characters, use soft breaks =\r\n

TODO: Some files from word appear to write line extensions with bare equals:

```
<table class=3DMsoTableGrid border=3D1 cellspacing=3D0 cellpadding=3D0 width=
="70%"
```
*/
function write_quoted_printable(text/*:string*/)/*:string*/ {
	var encoded = text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF=]/g, function(c) {
		var w = c.charCodeAt(0).toString(16).toUpperCase();
		return "=" + (w.length == 1 ? "0" + w : w);
	});

	encoded = encoded.replace(/ $/mg, "=20").replace(/\t$/mg, "=09");

	if(encoded.charAt(0) == "\n") encoded = "=0D" + encoded.slice(1);
	encoded = encoded.replace(/\r(?!\n)/mg, "=0D").replace(/\n\n/mg, "\n=0A").replace(/([^\r\n])\n/mg, "$1=0A");

	var o/*:Array<string>*/ = [], split = encoded.split("\r\n");
	for(var si = 0; si < split.length; ++si) {
		var str = split[si];
		if(str.length == 0) { o.push(""); continue; }
		for(var i = 0; i < str.length;) {
			var end = 76;
			var tmp = str.slice(i, i + end);
			if(tmp.charAt(end - 1) == "=") end --;
			else if(tmp.charAt(end - 2) == "=") end -= 2;
			else if(tmp.charAt(end - 3) == "=") end -= 3;
			tmp = str.slice(i, i + end);
			i += end;
			if(i < str.length) tmp += "=";
			o.push(tmp);
		}
	}

	return o.join("\r\n");
}
function parse_quoted_printable(data/*:Array<string>*/)/*:RawBytes*/ {
	var o = [];

	/* unify long lines */
	for(var di = 0; di < data.length; ++di) {
		var line = data[di];
		while(di <= data.length && line.charAt(line.length - 1) == "=") line = line.slice(0, line.length - 1) + data[++di];
		o.push(line);
	}

	/* decode */
	for(var oi = 0; oi < o.length; ++oi) o[oi] = o[oi].replace(/[=][0-9A-Fa-f]{2}/g, function($$) { return String.fromCharCode(parseInt($$.slice(1), 16)); });
	return s2a(o.join("\r\n"));
}


function parse_mime(cfb/*:CFBContainer*/, data/*:Array<string>*/, root/*:string*/)/*:void*/ {
	var fname = "", cte = "", ctype = "", fdata;
	var di = 0;
	for(;di < 10; ++di) {
		var line = data[di];
		if(!line || line.match(/^\s*$/)) break;
		var m = line.match(/^(.*?):\s*([^\s].*)$/);
		if(m) switch(m[1].toLowerCase()) {
			case "content-location": fname = m[2].trim(); break;
			case "content-type": ctype = m[2].trim(); break;
			case "content-transfer-encoding": cte = m[2].trim(); break;
		}
	}
	++di;
	switch(cte.toLowerCase()) {
		case 'base64': fdata = s2a(Base64_decode(data.slice(di).join(""))); break;
		case 'quoted-printable': fdata = parse_quoted_printable(data.slice(di)); break;
		default: throw new Error("Unsupported Content-Transfer-Encoding " + cte);
	}
	var file = cfb_add(cfb, fname.slice(root.length), fdata, {unsafe: true});
	if(ctype) file.ctype = ctype;
}

function parse_mad(file/*:RawBytes*/, options/*:CFBReadOpts*/)/*:CFBContainer*/ {
	if(a2s(file.slice(0,13)).toLowerCase() != "mime-version:") throw new Error("Unsupported MAD header");
	var root = (options && options.root || "");
	// $FlowIgnore
	var data = (has_buf && Buffer.isBuffer(file) ? file.toString("binary") : a2s(file)).split("\r\n");
	var di = 0, row = "";

	/* if root is not specified, scan for the common prefix */
	for(di = 0; di < data.length; ++di) {
		row = data[di];
		if(!/^Content-Location:/i.test(row)) continue;
		row = row.slice(row.indexOf("file"));
		if(!root) root = row.slice(0, row.lastIndexOf("/") + 1);
		if(row.slice(0, root.length) == root) continue;
		while(root.length > 0) {
			root = root.slice(0, root.length - 1);
			root = root.slice(0, root.lastIndexOf("/") + 1);
			if(row.slice(0,root.length) == root) break;
		}
	}

	var mboundary = (data[1] || "").match(/boundary="(.*?)"/);
	if(!mboundary) throw new Error("MAD cannot find boundary");
	var boundary = "--" + (mboundary[1] || "");

	var FileIndex/*:CFBFileIndex*/ = [], FullPaths/*:Array<string>*/ = [];
	var o = {
		FileIndex: FileIndex,
		FullPaths: FullPaths
	};
	init_cfb(o);
	var start_di, fcnt = 0;
	for(di = 0; di < data.length; ++di) {
		var line = data[di];
		if(line !== boundary && line !== boundary + "--") continue;
		if(fcnt++) parse_mime(o, data.slice(start_di, di), root);
		start_di = di;
	}
	return o;
}

function write_mad(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:string*/ {
	var opts = options || {};
	var boundary = opts.boundary || "SheetJS";
	boundary = '------=' + boundary;

	var out = [
		'MIME-Version: 1.0',
		'Content-Type: multipart/related; boundary="' + boundary.slice(2) + '"',
		'',
		'',
		''
	];

	var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
	for(var i = 1; i < cfb.FullPaths.length; ++i) {
		fp = cfb.FullPaths[i].slice(root.length);
		fi = cfb.FileIndex[i];
		if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;

		/* Normalize filename */
		fp = fp.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF]/g, function(c) {
			return "_x" + c.charCodeAt(0).toString(16) + "_";
		}).replace(/[\u0080-\uFFFF]/g, function(u) {
			return "_u" + u.charCodeAt(0).toString(16) + "_";
		});

		/* Extract content as binary string */
		var ca = fi.content;
		// $FlowIgnore
		var cstr = has_buf && Buffer.isBuffer(ca) ? ca.toString("binary") : a2s(ca);

		/* 4/5 of first 1024 chars ascii -> quoted printable, else base64 */
		var dispcnt = 0, L = Math.min(1024, cstr.length), cc = 0;
		for(var csl = 0; csl <= L; ++csl) if((cc=cstr.charCodeAt(csl)) >= 0x20 && cc < 0x80) ++dispcnt;
		var qp = dispcnt >= L * 4 / 5;

		out.push(boundary);
		out.push('Content-Location: ' + (opts.root || 'file:///C:/SheetJS/') + fp);
		out.push('Content-Transfer-Encoding: ' + (qp ? 'quoted-printable' : 'base64'));
		out.push('Content-Type: ' + get_content_type(fi, fp));
		out.push('');

		out.push(qp ? write_quoted_printable(cstr) : write_base64_76(cstr));
	}
	out.push(boundary + '--\r\n');
	return out.join("\r\n");
}
function cfb_new(opts/*:?any*/)/*:CFBContainer*/ {
	var o/*:CFBContainer*/ = ({}/*:any*/);
	init_cfb(o, opts);
	return o;
}

function cfb_add(cfb/*:CFBContainer*/, name/*:string*/, content/*:?RawBytes*/, opts/*:?any*/)/*:CFBEntry*/ {
	var unsafe = opts && opts.unsafe;
	if(!unsafe) init_cfb(cfb);
	var file = !unsafe && CFB.find(cfb, name);
	if(!file) {
		var fpath/*:string*/ = cfb.FullPaths[0];
		if(name.slice(0, fpath.length) == fpath) fpath = name;
		else {
			if(fpath.slice(-1) != "/") fpath += "/";
			fpath = (fpath + name).replace("//","/");
		}
		file = ({name: filename(name), type: 2}/*:any*/);
		cfb.FileIndex.push(file);
		cfb.FullPaths.push(fpath);
		if(!unsafe) CFB.utils.cfb_gc(cfb);
	}
	/*:: if(!file) throw new Error("unreachable"); */
	file.content = (content/*:any*/);
	file.size = content ? content.length : 0;
	if(opts) {
		if(opts.CLSID) file.clsid = opts.CLSID;
		if(opts.mt) file.mt = opts.mt;
		if(opts.ct) file.ct = opts.ct;
	}
	return file;
}

function cfb_del(cfb/*:CFBContainer*/, name/*:string*/)/*:boolean*/ {
	init_cfb(cfb);
	var file = CFB.find(cfb, name);
	if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
		cfb.FileIndex.splice(j, 1);
		cfb.FullPaths.splice(j, 1);
		return true;
	}
	return false;
}

function cfb_mov(cfb/*:CFBContainer*/, old_name/*:string*/, new_name/*:string*/)/*:boolean*/ {
	init_cfb(cfb);
	var file = CFB.find(cfb, old_name);
	if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
		cfb.FileIndex[j].name = filename(new_name);
		cfb.FullPaths[j] = new_name;
		return true;
	}
	return false;
}

function cfb_gc(cfb/*:CFBContainer*/)/*:void*/ { rebuild_cfb(cfb, true); }

exports$1.find = find;
exports$1.read = read;
exports$1.parse = parse;
exports$1.write = write;
exports$1.writeFile = write_file;
exports$1.utils = {
	cfb_new: cfb_new,
	cfb_add: cfb_add,
	cfb_del: cfb_del,
	cfb_mov: cfb_mov,
	cfb_gc: cfb_gc,
	ReadShift: ReadShift,
	CheckField: CheckField,
	prep_blob: prep_blob,
	bconcat: bconcat,
	use_zlib: use_zlib,
	_deflateRaw: _deflate,
	_inflateRaw: _inflate,
	consts: consts
};

return exports$1;
})();

let _fs = void 0;
function set_fs(fs) { _fs = fs; }

/* normalize data for blob ctor */
function blobify(data) {
	if(typeof data === "string") return s2ab(data);
	if(Array.isArray(data)) return a2u(data);
	return data;
}
/* write or download file */
function write_dl(fname/*:string*/, payload/*:any*/, enc/*:?string*/) {
	/*global IE_SaveFile, Blob, navigator, saveAs, document, File, chrome */
	if(typeof _fs !== 'undefined' && _fs.writeFileSync) return enc ? _fs.writeFileSync(fname, payload, enc) : _fs.writeFileSync(fname, payload);
	if(typeof Deno !== 'undefined') {
		/* in this spot, it's safe to assume typed arrays and TextEncoder/TextDecoder exist */
		if(enc && typeof payload == "string") switch(enc) {
			case "utf8": payload = new TextEncoder(enc).encode(payload); break;
			case "binary": payload = s2ab(payload); break;
			/* TODO: binary equivalent */
			default: throw new Error("Unsupported encoding " + enc);
		}
		return Deno.writeFileSync(fname, payload);
	}
	var data = (enc == "utf8") ? utf8write(payload) : payload;
	/*:: declare var IE_SaveFile: any; */
	if(typeof IE_SaveFile !== 'undefined') return IE_SaveFile(data, fname);
	if(typeof Blob !== 'undefined') {
		var blob = new Blob([blobify(data)], {type:"application/octet-stream"});
		/*:: declare var navigator: any; */
		if(typeof navigator !== 'undefined' && navigator.msSaveBlob) return navigator.msSaveBlob(blob, fname);
		/*:: declare var saveAs: any; */
		if(typeof saveAs !== 'undefined') return saveAs(blob, fname);
		if(typeof URL !== 'undefined' && typeof document !== 'undefined' && document.createElement && URL.createObjectURL) {
			var url = URL.createObjectURL(blob);
			/*:: declare var chrome: any; */
			if(typeof chrome === 'object' && typeof (chrome.downloads||{}).download == "function") {
				if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
				return chrome.downloads.download({ url: url, filename: fname, saveAs: true});
			}
			var a = document.createElement("a");
			if(a.download != null) {
				/*:: if(document.body == null) throw new Error("unreachable"); */
				a.download = fname; a.href = url; document.body.appendChild(a); a.click();
				/*:: if(document.body == null) throw new Error("unreachable"); */ document.body.removeChild(a);
				if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
				return url;
			}
		}
	}
	// $FlowIgnore
	if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
		// $FlowIgnore
		var out = File(fname); out.open("w"); out.encoding = "binary";
		if(Array.isArray(payload)) payload = a2s(payload);
		out.write(payload); out.close(); return payload;
	} catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
	throw new Error("cannot save file " + fname);
}

/* read binary data from file */
function read_binary(path/*:string*/) {
	if(typeof _fs !== 'undefined') return _fs.readFileSync(path);
	if(typeof Deno !== 'undefined') return Deno.readFileSync(path);
	// $FlowIgnore
	if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
		// $FlowIgnore
		var infile = File(path); infile.open("r"); infile.encoding = "binary";
		var data = infile.read(); infile.close();
		return data;
	} catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
	throw new Error("Cannot access file " + path);
}
function keys(o/*:any*/)/*:Array<any>*/ {
	var ks = Object.keys(o), o2 = [];
	for(var i = 0; i < ks.length; ++i) if(Object.prototype.hasOwnProperty.call(o, ks[i])) o2.push(ks[i]);
	return o2;
}

function evert_key(obj/*:any*/, key/*:string*/)/*:EvertType*/ {
	var o = ([]/*:any*/), K = keys(obj);
	for(var i = 0; i !== K.length; ++i) if(o[obj[K[i]][key]] == null) o[obj[K[i]][key]] = K[i];
	return o;
}

function evert(obj/*:any*/)/*:EvertType*/ {
	var o = ([]/*:any*/), K = keys(obj);
	for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = K[i];
	return o;
}

function evert_num(obj/*:any*/)/*:EvertNumType*/ {
	var o = ([]/*:any*/), K = keys(obj);
	for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = parseInt(K[i],10);
	return o;
}

function evert_arr(obj/*:any*/)/*:EvertArrType*/ {
	var o/*:EvertArrType*/ = ([]/*:any*/), K = keys(obj);
	for(var i = 0; i !== K.length; ++i) {
		if(o[obj[K[i]]] == null) o[obj[K[i]]] = [];
		o[obj[K[i]]].push(K[i]);
	}
	return o;
}

var basedate = /*#__PURE__*/new Date(1899, 11, 30, 0, 0, 0); // 2209161600000
function datenum(v/*:Date*/, date1904/*:?boolean*/)/*:number*/ {
	var epoch = /*#__PURE__*/v.getTime();
	if(date1904) epoch -= 1462*24*60*60*1000;
	var dnthresh = /*#__PURE__*/basedate.getTime() + (/*#__PURE__*/v.getTimezoneOffset() - /*#__PURE__*/basedate.getTimezoneOffset()) * 60000;
	return (epoch - dnthresh) / (24 * 60 * 60 * 1000);
}
var refdate = /*#__PURE__*/new Date();
var dnthresh = /*#__PURE__*/basedate.getTime() + (/*#__PURE__*/refdate.getTimezoneOffset() - /*#__PURE__*/basedate.getTimezoneOffset()) * 60000;
var refoffset = /*#__PURE__*/refdate.getTimezoneOffset();
function numdate(v/*:number*/)/*:Date*/ {
	var out = new Date();
	out.setTime(v * 24 * 60 * 60 * 1000 + dnthresh);
	if (out.getTimezoneOffset() !== refoffset) {
		out.setTime(out.getTime() + (out.getTimezoneOffset() - refoffset) * 60000);
	}
	return out;
}

/* ISO 8601 Duration */
function parse_isodur(s) {
	var sec = 0, mt = 0, time = false;
	var m = s.match(/P([0-9\.]+Y)?([0-9\.]+M)?([0-9\.]+D)?T([0-9\.]+H)?([0-9\.]+M)?([0-9\.]+S)?/);
	if(!m) throw new Error("|" + s + "| is not an ISO8601 Duration");
	for(var i = 1; i != m.length; ++i) {
		if(!m[i]) continue;
		mt = 1;
		if(i > 3) time = true;
		switch(m[i].slice(m[i].length-1)) {
			case 'Y':
				throw new Error("Unsupported ISO Duration Field: " + m[i].slice(m[i].length-1));
			case 'D': mt *= 24;
				/* falls through */
			case 'H': mt *= 60;
				/* falls through */
			case 'M':
				if(!time) throw new Error("Unsupported ISO Duration Field: M");
				else mt *= 60;
				/* falls through */
			case 'S': break;
		}
		sec += mt * parseInt(m[i], 10);
	}
	return sec;
}

var good_pd_date_1 = /*#__PURE__*/new Date('2017-02-19T19:06:09.000Z');
var good_pd_date = /*#__PURE__*/isNaN(/*#__PURE__*/good_pd_date_1.getFullYear()) ? /*#__PURE__*/new Date('2/19/17') : good_pd_date_1;
var good_pd = /*#__PURE__*/good_pd_date.getFullYear() == 2017;
/* parses a date as a local date */
function parseDate(str/*:string|Date*/, fixdate/*:?number*/)/*:Date*/ {
	var d = new Date(str);
	if(good_pd) {
		/*:: if(fixdate == null) fixdate = 0; */
		if(fixdate > 0) d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
		else if(fixdate < 0) d.setTime(d.getTime() - d.getTimezoneOffset() * 60 * 1000);
		return d;
	}
	if(str instanceof Date) return str;
	if(good_pd_date.getFullYear() == 1917 && !isNaN(d.getFullYear())) {
		var s = d.getFullYear();
		if(str.indexOf("" + s) > -1) return d;
		d.setFullYear(d.getFullYear() + 100); return d;
	}
	var n = str.match(/\d+/g)||["2017","2","19","0","0","0"];
	var out = new Date(+n[0], +n[1] - 1, +n[2], (+n[3]||0), (+n[4]||0), (+n[5]||0));
	if(str.indexOf("Z") > -1) out = new Date(out.getTime() - out.getTimezoneOffset() * 60 * 1000);
	return out;
}

function cc2str(arr/*:Array<number>*/, debomit)/*:string*/ {
	if(has_buf && Buffer.isBuffer(arr)) {
		if(debomit) {
			if(arr[0] == 0xFF && arr[1] == 0xFE) return utf8write(arr.slice(2).toString("utf16le"));
			if(arr[1] == 0xFE && arr[2] == 0xFF) return utf8write(utf16beread(arr.slice(2).toString("binary")));
		}
		return arr.toString("binary");
	}

	if(typeof TextDecoder !== "undefined") try {
		if(debomit) {
			if(arr[0] == 0xFF && arr[1] == 0xFE) return utf8write(new TextDecoder("utf-16le").decode(arr.slice(2)));
			if(arr[0] == 0xFE && arr[1] == 0xFF) return utf8write(new TextDecoder("utf-16be").decode(arr.slice(2)));
		}
		var rev = {
			"\u20ac": "\x80", "\u201a": "\x82", "\u0192": "\x83", "\u201e": "\x84",
			"\u2026": "\x85", "\u2020": "\x86", "\u2021": "\x87", "\u02c6": "\x88",
			"\u2030": "\x89", "\u0160": "\x8a", "\u2039": "\x8b", "\u0152": "\x8c",
			"\u017d": "\x8e", "\u2018": "\x91", "\u2019": "\x92", "\u201c": "\x93",
			"\u201d": "\x94", "\u2022": "\x95", "\u2013": "\x96", "\u2014": "\x97",
			"\u02dc": "\x98", "\u2122": "\x99", "\u0161": "\x9a", "\u203a": "\x9b",
			"\u0153": "\x9c", "\u017e": "\x9e", "\u0178": "\x9f"
		};
		if(Array.isArray(arr)) arr = new Uint8Array(arr);
		return new TextDecoder("latin1").decode(arr).replace(/[€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ]/g, function(c) { return rev[c] || c; });
	} catch(e) {}

	var o = [];
	for(var i = 0; i != arr.length; ++i) o.push(String.fromCharCode(arr[i]));
	return o.join("");
}

function dup(o/*:any*/)/*:any*/ {
	if(typeof JSON != 'undefined' && !Array.isArray(o)) return JSON.parse(JSON.stringify(o));
	if(typeof o != 'object' || o == null) return o;
	if(o instanceof Date) return new Date(o.getTime());
	var out = {};
	for(var k in o) if(Object.prototype.hasOwnProperty.call(o, k)) out[k] = dup(o[k]);
	return out;
}

function fill$1(c/*:string*/,l/*:number*/)/*:string*/ { var o = ""; while(o.length < l) o+=c; return o; }

/* TODO: stress test */
function fuzzynum(s/*:string*/)/*:number*/ {
	var v/*:number*/ = Number(s);
	if(!isNaN(v)) return isFinite(v) ? v : NaN;
	if(!/\d/.test(s)) return v;
	var wt = 1;
	var ss = s.replace(/([\d]),([\d])/g,"$1$2").replace(/[$]/g,"").replace(/[%]/g, function() { wt *= 100; return "";});
	if(!isNaN(v = Number(ss))) return v / wt;
	ss = ss.replace(/[(](.*)[)]/,function($$, $1) { wt = -wt; return $1;});
	if(!isNaN(v = Number(ss))) return v / wt;
	return v;
}
var lower_months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
function fuzzydate(s/*:string*/)/*:Date*/ {
	var o = new Date(s), n = new Date(NaN);
	var y = o.getYear(), m = o.getMonth(), d = o.getDate();
	if(isNaN(d)) return n;
	var lower = s.toLowerCase();
	if(lower.match(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/)) {
		lower = lower.replace(/[^a-z]/g,"").replace(/([^a-z]|^)[ap]m?([^a-z]|$)/,"");
		if(lower.length > 3 && lower_months.indexOf(lower) == -1) return n;
	} else if(lower.match(/[a-z]/)) return n;
	if(y < 0 || y > 8099) return n;
	if((m > 0 || d > 1) && y != 101) return o;
	if(s.match(/[^-0-9:,\/\\]/)) return n;
	return o;
}

var split_regex = /*#__PURE__*/(function() {
	var safe_split_regex = "abacaba".split(/(:?b)/i).length == 5;
	return function split_regex(str/*:string*/, re, def/*:string*/)/*:Array<string>*/ {
		if(safe_split_regex || typeof re == "string") return str.split(re);
		var p = str.split(re), o = [p[0]];
		for(var i = 1; i < p.length; ++i) { o.push(def); o.push(p[i]); }
		return o;
	};
})();
function getdatastr(data)/*:?string*/ {
	if(!data) return null;
	if(data.content && data.type) return cc2str(data.content, true);
	if(data.data) return debom(data.data);
	if(data.asNodeBuffer && has_buf) return debom(data.asNodeBuffer().toString('binary'));
	if(data.asBinary) return debom(data.asBinary());
	if(data._data && data._data.getContent) return debom(cc2str(Array.prototype.slice.call(data._data.getContent(),0)));
	return null;
}

function getdatabin(data) {
	if(!data) return null;
	if(data.data) return char_codes(data.data);
	if(data.asNodeBuffer && has_buf) return data.asNodeBuffer();
	if(data._data && data._data.getContent) {
		var o = data._data.getContent();
		if(typeof o == "string") return char_codes(o);
		return Array.prototype.slice.call(o);
	}
	if(data.content && data.type) return data.content;
	return null;
}

function getdata(data) { return (data && data.name.slice(-4) === ".bin") ? getdatabin(data) : getdatastr(data); }

/* Part 2 Section 10.1.2 "Mapping Content Types" Names are case-insensitive */
/* OASIS does not comment on filename case sensitivity */
function safegetzipfile(zip, file/*:string*/) {
	var k = zip.FullPaths || keys(zip.files);
	var f = file.toLowerCase().replace(/[\/]/g, '\\'), g = f.replace(/\\/g,'\/');
	for(var i=0; i<k.length; ++i) {
		var n = k[i].replace(/^Root Entry[\/]/,"").toLowerCase();
		if(f == n || g == n) return zip.files ? zip.files[k[i]] : zip.FileIndex[i];
	}
	return null;
}

function getzipfile(zip, file/*:string*/) {
	var o = safegetzipfile(zip, file);
	if(o == null) throw new Error("Cannot find file " + file + " in zip");
	return o;
}

function getzipdata(zip, file/*:string*/, safe/*:?boolean*/)/*:any*/ {
	if(!safe) return getdata(getzipfile(zip, file));
	if(!file) return null;
	try { return getzipdata(zip, file); } catch(e) { return null; }
}

function getzipstr(zip, file/*:string*/, safe/*:?boolean*/)/*:?string*/ {
	if(!safe) return getdatastr(getzipfile(zip, file));
	if(!file) return null;
	try { return getzipstr(zip, file); } catch(e) { return null; }
}

function getzipbin(zip, file/*:string*/, safe/*:?boolean*/)/*:any*/ {
	if(!safe) return getdatabin(getzipfile(zip, file));
	if(!file) return null;
	try { return getzipbin(zip, file); } catch(e) { return null; }
}

function zipentries(zip) {
	var k = zip.FullPaths || keys(zip.files), o = [];
	for(var i = 0; i < k.length; ++i) if(k[i].slice(-1) != '/') o.push(k[i].replace(/^Root Entry[\/]/, ""));
	return o.sort();
}

function zip_add_file(zip, path, content) {
	if(zip.FullPaths) {
		if(typeof content == "string") {
			var res;
			if(has_buf) res = Buffer_from(content);
			/* TODO: investigate performance in Edge 13 */
			//else if(typeof TextEncoder !== "undefined") res = new TextEncoder().encode(content);
			else res = utf8decode(content);
			return CFB.utils.cfb_add(zip, path, res);
		}
		CFB.utils.cfb_add(zip, path, content);
	}
	else zip.file(path, content);
}

function zip_new() { return CFB.utils.cfb_new(); }

function zip_read(d, o) {
	switch(o.type) {
		case "base64": return CFB.read(d, { type: "base64" });
		case "binary": return CFB.read(d, { type: "binary" });
		case "buffer": case "array": return CFB.read(d, { type: "buffer" });
	}
	throw new Error("Unrecognized type " + o.type);
}

function resolve_path(path/*:string*/, base/*:string*/)/*:string*/ {
	if(path.charAt(0) == "/") return path.slice(1);
	var result = base.split('/');
	if(base.slice(-1) != "/") result.pop(); // folder path
	var target = path.split('/');
	while (target.length !== 0) {
		var step = target.shift();
		if (step === '..') result.pop();
		else if (step !== '.') result.push(step);
	}
	return result.join('/');
}
var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';
var attregexg=/([^"\s?>\/]+)\s*=\s*((?:")([^"]*)(?:")|(?:')([^']*)(?:')|([^'">\s]+))/g;
var tagregex1=/<[\/\?]?[a-zA-Z0-9:_-]+(?:\s+[^"\s?>\/]+\s*=\s*(?:"[^"]*"|'[^']*'|[^'">\s=]+))*\s*[\/\?]?>/mg, tagregex2 = /<[^>]*>/g;
var tagregex = /*#__PURE__*/XML_HEADER.match(tagregex1) ? tagregex1 : tagregex2;
var nsregex=/<\w*:/, nsregex2 = /<(\/?)\w+:/;
function parsexmltag(tag/*:string*/, skip_root/*:?boolean*/, skip_LC/*:?boolean*/)/*:any*/ {
	var z = ({}/*:any*/);
	var eq = 0, c = 0;
	for(; eq !== tag.length; ++eq) if((c = tag.charCodeAt(eq)) === 32 || c === 10 || c === 13) break;
	if(!skip_root) z[0] = tag.slice(0, eq);
	if(eq === tag.length) return z;
	var m = tag.match(attregexg), j=0, v="", i=0, q="", cc="", quot = 1;
	if(m) for(i = 0; i != m.length; ++i) {
		cc = m[i];
		for(c=0; c != cc.length; ++c) if(cc.charCodeAt(c) === 61) break;
		q = cc.slice(0,c).trim();
		while(cc.charCodeAt(c+1) == 32) ++c;
		quot = ((eq=cc.charCodeAt(c+1)) == 34 || eq == 39) ? 1 : 0;
		v = cc.slice(c+1+quot, cc.length-quot);
		for(j=0;j!=q.length;++j) if(q.charCodeAt(j) === 58) break;
		if(j===q.length) {
			if(q.indexOf("_") > 0) q = q.slice(0, q.indexOf("_")); // from ods
			z[q] = v;
			if(!skip_LC) z[q.toLowerCase()] = v;
		}
		else {
			var k = (j===5 && q.slice(0,5)==="xmlns"?"xmlns":"")+q.slice(j+1);
			if(z[k] && q.slice(j-3,j) == "ext") continue; // from ods
			z[k] = v;
			if(!skip_LC) z[k.toLowerCase()] = v;
		}
	}
	return z;
}
function strip_ns(x/*:string*/)/*:string*/ { return x.replace(nsregex2, "<$1"); }

var encodings = {
	'&quot;': '"',
	'&apos;': "'",
	'&gt;': '>',
	'&lt;': '<',
	'&amp;': '&'
};
var rencoding = /*#__PURE__*/evert(encodings);
//var rencstr = "&<>'\"".split("");

// TODO: CP remap (need to read file version to determine OS)
var unescapexml/*:StringConv*/ = /*#__PURE__*/(function() {
	/* 22.4.2.4 bstr (Basic String) */
	var encregex = /&(?:quot|apos|gt|lt|amp|#x?([\da-fA-F]+));/ig, coderegex = /_x([\da-fA-F]{4})_/ig;
	return function unescapexml(text/*:string*/)/*:string*/ {
		var s = text + '', i = s.indexOf("<![CDATA[");
		if(i == -1) return s.replace(encregex, function($$, $1) { return encodings[$$]||String.fromCharCode(parseInt($1,$$.indexOf("x")>-1?16:10))||$$; }).replace(coderegex,function(m,c) {return String.fromCharCode(parseInt(c,16));});
		var j = s.indexOf("]]>");
		return unescapexml(s.slice(0, i)) + s.slice(i+9,j) + unescapexml(s.slice(j+3));
	};
})();

var decregex=/[&<>'"]/g, charegex = /[\u0000-\u0008\u000b-\u001f]/g;
function escapexml(text/*:string*/)/*:string*/{
	var s = text + '';
	return s.replace(decregex, function(y) { return rencoding[y]; }).replace(charegex,function(s) { return "_x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + "_";});
}
function escapexmltag(text/*:string*/)/*:string*/{ return escapexml(text).replace(/ /g,"_x0020_"); }

var htmlcharegex = /[\u0000-\u001f]/g;
function escapehtml(text/*:string*/)/*:string*/{
	var s = text + '';
	return s.replace(decregex, function(y) { return rencoding[y]; }).replace(/\n/g, "<br/>").replace(htmlcharegex,function(s) { return "&#x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + ";"; });
}

function escapexlml(text/*:string*/)/*:string*/{
	var s = text + '';
	return s.replace(decregex, function(y) { return rencoding[y]; }).replace(htmlcharegex,function(s) { return "&#x" + (s.charCodeAt(0).toString(16)).toUpperCase() + ";"; });
}

/* TODO: handle codepages */
var xlml_fixstr/*:StringConv*/ = /*#__PURE__*/(function() {
	var entregex = /&#(\d+);/g;
	function entrepl($$/*:string*/,$1/*:string*/)/*:string*/ { return String.fromCharCode(parseInt($1,10)); }
	return function xlml_fixstr(str/*:string*/)/*:string*/ { return str.replace(entregex,entrepl); };
})();
function xlml_unfixstr(str/*:string*/)/*:string*/ { return str.replace(/(\r\n|[\r\n])/g,"\&#10;"); }

function parsexmlbool(value/*:any*/)/*:boolean*/ {
	switch(value) {
		case 1: case true: case '1': case 'true': case 'TRUE': return true;
		/* case '0': case 'false': case 'FALSE':*/
		default: return false;
	}
}

function utf8reada(orig/*:string*/)/*:string*/ {
	var out = "", i = 0, c = 0, d = 0, e = 0, f = 0, w = 0;
	while (i < orig.length) {
		c = orig.charCodeAt(i++);
		if (c < 128) { out += String.fromCharCode(c); continue; }
		d = orig.charCodeAt(i++);
		if (c>191 && c<224) { f = ((c & 31) << 6); f |= (d & 63); out += String.fromCharCode(f); continue; }
		e = orig.charCodeAt(i++);
		if (c < 240) { out += String.fromCharCode(((c & 15) << 12) | ((d & 63) << 6) | (e & 63)); continue; }
		f = orig.charCodeAt(i++);
		w = (((c & 7) << 18) | ((d & 63) << 12) | ((e & 63) << 6) | (f & 63))-65536;
		out += String.fromCharCode(0xD800 + ((w>>>10)&1023));
		out += String.fromCharCode(0xDC00 + (w&1023));
	}
	return out;
}

function utf8readb(data) {
	var out = new_raw_buf(2*data.length), w, i, j = 1, k = 0, ww=0, c;
	for(i = 0; i < data.length; i+=j) {
		j = 1;
		if((c=data.charCodeAt(i)) < 128) w = c;
		else if(c < 224) { w = (c&31)*64+(data.charCodeAt(i+1)&63); j=2; }
		else if(c < 240) { w=(c&15)*4096+(data.charCodeAt(i+1)&63)*64+(data.charCodeAt(i+2)&63); j=3; }
		else { j = 4;
			w = (c & 7)*262144+(data.charCodeAt(i+1)&63)*4096+(data.charCodeAt(i+2)&63)*64+(data.charCodeAt(i+3)&63);
			w -= 65536; ww = 0xD800 + ((w>>>10)&1023); w = 0xDC00 + (w&1023);
		}
		if(ww !== 0) { out[k++] = ww&255; out[k++] = ww>>>8; ww = 0; }
		out[k++] = w%256; out[k++] = w>>>8;
	}
	return out.slice(0,k).toString('ucs2');
}

function utf8readc(data) { return Buffer_from(data, 'binary').toString('utf8'); }

var utf8corpus = "foo bar baz\u00e2\u0098\u0083\u00f0\u009f\u008d\u00a3";
var utf8read = has_buf && (/*#__PURE__*/utf8readc(utf8corpus) == /*#__PURE__*/utf8reada(utf8corpus) && utf8readc || /*#__PURE__*/utf8readb(utf8corpus) == /*#__PURE__*/utf8reada(utf8corpus) && utf8readb) || utf8reada;

var utf8write/*:StringConv*/ = has_buf ? function(data) { return Buffer_from(data, 'utf8').toString("binary"); } : function(orig/*:string*/)/*:string*/ {
	var out/*:Array<string>*/ = [], i = 0, c = 0, d = 0;
	while(i < orig.length) {
		c = orig.charCodeAt(i++);
		switch(true) {
			case c < 128: out.push(String.fromCharCode(c)); break;
			case c < 2048:
				out.push(String.fromCharCode(192 + (c >> 6)));
				out.push(String.fromCharCode(128 + (c & 63)));
				break;
			case c >= 55296 && c < 57344:
				c -= 55296; d = orig.charCodeAt(i++) - 56320 + (c<<10);
				out.push(String.fromCharCode(240 + ((d >>18) & 7)));
				out.push(String.fromCharCode(144 + ((d >>12) & 63)));
				out.push(String.fromCharCode(128 + ((d >> 6) & 63)));
				out.push(String.fromCharCode(128 + (d & 63)));
				break;
			default:
				out.push(String.fromCharCode(224 + (c >> 12)));
				out.push(String.fromCharCode(128 + ((c >> 6) & 63)));
				out.push(String.fromCharCode(128 + (c & 63)));
		}
	}
	return out.join("");
};

// matches <foo>...</foo> extracts content
var matchtag = /*#__PURE__*/(function() {
	var mtcache/*:{[k:string]:RegExp}*/ = ({}/*:any*/);
	return function matchtag(f/*:string*/,g/*:?string*/)/*:RegExp*/ {
		var t = f+"|"+(g||"");
		if(mtcache[t]) return mtcache[t];
		return (mtcache[t] = new RegExp('<(?:\\w+:)?'+f+'(?: xml:space="preserve")?(?:[^>]*)>([\\s\\S]*?)</(?:\\w+:)?'+f+'>',((g||"")/*:any*/)));
	};
})();

var htmldecode/*:{(s:string):string}*/ = /*#__PURE__*/(function() {
	var entities/*:Array<[RegExp, string]>*/ = [
		['nbsp', ' '], ['middot', '·'],
		['quot', '"'], ['apos', "'"], ['gt',   '>'], ['lt',   '<'], ['amp',  '&']
	].map(function(x/*:[string, string]*/) { return [new RegExp('&' + x[0] + ';', "ig"), x[1]]; });
	return function htmldecode(str/*:string*/)/*:string*/ {
		var o = str
				// Remove new lines and spaces from start of content
				.replace(/^[\t\n\r ]+/, "")
				// Remove new lines and spaces from end of content
				.replace(/[\t\n\r ]+$/,"")
				// Added line which removes any white space characters after and before html tags
				.replace(/>\s+/g,">").replace(/\s+</g,"<")
				// Replace remaining new lines and spaces with space
				.replace(/[\t\n\r ]+/g, " ")
				// Replace <br> tags with new lines
				.replace(/<\s*[bB][rR]\s*\/?>/g,"\n")
				// Strip HTML elements
				.replace(/<[^>]*>/g,"");
		for(var i = 0; i < entities.length; ++i) o = o.replace(entities[i][0], entities[i][1]);
		return o;
	};
})();

var vtregex = /*#__PURE__*/(function(){ var vt_cache = {};
	return function vt_regex(bt) {
		if(vt_cache[bt] !== undefined) return vt_cache[bt];
		return (vt_cache[bt] = new RegExp("<(?:vt:)?" + bt + ">([\\s\\S]*?)</(?:vt:)?" + bt + ">", 'g') );
};})();
var vtvregex = /<\/?(?:vt:)?variant>/g, vtmregex = /<(?:vt:)([^>]*)>([\s\S]*)</;
function parseVector(data/*:string*/, opts)/*:Array<{v:string,t:string}>*/ {
	var h = parsexmltag(data);

	var matches/*:Array<string>*/ = data.match(vtregex(h.baseType))||[];
	var res/*:Array<any>*/ = [];
	if(matches.length != h.size) {
		if(opts.WTF) throw new Error("unexpected vector length " + matches.length + " != " + h.size);
		return res;
	}
	matches.forEach(function(x/*:string*/) {
		var v = x.replace(vtvregex,"").match(vtmregex);
		if(v) res.push({v:utf8read(v[2]), t:v[1]});
	});
	return res;
}

var wtregex = /(^\s|\s$|\n)/;
function writetag(f/*:string*/,g/*:string*/)/*:string*/ { return '<' + f + (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f + '>'; }

function wxt_helper(h)/*:string*/ { return keys(h).map(function(k) { return " " + k + '="' + h[k] + '"';}).join(""); }
function writextag(f/*:string*/,g/*:?string*/,h) { return '<' + f + ((h != null) ? wxt_helper(h) : "") + ((g != null) ? (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f : "/") + '>';}

function write_w3cdtf(d/*:Date*/, t/*:?boolean*/)/*:string*/ { try { return d.toISOString().replace(/\.\d*/,""); } catch(e) { if(t) throw e; } return ""; }

function write_vt(s, xlsx/*:?boolean*/)/*:string*/ {
	switch(typeof s) {
		case 'string':
			var o = writextag('vt:lpwstr', escapexml(s));
			if(xlsx) o = o.replace(/&quot;/g, "_x0022_");
			return o;
		case 'number': return writextag((s|0)==s?'vt:i4':'vt:r8', escapexml(String(s)));
		case 'boolean': return writextag('vt:bool',s?'true':'false');
	}
	if(s instanceof Date) return writextag('vt:filetime', write_w3cdtf(s));
	throw new Error("Unable to serialize " + s);
}

function xlml_normalize(d)/*:string*/ {
	if(has_buf &&/*::typeof Buffer !== "undefined" && d != null && d instanceof Buffer &&*/ Buffer.isBuffer(d)) return d.toString('utf8');
	if(typeof d === 'string') return d;
	/* duktape */
	if(typeof Uint8Array !== 'undefined' && d instanceof Uint8Array) return utf8read(a2s(ab2a(d)));
	throw new Error("Bad input format: expected Buffer or string");
}
/* UOS uses CJK in tags */
var xlmlregex = /<(\/?)([^\s?><!\/:]*:|)([^\s?<>:\/]+)(?:[\s?:\/][^>]*)?>/mg;
//var xlmlregex = /<(\/?)([a-z0-9]*:|)(\w+)[^>]*>/mg;

var XMLNS = ({
	CORE_PROPS: 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties',
	CUST_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",
	EXT_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",
	CT: 'http://schemas.openxmlformats.org/package/2006/content-types',
	RELS: 'http://schemas.openxmlformats.org/package/2006/relationships',
	TCMNT: 'http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments',
	'dc': 'http://purl.org/dc/elements/1.1/',
	'dcterms': 'http://purl.org/dc/terms/',
	'dcmitype': 'http://purl.org/dc/dcmitype/',
	'mx': 'http://schemas.microsoft.com/office/mac/excel/2008/main',
	'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
	'sjs': 'http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties',
	'vt': 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes',
	'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
	'xsd': 'http://www.w3.org/2001/XMLSchema'
}/*:any*/);

var XMLNS_main = [
	'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
	'http://purl.oclc.org/ooxml/spreadsheetml/main',
	'http://schemas.microsoft.com/office/excel/2006/main',
	'http://schemas.microsoft.com/office/excel/2006/2'
];

var XLMLNS = ({
	'o':    'urn:schemas-microsoft-com:office:office',
	'x':    'urn:schemas-microsoft-com:office:excel',
	'ss':   'urn:schemas-microsoft-com:office:spreadsheet',
	'dt':   'uuid:C2F41010-65B3-11d1-A29F-00AA00C14882',
	'mv':   'http://macVmlSchemaUri',
	'v':    'urn:schemas-microsoft-com:vml',
	'html': 'http://www.w3.org/TR/REC-html40'
}/*:any*/);
function read_double_le(b/*:RawBytes|CFBlob*/, idx/*:number*/)/*:number*/ {
	var s = 1 - 2 * (b[idx + 7] >>> 7);
	var e = ((b[idx + 7] & 0x7f) << 4) + ((b[idx + 6] >>> 4) & 0x0f);
	var m = (b[idx+6]&0x0f);
	for(var i = 5; i >= 0; --i) m = m * 256 + b[idx + i];
	if(e == 0x7ff) return m == 0 ? (s * Infinity) : NaN;
	if(e == 0) e = -1022;
	else { e -= 1023; m += Math.pow(2,52); }
	return s * Math.pow(2, e - 52) * m;
}

function write_double_le(b/*:RawBytes|CFBlob*/, v/*:number*/, idx/*:number*/) {
	var bs = ((((v < 0) || (1/v == -Infinity)) ? 1 : 0) << 7), e = 0, m = 0;
	var av = bs ? (-v) : v;
	if(!isFinite(av)) { e = 0x7ff; m = isNaN(v) ? 0x6969 : 0; }
	else if(av == 0) e = m = 0;
	else {
		e = Math.floor(Math.log(av) / Math.LN2);
		m = av * Math.pow(2, 52 - e);
		if((e <= -1023) && (!isFinite(m) || (m < Math.pow(2,52)))) { e = -1022; }
		else { m -= Math.pow(2,52); e+=1023; }
	}
	for(var i = 0; i <= 5; ++i, m/=256) b[idx + i] = m & 0xff;
	b[idx + 6] = ((e & 0x0f) << 4) | (m & 0xf);
	b[idx + 7] = (e >> 4) | bs;
}

var ___toBuffer = function(bufs/*:Array<Array<RawBytes> >*/)/*:RawBytes*/ { var x=[],w=10240; for(var i=0;i<bufs[0].length;++i) if(bufs[0][i]) for(var j=0,L=bufs[0][i].length;j<L;j+=w) x.push.apply(x, bufs[0][i].slice(j,j+w)); return x; };
var __toBuffer = has_buf ? function(bufs) { return (bufs[0].length > 0 && Buffer.isBuffer(bufs[0][0])) ? Buffer.concat(bufs[0].map(function(x) { return Buffer.isBuffer(x) ? x : Buffer_from(x); })) : ___toBuffer(bufs);} : ___toBuffer;

var ___utf16le = function(b/*:RawBytes|CFBlob*/,s/*:number*/,e/*:number*/)/*:string*/ { var ss/*:Array<string>*/=[]; for(var i=s; i<e; i+=2) ss.push(String.fromCharCode(__readUInt16LE(b,i))); return ss.join("").replace(chr0,''); };
var __utf16le = has_buf ? function(b/*:RawBytes|CFBlob*/,s/*:number*/,e/*:number*/)/*:string*/ { if(!Buffer.isBuffer(b)/*:: || !(b instanceof Buffer)*/) return ___utf16le(b,s,e); return b.toString('utf16le',s,e).replace(chr0,'')/*.replace(chr1,'!')*/; } : ___utf16le;

var ___hexlify = function(b/*:RawBytes|CFBlob*/,s/*:number*/,l/*:number*/)/*:string*/ { var ss/*:Array<string>*/=[]; for(var i=s; i<s+l; ++i) ss.push(("0" + b[i].toString(16)).slice(-2)); return ss.join(""); };
var __hexlify = has_buf ? function(b/*:RawBytes|CFBlob*/,s/*:number*/,l/*:number*/)/*:string*/ { return Buffer.isBuffer(b)/*:: && b instanceof Buffer*/ ? b.toString('hex',s,s+l) : ___hexlify(b,s,l); } : ___hexlify;

var ___utf8 = function(b/*:RawBytes|CFBlob*/,s/*:number*/,e/*:number*/) { var ss=[]; for(var i=s; i<e; i++) ss.push(String.fromCharCode(__readUInt8(b,i))); return ss.join(""); };
var __utf8 = has_buf ? function utf8_b(b/*:RawBytes|CFBlob*/, s/*:number*/, e/*:number*/) { return (Buffer.isBuffer(b)/*:: && (b instanceof Buffer)*/) ? b.toString('utf8',s,e) : ___utf8(b,s,e); } : ___utf8;

var ___lpstr = function(b/*:RawBytes|CFBlob*/,i/*:number*/) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
var __lpstr = ___lpstr;

var ___cpstr = function(b/*:RawBytes|CFBlob*/,i/*:number*/) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
var __cpstr = ___cpstr;

var ___lpwstr = function(b/*:RawBytes|CFBlob*/,i/*:number*/) { var len = 2*__readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
var __lpwstr = ___lpwstr;

var ___lpp4 = function lpp4_(b/*:RawBytes|CFBlob*/,i/*:number*/) { var len = __readUInt32LE(b,i); return len > 0 ? __utf16le(b, i+4,i+4+len) : "";};
var __lpp4 = ___lpp4;

var ___8lpp4 = function(b/*:RawBytes|CFBlob*/,i/*:number*/) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len) : "";};
var __8lpp4 = ___8lpp4;

var ___double = function(b/*:RawBytes|CFBlob*/, idx/*:number*/) { return read_double_le(b, idx);};
var __double = ___double;

var is_buf = function is_buf_a(a) { return Array.isArray(a) || (typeof Uint8Array !== "undefined" && a instanceof Uint8Array); };

if(has_buf/*:: && typeof Buffer !== 'undefined'*/) {
	__lpstr = function lpstr_b(b/*:RawBytes|CFBlob*/, i/*:number*/) { if(!Buffer.isBuffer(b)/*:: || !(b instanceof Buffer)*/) return ___lpstr(b, i); var len = b.readUInt32LE(i); return len > 0 ? b.toString('utf8',i+4,i+4+len-1) : "";};
	__cpstr = function cpstr_b(b/*:RawBytes|CFBlob*/, i/*:number*/) { if(!Buffer.isBuffer(b)/*:: || !(b instanceof Buffer)*/) return ___cpstr(b, i); var len = b.readUInt32LE(i); return len > 0 ? b.toString('utf8',i+4,i+4+len-1) : "";};
	__lpwstr = function lpwstr_b(b/*:RawBytes|CFBlob*/, i/*:number*/) { if(!Buffer.isBuffer(b)/*:: || !(b instanceof Buffer)*/) return ___lpwstr(b, i); var len = 2*b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len-1);};
	__lpp4 = function lpp4_b(b/*:RawBytes|CFBlob*/, i/*:number*/) { if(!Buffer.isBuffer(b)/*:: || !(b instanceof Buffer)*/) return ___lpp4(b, i); var len = b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len);};
	__8lpp4 = function lpp4_8b(b/*:RawBytes|CFBlob*/, i/*:number*/) { if(!Buffer.isBuffer(b)/*:: || !(b instanceof Buffer)*/) return ___8lpp4(b, i); var len = b.readUInt32LE(i); return b.toString('utf8',i+4,i+4+len);};
	__double = function double_(b/*:RawBytes|CFBlob*/, i/*:number*/) { if(Buffer.isBuffer(b)/*::&& b instanceof Buffer*/) return b.readDoubleLE(i); return ___double(b,i); };
	is_buf = function is_buf_b(a) { return Buffer.isBuffer(a) || Array.isArray(a) || (typeof Uint8Array !== "undefined" && a instanceof Uint8Array); };
}

/* from js-xls */
function cpdoit() {
	__utf16le = function(b/*:RawBytes|CFBlob*/,s/*:number*/,e/*:number*/) { return $cptable.utils.decode(1200, b.slice(s,e)).replace(chr0, ''); };
	__utf8 = function(b/*:RawBytes|CFBlob*/,s/*:number*/,e/*:number*/) { return $cptable.utils.decode(65001, b.slice(s,e)); };
	__lpstr = function(b/*:RawBytes|CFBlob*/,i/*:number*/) { var len = __readUInt32LE(b,i); return len > 0 ? $cptable.utils.decode(current_ansi, b.slice(i+4, i+4+len-1)) : "";};
	__cpstr = function(b/*:RawBytes|CFBlob*/,i/*:number*/) { var len = __readUInt32LE(b,i); return len > 0 ? $cptable.utils.decode(current_codepage, b.slice(i+4, i+4+len-1)) : "";};
	__lpwstr = function(b/*:RawBytes|CFBlob*/,i/*:number*/) { var len = 2*__readUInt32LE(b,i); return len > 0 ? $cptable.utils.decode(1200, b.slice(i+4,i+4+len-1)) : "";};
	__lpp4 = function(b/*:RawBytes|CFBlob*/,i/*:number*/) { var len = __readUInt32LE(b,i); return len > 0 ? $cptable.utils.decode(1200, b.slice(i+4,i+4+len)) : "";};
	__8lpp4 = function(b/*:RawBytes|CFBlob*/,i/*:number*/) { var len = __readUInt32LE(b,i); return len > 0 ? $cptable.utils.decode(65001, b.slice(i+4,i+4+len)) : "";};
}
if(typeof $cptable !== 'undefined') cpdoit();

var __readUInt8 = function(b/*:RawBytes|CFBlob*/, idx/*:number*/)/*:number*/ { return b[idx]; };
var __readUInt16LE = function(b/*:RawBytes|CFBlob*/, idx/*:number*/)/*:number*/ { return (b[idx+1]*(1<<8))+b[idx]; };
var __readInt16LE = function(b/*:RawBytes|CFBlob*/, idx/*:number*/)/*:number*/ { var u = (b[idx+1]*(1<<8))+b[idx]; return (u < 0x8000) ? u : ((0xffff - u + 1) * -1); };
var __readUInt32LE = function(b/*:RawBytes|CFBlob*/, idx/*:number*/)/*:number*/ { return b[idx+3]*(1<<24)+(b[idx+2]<<16)+(b[idx+1]<<8)+b[idx]; };
var __readInt32LE = function(b/*:RawBytes|CFBlob*/, idx/*:number*/)/*:number*/ { return (b[idx+3]<<24)|(b[idx+2]<<16)|(b[idx+1]<<8)|b[idx]; };
var __readInt32BE = function(b/*:RawBytes|CFBlob*/, idx/*:number*/)/*:number*/ { return (b[idx]<<24)|(b[idx+1]<<16)|(b[idx+2]<<8)|b[idx+3]; };

function ReadShift(size/*:number*/, t/*:?string*/)/*:number|string*/ {
	var o="", oI/*:: :number = 0*/, oR, oo=[], w, vv, i, loc;
	switch(t) {
		case 'dbcs':
			loc = this.l;
			if(has_buf && Buffer.isBuffer(this)) o = this.slice(this.l, this.l+2*size).toString("utf16le");
			else for(i = 0; i < size; ++i) { o+=String.fromCharCode(__readUInt16LE(this, loc)); loc+=2; }
			size *= 2;
			break;

		case 'utf8': o = __utf8(this, this.l, this.l + size); break;
		case 'utf16le': size *= 2; o = __utf16le(this, this.l, this.l + size); break;

		case 'wstr':
			if(typeof $cptable !== 'undefined') o = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l+2*size));
			else return ReadShift.call(this, size, 'dbcs');
			size = 2 * size; break;

		/* [MS-OLEDS] 2.1.4 LengthPrefixedAnsiString */
		case 'lpstr-ansi': o = __lpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
		case 'lpstr-cp': o = __cpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
		/* [MS-OLEDS] 2.1.5 LengthPrefixedUnicodeString */
		case 'lpwstr': o = __lpwstr(this, this.l); size = 4 + 2 * __readUInt32LE(this, this.l); break;
		/* [MS-OFFCRYPTO] 2.1.2 Length-Prefixed Padded Unicode String (UNICODE-LP-P4) */
		case 'lpp4': size = 4 +  __readUInt32LE(this, this.l); o = __lpp4(this, this.l); if(size & 0x02) size += 2; break;
		/* [MS-OFFCRYPTO] 2.1.3 Length-Prefixed UTF-8 String (UTF-8-LP-P4) */
		case '8lpp4': size = 4 +  __readUInt32LE(this, this.l); o = __8lpp4(this, this.l); if(size & 0x03) size += 4 - (size & 0x03); break;

		case 'cstr': size = 0; o = "";
			while((w=__readUInt8(this, this.l + size++))!==0) oo.push(_getchar(w));
			o = oo.join(""); break;
		case '_wstr': size = 0; o = "";
			while((w=__readUInt16LE(this,this.l +size))!==0){oo.push(_getchar(w));size+=2;}
			size+=2; o = oo.join(""); break;

		/* sbcs and dbcs support continue records in the SST way TODO codepages */
		case 'dbcs-cont': o = ""; loc = this.l;
			for(i = 0; i < size; ++i) {
				if(this.lens && this.lens.indexOf(loc) !== -1) {
					w = __readUInt8(this, loc);
					this.l = loc + 1;
					vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
					return oo.join("") + vv;
				}
				oo.push(_getchar(__readUInt16LE(this, loc)));
				loc+=2;
			} o = oo.join(""); size *= 2; break;

		case 'cpstr':
			if(typeof $cptable !== 'undefined') {
				o = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l + size));
				break;
			}
		/* falls through */
		case 'sbcs-cont': o = ""; loc = this.l;
			for(i = 0; i != size; ++i) {
				if(this.lens && this.lens.indexOf(loc) !== -1) {
					w = __readUInt8(this, loc);
					this.l = loc + 1;
					vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
					return oo.join("") + vv;
				}
				oo.push(_getchar(__readUInt8(this, loc)));
				loc+=1;
			} o = oo.join(""); break;

		default:
	switch(size) {
		case 1: oI = __readUInt8(this, this.l); this.l++; return oI;
		case 2: oI = (t === 'i' ? __readInt16LE : __readUInt16LE)(this, this.l); this.l += 2; return oI;
		case 4: case -4:
			if(t === 'i' || ((this[this.l+3] & 0x80)===0)) { oI = ((size > 0) ? __readInt32LE : __readInt32BE)(this, this.l); this.l += 4; return oI; }
			else { oR = __readUInt32LE(this, this.l); this.l += 4; } return oR;
		case 8: case -8:
			if(t === 'f') {
				if(size == 8) oR = __double(this, this.l);
				else oR = __double([this[this.l+7],this[this.l+6],this[this.l+5],this[this.l+4],this[this.l+3],this[this.l+2],this[this.l+1],this[this.l+0]], 0);
				this.l += 8; return oR;
			} else size = 8;
		/* falls through */
		case 16: o = __hexlify(this, this.l, size); break;
	}}
	this.l+=size; return o;
}

var __writeUInt32LE = function(b/*:RawBytes|CFBlob*/, val/*:number*/, idx/*:number*/)/*:void*/ { b[idx] = (val & 0xFF); b[idx+1] = ((val >>> 8) & 0xFF); b[idx+2] = ((val >>> 16) & 0xFF); b[idx+3] = ((val >>> 24) & 0xFF); };
var __writeInt32LE  = function(b/*:RawBytes|CFBlob*/, val/*:number*/, idx/*:number*/)/*:void*/ { b[idx] = (val & 0xFF); b[idx+1] = ((val >> 8) & 0xFF); b[idx+2] = ((val >> 16) & 0xFF); b[idx+3] = ((val >> 24) & 0xFF); };
var __writeUInt16LE = function(b/*:RawBytes|CFBlob*/, val/*:number*/, idx/*:number*/)/*:void*/ { b[idx] = (val & 0xFF); b[idx+1] = ((val >>> 8) & 0xFF); };

function WriteShift(t/*:number*/, val/*:string|number*/, f/*:?string*/)/*:any*/ {
	var size = 0, i = 0;
	if(f === 'dbcs') {
		/*:: if(typeof val !== 'string') throw new Error("unreachable"); */
		for(i = 0; i != val.length; ++i) __writeUInt16LE(this, val.charCodeAt(i), this.l + 2 * i);
		size = 2 * val.length;
	} else if(f === 'sbcs') {
		if(typeof $cptable !== 'undefined' && current_ansi == 874) {
			/* TODO: use tables directly, don't encode */
			/*:: if(typeof val !== "string") throw new Error("unreachable"); */
			for(i = 0; i != val.length; ++i) {
				var cppayload = $cptable.utils.encode(current_ansi, val.charAt(i));
				this[this.l + i] = cppayload[0];
			}
		} else {
			/*:: if(typeof val !== 'string') throw new Error("unreachable"); */
			val = val.replace(/[^\x00-\x7F]/g, "_");
			/*:: if(typeof val !== 'string') throw new Error("unreachable"); */
			for(i = 0; i != val.length; ++i) this[this.l + i] = (val.charCodeAt(i) & 0xFF);
		}
		size = val.length;
	} else if(f === 'hex') {
		for(; i < t; ++i) {
			/*:: if(typeof val !== "string") throw new Error("unreachable"); */
			this[this.l++] = (parseInt(val.slice(2*i, 2*i+2), 16)||0);
		} return this;
	} else if(f === 'utf16le') {
			/*:: if(typeof val !== "string") throw new Error("unreachable"); */
			var end/*:number*/ = Math.min(this.l + t, this.length);
			for(i = 0; i < Math.min(val.length, t); ++i) {
				var cc = val.charCodeAt(i);
				this[this.l++] = (cc & 0xff);
				this[this.l++] = (cc >> 8);
			}
			while(this.l < end) this[this.l++] = 0;
			return this;
	} else /*:: if(typeof val === 'number') */ switch(t) {
		case  1: size = 1; this[this.l] = val&0xFF; break;
		case  2: size = 2; this[this.l] = val&0xFF; val >>>= 8; this[this.l+1] = val&0xFF; break;
		case  3: size = 3; this[this.l] = val&0xFF; val >>>= 8; this[this.l+1] = val&0xFF; val >>>= 8; this[this.l+2] = val&0xFF; break;
		case  4: size = 4; __writeUInt32LE(this, val, this.l); break;
		case  8: size = 8; if(f === 'f') { write_double_le(this, val, this.l); break; }
		/* falls through */
		case 16: break;
		case -4: size = 4; __writeInt32LE(this, val, this.l); break;
	}
	this.l += size; return this;
}

function CheckField(hexstr/*:string*/, fld/*:string*/)/*:void*/ {
	var m = __hexlify(this,this.l,hexstr.length>>1);
	if(m !== hexstr) throw new Error(fld + 'Expected ' + hexstr + ' saw ' + m);
	this.l += hexstr.length>>1;
}

function prep_blob(blob, pos/*:number*/)/*:void*/ {
	blob.l = pos;
	blob.read_shift = /*::(*/ReadShift/*:: :any)*/;
	blob.chk = CheckField;
	blob.write_shift = WriteShift;
}

function parsenoop(blob, length/*:: :number, opts?:any */) { blob.l += length; }

function new_buf(sz/*:number*/)/*:Block*/ {
	var o = new_raw_buf(sz);
	prep_blob(o, 0);
	return o;
}

/* [MS-XLSB] 2.1.4 Record */
function recordhopper(data, cb/*:RecordHopperCB*/, opts/*:?any*/) {
	if(!data) return;
	var tmpbyte, cntbyte, length;
	prep_blob(data, data.l || 0);
	var L = data.length, RT = 0, tgt = 0;
	while(data.l < L) {
		RT = data.read_shift(1);
		if(RT & 0x80) RT = (RT & 0x7F) + ((data.read_shift(1) & 0x7F)<<7);
		var R = XLSBRecordEnum[RT] || XLSBRecordEnum[0xFFFF];
		tmpbyte = data.read_shift(1);
		length = tmpbyte & 0x7F;
		for(cntbyte = 1; cntbyte <4 && (tmpbyte & 0x80); ++cntbyte) length += ((tmpbyte = data.read_shift(1)) & 0x7F)<<(7*cntbyte);
		tgt = data.l + length;
		var d = R.f && R.f(data, length, opts);
		data.l = tgt;
		if(cb(d, R, RT)) return;
	}
}

/* control buffer usage for fixed-length buffers */
function buf_array()/*:BufArray*/ {
	var bufs/*:Array<Block>*/ = [], blksz = has_buf ? 256 : 2048;
	var newblk = function ba_newblk(sz/*:number*/)/*:Block*/ {
		var o/*:Block*/ = (new_buf(sz)/*:any*/);
		prep_blob(o, 0);
		return o;
	};

	var curbuf/*:Block*/ = newblk(blksz);

	var endbuf = function ba_endbuf() {
		if(!curbuf) return;
		if(curbuf.length > curbuf.l) { curbuf = curbuf.slice(0, curbuf.l); curbuf.l = curbuf.length; }
		if(curbuf.length > 0) bufs.push(curbuf);
		curbuf = null;
	};

	var next = function ba_next(sz/*:number*/)/*:Block*/ {
		if(curbuf && (sz < (curbuf.length - curbuf.l))) return curbuf;
		endbuf();
		return (curbuf = newblk(Math.max(sz+1, blksz)));
	};

	var end = function ba_end() {
		endbuf();
		return bconcat(bufs);
	};

	var push = function ba_push(buf) { endbuf(); curbuf = buf; if(curbuf.l == null) curbuf.l = curbuf.length; next(blksz); };

	return ({ next:next, push:push, end:end, _bufs:bufs }/*:any*/);
}

function write_record(ba/*:BufArray*/, type/*:number*/, payload, length/*:?number*/) {
	var t/*:number*/ = +type, l;
	if(isNaN(t)) return; // TODO: throw something here?
	if(!length) length = XLSBRecordEnum[t].p || (payload||[]).length || 0;
	l = 1 + (t >= 0x80 ? 1 : 0) + 1/* + length*/;
	if(length >= 0x80) ++l; if(length >= 0x4000) ++l; if(length >= 0x200000) ++l;
	var o = ba.next(l);
	if(t <= 0x7F) o.write_shift(1, t);
	else {
		o.write_shift(1, (t & 0x7F) + 0x80);
		o.write_shift(1, (t >> 7));
	}
	for(var i = 0; i != 4; ++i) {
		if(length >= 0x80) { o.write_shift(1, (length & 0x7F)+0x80); length >>= 7; }
		else { o.write_shift(1, length); break; }
	}
	if(/*:: length != null &&*/length > 0 && is_buf(payload)) ba.push(payload);
}
/* XLS ranges enforced */
function shift_cell_xls(cell/*:CellAddress*/, tgt/*:any*/, opts/*:?any*/)/*:CellAddress*/ {
	var out = dup(cell);
	if(tgt.s) {
		if(out.cRel) out.c += tgt.s.c;
		if(out.rRel) out.r += tgt.s.r;
	} else {
		if(out.cRel) out.c += tgt.c;
		if(out.rRel) out.r += tgt.r;
	}
	if(!opts || opts.biff < 12) {
		while(out.c >= 0x100) out.c -= 0x100;
		while(out.r >= 0x10000) out.r -= 0x10000;
	}
	return out;
}

function shift_range_xls(cell, range, opts) {
	var out = dup(cell);
	out.s = shift_cell_xls(out.s, range.s, opts);
	out.e = shift_cell_xls(out.e, range.s, opts);
	return out;
}

function encode_cell_xls(c/*:CellAddress*/, biff/*:number*/)/*:string*/ {
	if(c.cRel && c.c < 0) { c = dup(c); while(c.c < 0) c.c += (biff > 8) ? 0x4000 : 0x100; }
	if(c.rRel && c.r < 0) { c = dup(c); while(c.r < 0) c.r += (biff > 8) ? 0x100000 : ((biff > 5) ? 0x10000 : 0x4000); }
	var s = encode_cell(c);
	if(!c.cRel && c.cRel != null) s = fix_col(s);
	if(!c.rRel && c.rRel != null) s = fix_row(s);
	return s;
}

function encode_range_xls(r, opts)/*:string*/ {
	if(r.s.r == 0 && !r.s.rRel) {
		if(r.e.r == (opts.biff >= 12 ? 0xFFFFF : (opts.biff >= 8 ? 0x10000 : 0x4000)) && !r.e.rRel) {
			return (r.s.cRel ? "" : "$") + encode_col(r.s.c) + ":" + (r.e.cRel ? "" : "$") + encode_col(r.e.c);
		}
	}
	if(r.s.c == 0 && !r.s.cRel) {
		if(r.e.c == (opts.biff >= 12 ? 0x3FFF : 0xFF) && !r.e.cRel) {
			return (r.s.rRel ? "" : "$") + encode_row(r.s.r) + ":" + (r.e.rRel ? "" : "$") + encode_row(r.e.r);
		}
	}
	return encode_cell_xls(r.s, opts.biff) + ":" + encode_cell_xls(r.e, opts.biff);
}
function decode_row(rowstr/*:string*/)/*:number*/ { return parseInt(unfix_row(rowstr),10) - 1; }
function encode_row(row/*:number*/)/*:string*/ { return "" + (row + 1); }
function fix_row(cstr/*:string*/)/*:string*/ { return cstr.replace(/([A-Z]|^)(\d+)$/,"$1$$$2"); }
function unfix_row(cstr/*:string*/)/*:string*/ { return cstr.replace(/\$(\d+)$/,"$1"); }

function decode_col(colstr/*:string*/)/*:number*/ { var c = unfix_col(colstr), d = 0, i = 0; for(; i !== c.length; ++i) d = 26*d + c.charCodeAt(i) - 64; return d - 1; }
function encode_col(col/*:number*/)/*:string*/ { if(col < 0) throw new Error("invalid column " + col); var s=""; for(++col; col; col=Math.floor((col-1)/26)) s = String.fromCharCode(((col-1)%26) + 65) + s; return s; }
function fix_col(cstr/*:string*/)/*:string*/ { return cstr.replace(/^([A-Z])/,"$$$1"); }
function unfix_col(cstr/*:string*/)/*:string*/ { return cstr.replace(/^\$([A-Z])/,"$1"); }

function split_cell(cstr/*:string*/)/*:Array<string>*/ { return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/,"$1,$2").split(","); }
//function decode_cell(cstr/*:string*/)/*:CellAddress*/ { var splt = split_cell(cstr); return { c:decode_col(splt[0]), r:decode_row(splt[1]) }; }
function decode_cell(cstr/*:string*/)/*:CellAddress*/ {
	var R = 0, C = 0;
	for(var i = 0; i < cstr.length; ++i) {
		var cc = cstr.charCodeAt(i);
		if(cc >= 48 && cc <= 57) R = 10 * R + (cc - 48);
		else if(cc >= 65 && cc <= 90) C = 26 * C + (cc - 64);
	}
	return { c: C - 1, r:R - 1 };
}
//function encode_cell(cell/*:CellAddress*/)/*:string*/ { return encode_col(cell.c) + encode_row(cell.r); }
function encode_cell(cell/*:CellAddress*/)/*:string*/ {
	var col = cell.c + 1;
	var s="";
	for(; col; col=((col-1)/26)|0) s = String.fromCharCode(((col-1)%26) + 65) + s;
	return s + (cell.r + 1);
}
function decode_range(range/*:string*/)/*:Range*/ {
	var idx = range.indexOf(":");
	if(idx == -1) return { s: decode_cell(range), e: decode_cell(range) };
	return { s: decode_cell(range.slice(0, idx)), e: decode_cell(range.slice(idx + 1)) };
}
/*# if only one arg, it is assumed to be a Range.  If 2 args, both are cell addresses */
function encode_range(cs/*:CellAddrSpec|Range*/,ce/*:?CellAddrSpec*/)/*:string*/ {
	if(typeof ce === 'undefined' || typeof ce === 'number') {
/*:: if(!(cs instanceof Range)) throw "unreachable"; */
		return encode_range(cs.s, cs.e);
	}
/*:: if((cs instanceof Range)) throw "unreachable"; */
	if(typeof cs !== 'string') cs = encode_cell((cs/*:any*/));
	if(typeof ce !== 'string') ce = encode_cell((ce/*:any*/));
/*:: if(typeof cs !== 'string') throw "unreachable"; */
/*:: if(typeof ce !== 'string') throw "unreachable"; */
	return cs == ce ? cs : cs + ":" + ce;
}

function safe_decode_range(range/*:string*/)/*:Range*/ {
	var o = {s:{c:0,r:0},e:{c:0,r:0}};
	var idx = 0, i = 0, cc = 0;
	var len = range.length;
	for(idx = 0; i < len; ++i) {
		if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
		idx = 26*idx + cc;
	}
	o.s.c = --idx;

	for(idx = 0; i < len; ++i) {
		if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
		idx = 10*idx + cc;
	}
	o.s.r = --idx;

	if(i === len || cc != 10) { o.e.c=o.s.c; o.e.r=o.s.r; return o; }
	++i;

	for(idx = 0; i != len; ++i) {
		if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
		idx = 26*idx + cc;
	}
	o.e.c = --idx;

	for(idx = 0; i != len; ++i) {
		if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
		idx = 10*idx + cc;
	}
	o.e.r = --idx;
	return o;
}

function safe_format_cell(cell/*:Cell*/, v/*:any*/) {
	var q = (cell.t == 'd' && v instanceof Date);
	if(cell.z != null) try { return (cell.w = SSF_format(cell.z, q ? datenum(v) : v)); } catch(e) { }
	try { return (cell.w = SSF_format((cell.XF||{}).numFmtId||(q ? 14 : 0),  q ? datenum(v) : v)); } catch(e) { return ''+v; }
}

function format_cell(cell/*:Cell*/, v/*:any*/, o/*:any*/) {
	if(cell == null || cell.t == null || cell.t == 'z') return "";
	if(cell.w !== undefined) return cell.w;
	if(cell.t == 'd' && !cell.z && o && o.dateNF) cell.z = o.dateNF;
	if(cell.t == "e") return BErr[cell.v] || cell.v;
	if(v == undefined) return safe_format_cell(cell, cell.v);
	return safe_format_cell(cell, v);
}

function sheet_to_workbook(sheet/*:Worksheet*/, opts)/*:Workbook*/ {
	var n = opts && opts.sheet ? opts.sheet : "Sheet1";
	var sheets = {}; sheets[n] = sheet;
	return { SheetNames: [n], Sheets: sheets };
}

function sheet_add_aoa(_ws/*:?Worksheet*/, data/*:AOA*/, opts/*:?any*/)/*:Worksheet*/ {
	var o = opts || {};
	var dense = _ws ? Array.isArray(_ws) : o.dense;
	if(DENSE != null && dense == null) dense = DENSE;
	var ws/*:Worksheet*/ = _ws || (dense ? ([]/*:any*/) : ({}/*:any*/));
	var _R = 0, _C = 0;
	if(ws && o.origin != null) {
		if(typeof o.origin == 'number') _R = o.origin;
		else {
			var _origin/*:CellAddress*/ = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
			_R = _origin.r; _C = _origin.c;
		}
		if(!ws["!ref"]) ws["!ref"] = "A1:A1";
	}
	var range/*:Range*/ = ({s: {c:10000000, r:10000000}, e: {c:0, r:0}}/*:any*/);
	if(ws['!ref']) {
		var _range = safe_decode_range(ws['!ref']);
		range.s.c = _range.s.c;
		range.s.r = _range.s.r;
		range.e.c = Math.max(range.e.c, _range.e.c);
		range.e.r = Math.max(range.e.r, _range.e.r);
		if(_R == -1) range.e.r = _R = _range.e.r + 1;
	}
	for(var R = 0; R != data.length; ++R) {
		if(!data[R]) continue;
		if(!Array.isArray(data[R])) throw new Error("aoa_to_sheet expects an array of arrays");
		for(var C = 0; C != data[R].length; ++C) {
			if(typeof data[R][C] === 'undefined') continue;
			var cell/*:Cell*/ = ({v: data[R][C] }/*:any*/);
			var __R = _R + R, __C = _C + C;
			if(range.s.r > __R) range.s.r = __R;
			if(range.s.c > __C) range.s.c = __C;
			if(range.e.r < __R) range.e.r = __R;
			if(range.e.c < __C) range.e.c = __C;
			if(data[R][C] && typeof data[R][C] === 'object' && !Array.isArray(data[R][C]) && !(data[R][C] instanceof Date)) cell = data[R][C];
			else {
				if(Array.isArray(cell.v)) { cell.f = data[R][C][1]; cell.v = cell.v[0]; }
				if(cell.v === null) {
					if(cell.f) cell.t = 'n';
					else if(o.nullError) { cell.t = 'e'; cell.v = 0; }
					else if(!o.sheetStubs) continue;
					else cell.t = 'z';
				}
				else if(typeof cell.v === 'number') cell.t = 'n';
				else if(typeof cell.v === 'boolean') cell.t = 'b';
				else if(cell.v instanceof Date) {
					cell.z = o.dateNF || table_fmt[14];
					if(o.cellDates) { cell.t = 'd'; cell.w = SSF_format(cell.z, datenum(cell.v)); }
					else { cell.t = 'n'; cell.v = datenum(cell.v); cell.w = SSF_format(cell.z, cell.v); }
				}
				else cell.t = 's';
			}
			if(dense) {
				if(!ws[__R]) ws[__R] = [];
				if(ws[__R][__C] && ws[__R][__C].z) cell.z = ws[__R][__C].z;
				ws[__R][__C] = cell;
			} else {
				var cell_ref = encode_cell(({c:__C,r:__R}/*:any*/));
				if(ws[cell_ref] && ws[cell_ref].z) cell.z = ws[cell_ref].z;
				ws[cell_ref] = cell;
			}
		}
	}
	if(range.s.c < 10000000) ws['!ref'] = encode_range(range);
	return ws;
}
function aoa_to_sheet(data/*:AOA*/, opts/*:?any*/)/*:Worksheet*/ { return sheet_add_aoa(null, data, opts); }

function parse_Int32LE(data) {
	return data.read_shift(4, 'i');
}
function write_UInt32LE(x/*:number*/, o) {
	if (!o) o = new_buf(4);
	o.write_shift(4, x);
	return o;
}

/* [MS-XLSB] 2.5.168 */
function parse_XLWideString(data/*::, length*/)/*:string*/ {
	var cchCharacters = data.read_shift(4);
	return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, 'dbcs');
}
function write_XLWideString(data/*:string*/, o) {
	var _null = false; if (o == null) { _null = true; o = new_buf(4 + 2 * data.length); }
	o.write_shift(4, data.length);
	if (data.length > 0) o.write_shift(0, data, 'dbcs');
	return _null ? o.slice(0, o.l) : o;
}

/* [MS-XLSB] 2.5.91 */
//function parse_LPWideString(data/*::, length*/)/*:string*/ {
//	var cchCharacters = data.read_shift(2);
//	return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, "utf16le");
//}

/* [MS-XLSB] 2.5.143 */
function parse_StrRun(data) {
	return { ich: data.read_shift(2), ifnt: data.read_shift(2) };
}
function write_StrRun(run, o) {
	if (!o) o = new_buf(4);
	o.write_shift(2, run.ich || 0);
	o.write_shift(2, run.ifnt || 0);
	return o;
}

/* [MS-XLSB] 2.5.121 */
function parse_RichStr(data, length/*:number*/)/*:XLString*/ {
	var start = data.l;
	var flags = data.read_shift(1);
	var str = parse_XLWideString(data);
	var rgsStrRun = [];
	var z = ({ t: str, h: str }/*:any*/);
	if ((flags & 1) !== 0) { /* fRichStr */
		/* TODO: formatted string */
		var dwSizeStrRun = data.read_shift(4);
		for (var i = 0; i != dwSizeStrRun; ++i) rgsStrRun.push(parse_StrRun(data));
		z.r = rgsStrRun;
	}
	else z.r = [{ ich: 0, ifnt: 0 }];
	//if((flags & 2) !== 0) { /* fExtStr */
	//	/* TODO: phonetic string */
	//}
	data.l = start + length;
	return z;
}
function write_RichStr(str/*:XLString*/, o/*:?Block*/)/*:Block*/ {
	/* TODO: formatted string */
	var _null = false; if (o == null) { _null = true; o = new_buf(15 + 4 * str.t.length); }
	o.write_shift(1, 0);
	write_XLWideString(str.t, o);
	return _null ? o.slice(0, o.l) : o;
}
/* [MS-XLSB] 2.4.328 BrtCommentText (RichStr w/1 run) */
var parse_BrtCommentText = parse_RichStr;
function write_BrtCommentText(str/*:XLString*/, o/*:?Block*/)/*:Block*/ {
	/* TODO: formatted string */
	var _null = false; if (o == null) { _null = true; o = new_buf(23 + 4 * str.t.length); }
	o.write_shift(1, 1);
	write_XLWideString(str.t, o);
	o.write_shift(4, 1);
	write_StrRun({ ich: 0, ifnt: 0 }, o);
	return _null ? o.slice(0, o.l) : o;
}

/* [MS-XLSB] 2.5.9 */
function parse_XLSBCell(data)/*:any*/ {
	var col = data.read_shift(4);
	var iStyleRef = data.read_shift(2);
	iStyleRef += data.read_shift(1) << 16;
	data.l++; //var fPhShow = data.read_shift(1);
	return { c: col, iStyleRef: iStyleRef };
}
function write_XLSBCell(cell/*:any*/, o/*:?Block*/) {
	if (o == null) o = new_buf(8);
	o.write_shift(-4, cell.c);
	o.write_shift(3, cell.iStyleRef || cell.s);
	o.write_shift(1, 0); /* fPhShow */
	return o;
}

/* Short XLSB Cell does not include column */
function parse_XLSBShortCell(data)/*:any*/ {
	var iStyleRef = data.read_shift(2);
	iStyleRef += data.read_shift(1) <<16;
	data.l++; //var fPhShow = data.read_shift(1);
	return { c:-1, iStyleRef: iStyleRef };
}
function write_XLSBShortCell(cell/*:any*/, o/*:?Block*/) {
	if(o == null) o = new_buf(4);
	o.write_shift(3, cell.iStyleRef || cell.s);
	o.write_shift(1, 0); /* fPhShow */
	return o;
}

/* [MS-XLSB] 2.5.21 */
var parse_XLSBCodeName = parse_XLWideString;
var write_XLSBCodeName = write_XLWideString;

/* [MS-XLSB] 2.5.166 */
function parse_XLNullableWideString(data/*::, length*/)/*:string*/ {
	var cchCharacters = data.read_shift(4);
	return cchCharacters === 0 || cchCharacters === 0xFFFFFFFF ? "" : data.read_shift(cchCharacters, 'dbcs');
}
function write_XLNullableWideString(data/*:string*/, o) {
	var _null = false; if (o == null) { _null = true; o = new_buf(127); }
	o.write_shift(4, data.length > 0 ? data.length : 0xFFFFFFFF);
	if (data.length > 0) o.write_shift(0, data, 'dbcs');
	return _null ? o.slice(0, o.l) : o;
}

/* [MS-XLSB] 2.5.165 */
var parse_XLNameWideString = parse_XLWideString;
//var write_XLNameWideString = write_XLWideString;

/* [MS-XLSB] 2.5.114 */
var parse_RelID = parse_XLNullableWideString;
var write_RelID = write_XLNullableWideString;


/* [MS-XLS] 2.5.217 ; [MS-XLSB] 2.5.122 */
function parse_RkNumber(data)/*:number*/ {
	var b = data.slice(data.l, data.l + 4);
	var fX100 = (b[0] & 1), fInt = (b[0] & 2);
	data.l += 4;
	var RK = fInt === 0 ? __double([0, 0, 0, 0, (b[0] & 0xFC), b[1], b[2], b[3]], 0) : __readInt32LE(b, 0) >> 2;
	return fX100 ? (RK / 100) : RK;
}
function write_RkNumber(data/*:number*/, o) {
	if (o == null) o = new_buf(4);
	var fX100 = 0, fInt = 0, d100 = data * 100;
	if ((data == (data | 0)) && (data >= -(1 << 29)) && (data < (1 << 29))) { fInt = 1; }
	else if ((d100 == (d100 | 0)) && (d100 >= -(1 << 29)) && (d100 < (1 << 29))) { fInt = 1; fX100 = 1; }
	if (fInt) o.write_shift(-4, ((fX100 ? d100 : data) << 2) + (fX100 + 2));
	else throw new Error("unsupported RkNumber " + data); // TODO
}


/* [MS-XLSB] 2.5.117 RfX */
function parse_RfX(data /*::, length*/)/*:Range*/ {
	var cell/*:Range*/ = ({ s: {}, e: {} }/*:any*/);
	cell.s.r = data.read_shift(4);
	cell.e.r = data.read_shift(4);
	cell.s.c = data.read_shift(4);
	cell.e.c = data.read_shift(4);
	return cell;
}
function write_RfX(r/*:Range*/, o) {
	if (!o) o = new_buf(16);
	o.write_shift(4, r.s.r);
	o.write_shift(4, r.e.r);
	o.write_shift(4, r.s.c);
	o.write_shift(4, r.e.c);
	return o;
}

/* [MS-XLSB] 2.5.153 UncheckedRfX */
var parse_UncheckedRfX = parse_RfX;
var write_UncheckedRfX = write_RfX;

/* [MS-XLSB] 2.5.155 UncheckedSqRfX */
//function parse_UncheckedSqRfX(data) {
//	var cnt = data.read_shift(4);
//	var out = [];
//	for(var i = 0; i < cnt; ++i) {
//		var rng = parse_UncheckedRfX(data);
//		out.push(encode_range(rng));
//	}
//	return out.join(",");
//}
//function write_UncheckedSqRfX(sqrfx/*:string*/) {
//	var parts = sqrfx.split(/\s*,\s*/);
//	var o = new_buf(4); o.write_shift(4, parts.length);
//	var out = [o];
//	parts.forEach(function(rng) {
//		out.push(write_UncheckedRfX(safe_decode_range(rng)));
//	});
//	return bconcat(out);
//}

/* [MS-XLS] 2.5.342 ; [MS-XLSB] 2.5.171 */
/* TODO: error checking, NaN and Infinity values are not valid Xnum */
function parse_Xnum(data/*::, length*/) {
	if(data.length - data.l < 8) throw "XLS Xnum Buffer underflow";
	return data.read_shift(8, 'f');
}
function write_Xnum(data, o) { return (o || new_buf(8)).write_shift(8, data, 'f'); }

/* [MS-XLSB] 2.4.324 BrtColor */
function parse_BrtColor(data/*::, length*/) {
	var out = {};
	var d = data.read_shift(1);

	//var fValidRGB = d & 1;
	var xColorType = d >>> 1;

	var index = data.read_shift(1);
	var nTS = data.read_shift(2, 'i');
	var bR = data.read_shift(1);
	var bG = data.read_shift(1);
	var bB = data.read_shift(1);
	data.l++; //var bAlpha = data.read_shift(1);

	switch (xColorType) {
		case 0: out.auto = 1; break;
		case 1:
			out.index = index;
			var icv = XLSIcv[index];
			/* automatic pseudo index 81 */
			if (icv) out.rgb = rgb2Hex(icv);
			break;
		case 2:
			/* if(!fValidRGB) throw new Error("invalid"); */
			out.rgb = rgb2Hex([bR, bG, bB]);
			break;
		case 3: out.theme = index; break;
	}
	if (nTS != 0) out.tint = nTS > 0 ? nTS / 32767 : nTS / 32768;

	return out;
}
function write_BrtColor(color, o) {
	if (!o) o = new_buf(8);
	if (!color || color.auto) { o.write_shift(4, 0); o.write_shift(4, 0); return o; }
	if (color.index != null) {
		o.write_shift(1, 0x02);
		o.write_shift(1, color.index);
	} else if (color.theme != null) {
		o.write_shift(1, 0x06);
		o.write_shift(1, color.theme);
	} else {
		o.write_shift(1, 0x05);
		o.write_shift(1, 0);
	}
	var nTS = color.tint || 0;
	if (nTS > 0) nTS *= 32767;
	else if (nTS < 0) nTS *= 32768;
	o.write_shift(2, nTS);
	if (!color.rgb || color.theme != null) {
		o.write_shift(2, 0);
		o.write_shift(1, 0);
		o.write_shift(1, 0);
	} else {
		var rgb = (color.rgb || 'FFFFFF');
		if (typeof rgb == 'number') rgb = ("000000" + rgb.toString(16)).slice(-6);
		o.write_shift(1, parseInt(rgb.slice(0, 2), 16));
		o.write_shift(1, parseInt(rgb.slice(2, 4), 16));
		o.write_shift(1, parseInt(rgb.slice(4, 6), 16));
		o.write_shift(1, 0xFF);
	}
	return o;
}

/* [MS-XLSB] 2.5.52 */
function parse_FontFlags(data/*::, length, opts*/) {
	var d = data.read_shift(1);
	data.l++;
	var out = {
		fBold: d & 0x01,
		fItalic: d & 0x02,
		fUnderline: d & 0x04,
		fStrikeout: d & 0x08,
		fOutline: d & 0x10,
		fShadow: d & 0x20,
		fCondense: d & 0x40,
		fExtend: d & 0x80
	};
	return out;
}
function write_FontFlags(font, o) {
	if (!o) o = new_buf(2);
	var grbit =
		(font.italic ? 0x02 : 0) |
		(font.strike ? 0x08 : 0) |
		(font.outline ? 0x10 : 0) |
		(font.shadow ? 0x20 : 0) |
		(font.condense ? 0x40 : 0) |
		(font.extend ? 0x80 : 0);
	o.write_shift(1, grbit);
	o.write_shift(1, 0);
	return o;
}

/* [MS-OLEDS] 2.3.1 and 2.3.2 */
function parse_ClipboardFormatOrString(o, w/*:number*/)/*:string*/ {
	// $FlowIgnore
	var ClipFmt = { 2: "BITMAP", 3: "METAFILEPICT", 8: "DIB", 14: "ENHMETAFILE" };
	var m/*:number*/ = o.read_shift(4);
	switch (m) {
		case 0x00000000: return "";
		case 0xffffffff: case 0xfffffffe: return ClipFmt[o.read_shift(4)] || "";
	}
	if (m > 0x190) throw new Error("Unsupported Clipboard: " + m.toString(16));
	o.l -= 4;
	return o.read_shift(0, w == 1 ? "lpstr" : "lpwstr");
}
function parse_ClipboardFormatOrAnsiString(o) { return parse_ClipboardFormatOrString(o, 1); }
function parse_ClipboardFormatOrUnicodeString(o) { return parse_ClipboardFormatOrString(o, 2); }

/* [MS-OLEPS] 2.2 PropertyType */
// Note: some tree shakers cannot handle VT_VECTOR | $CONST, hence extra vars
//var VT_EMPTY    = 0x0000;
//var VT_NULL     = 0x0001;
var VT_I2       = 0x0002;
var VT_I4       = 0x0003;
//var VT_R4       = 0x0004;
//var VT_R8       = 0x0005;
//var VT_CY       = 0x0006;
//var VT_DATE     = 0x0007;
//var VT_BSTR     = 0x0008;
//var VT_ERROR    = 0x000A;
var VT_BOOL     = 0x000B;
var VT_VARIANT  = 0x000C;
//var VT_DECIMAL  = 0x000E;
//var VT_I1       = 0x0010;
//var VT_UI1      = 0x0011;
//var VT_UI2      = 0x0012;
var VT_UI4      = 0x0013;
//var VT_I8       = 0x0014;
//var VT_UI8      = 0x0015;
//var VT_INT      = 0x0016;
//var VT_UINT     = 0x0017;
var VT_LPSTR    = 0x001E;
//var VT_LPWSTR   = 0x001F;
var VT_FILETIME = 0x0040;
var VT_BLOB     = 0x0041;
//var VT_STREAM   = 0x0042;
//var VT_STORAGE  = 0x0043;
//var VT_STREAMED_Object  = 0x0044;
//var VT_STORED_Object    = 0x0045;
//var VT_BLOB_Object      = 0x0046;
var VT_CF       = 0x0047;
//var VT_CLSID    = 0x0048;
//var VT_VERSIONED_STREAM = 0x0049;
var VT_VECTOR   = 0x1000;
var VT_VECTOR_VARIANT = 0x100C;
var VT_VECTOR_LPSTR   = 0x101E;
//var VT_ARRAY    = 0x2000;

var VT_STRING   = 0x0050; // 2.3.3.1.11 VtString
var VT_USTR     = 0x0051; // 2.3.3.1.12 VtUnalignedString
var VT_CUSTOM   = [VT_STRING, VT_USTR];

/* [MS-OSHARED] 2.3.3.2.2.1 Document Summary Information PIDDSI */
var DocSummaryPIDDSI = {
	/*::[*/0x01/*::]*/: { n: 'CodePage', t: VT_I2 },
	/*::[*/0x02/*::]*/: { n: 'Category', t: VT_STRING },
	/*::[*/0x03/*::]*/: { n: 'PresentationFormat', t: VT_STRING },
	/*::[*/0x04/*::]*/: { n: 'ByteCount', t: VT_I4 },
	/*::[*/0x05/*::]*/: { n: 'LineCount', t: VT_I4 },
	/*::[*/0x06/*::]*/: { n: 'ParagraphCount', t: VT_I4 },
	/*::[*/0x07/*::]*/: { n: 'SlideCount', t: VT_I4 },
	/*::[*/0x08/*::]*/: { n: 'NoteCount', t: VT_I4 },
	/*::[*/0x09/*::]*/: { n: 'HiddenCount', t: VT_I4 },
	/*::[*/0x0a/*::]*/: { n: 'MultimediaClipCount', t: VT_I4 },
	/*::[*/0x0b/*::]*/: { n: 'ScaleCrop', t: VT_BOOL },
	/*::[*/0x0c/*::]*/: { n: 'HeadingPairs', t: VT_VECTOR_VARIANT /* VT_VECTOR | VT_VARIANT */ },
	/*::[*/0x0d/*::]*/: { n: 'TitlesOfParts', t: VT_VECTOR_LPSTR /* VT_VECTOR | VT_LPSTR */ },
	/*::[*/0x0e/*::]*/: { n: 'Manager', t: VT_STRING },
	/*::[*/0x0f/*::]*/: { n: 'Company', t: VT_STRING },
	/*::[*/0x10/*::]*/: { n: 'LinksUpToDate', t: VT_BOOL },
	/*::[*/0x11/*::]*/: { n: 'CharacterCount', t: VT_I4 },
	/*::[*/0x13/*::]*/: { n: 'SharedDoc', t: VT_BOOL },
	/*::[*/0x16/*::]*/: { n: 'HyperlinksChanged', t: VT_BOOL },
	/*::[*/0x17/*::]*/: { n: 'AppVersion', t: VT_I4, p: 'version' },
	/*::[*/0x18/*::]*/: { n: 'DigSig', t: VT_BLOB },
	/*::[*/0x1A/*::]*/: { n: 'ContentType', t: VT_STRING },
	/*::[*/0x1B/*::]*/: { n: 'ContentStatus', t: VT_STRING },
	/*::[*/0x1C/*::]*/: { n: 'Language', t: VT_STRING },
	/*::[*/0x1D/*::]*/: { n: 'Version', t: VT_STRING },
	/*::[*/0xFF/*::]*/: {},
	/* [MS-OLEPS] 2.18 */
	/*::[*/0x80000000/*::]*/: { n: 'Locale', t: VT_UI4 },
	/*::[*/0x80000003/*::]*/: { n: 'Behavior', t: VT_UI4 },
	/*::[*/0x72627262/*::]*/: {}
};

/* [MS-OSHARED] 2.3.3.2.1.1 Summary Information Property Set PIDSI */
var SummaryPIDSI = {
	/*::[*/0x01/*::]*/: { n: 'CodePage', t: VT_I2 },
	/*::[*/0x02/*::]*/: { n: 'Title', t: VT_STRING },
	/*::[*/0x03/*::]*/: { n: 'Subject', t: VT_STRING },
	/*::[*/0x04/*::]*/: { n: 'Author', t: VT_STRING },
	/*::[*/0x05/*::]*/: { n: 'Keywords', t: VT_STRING },
	/*::[*/0x06/*::]*/: { n: 'Comments', t: VT_STRING },
	/*::[*/0x07/*::]*/: { n: 'Template', t: VT_STRING },
	/*::[*/0x08/*::]*/: { n: 'LastAuthor', t: VT_STRING },
	/*::[*/0x09/*::]*/: { n: 'RevNumber', t: VT_STRING },
	/*::[*/0x0A/*::]*/: { n: 'EditTime', t: VT_FILETIME },
	/*::[*/0x0B/*::]*/: { n: 'LastPrinted', t: VT_FILETIME },
	/*::[*/0x0C/*::]*/: { n: 'CreatedDate', t: VT_FILETIME },
	/*::[*/0x0D/*::]*/: { n: 'ModifiedDate', t: VT_FILETIME },
	/*::[*/0x0E/*::]*/: { n: 'PageCount', t: VT_I4 },
	/*::[*/0x0F/*::]*/: { n: 'WordCount', t: VT_I4 },
	/*::[*/0x10/*::]*/: { n: 'CharCount', t: VT_I4 },
	/*::[*/0x11/*::]*/: { n: 'Thumbnail', t: VT_CF },
	/*::[*/0x12/*::]*/: { n: 'Application', t: VT_STRING },
	/*::[*/0x13/*::]*/: { n: 'DocSecurity', t: VT_I4 },
	/*::[*/0xFF/*::]*/: {},
	/* [MS-OLEPS] 2.18 */
	/*::[*/0x80000000/*::]*/: { n: 'Locale', t: VT_UI4 },
	/*::[*/0x80000003/*::]*/: { n: 'Behavior', t: VT_UI4 },
	/*::[*/0x72627262/*::]*/: {}
};

/* [MS-XLS] 2.4.63 Country/Region codes */
var CountryEnum = {
	/*::[*/0x0001/*::]*/: "US", // United States
	/*::[*/0x0002/*::]*/: "CA", // Canada
	/*::[*/0x0003/*::]*/: "", // Latin America (except Brazil)
	/*::[*/0x0007/*::]*/: "RU", // Russia
	/*::[*/0x0014/*::]*/: "EG", // Egypt
	/*::[*/0x001E/*::]*/: "GR", // Greece
	/*::[*/0x001F/*::]*/: "NL", // Netherlands
	/*::[*/0x0020/*::]*/: "BE", // Belgium
	/*::[*/0x0021/*::]*/: "FR", // France
	/*::[*/0x0022/*::]*/: "ES", // Spain
	/*::[*/0x0024/*::]*/: "HU", // Hungary
	/*::[*/0x0027/*::]*/: "IT", // Italy
	/*::[*/0x0029/*::]*/: "CH", // Switzerland
	/*::[*/0x002B/*::]*/: "AT", // Austria
	/*::[*/0x002C/*::]*/: "GB", // United Kingdom
	/*::[*/0x002D/*::]*/: "DK", // Denmark
	/*::[*/0x002E/*::]*/: "SE", // Sweden
	/*::[*/0x002F/*::]*/: "NO", // Norway
	/*::[*/0x0030/*::]*/: "PL", // Poland
	/*::[*/0x0031/*::]*/: "DE", // Germany
	/*::[*/0x0034/*::]*/: "MX", // Mexico
	/*::[*/0x0037/*::]*/: "BR", // Brazil
	/*::[*/0x003d/*::]*/: "AU", // Australia
	/*::[*/0x0040/*::]*/: "NZ", // New Zealand
	/*::[*/0x0042/*::]*/: "TH", // Thailand
	/*::[*/0x0051/*::]*/: "JP", // Japan
	/*::[*/0x0052/*::]*/: "KR", // Korea
	/*::[*/0x0054/*::]*/: "VN", // Viet Nam
	/*::[*/0x0056/*::]*/: "CN", // China
	/*::[*/0x005A/*::]*/: "TR", // Turkey
	/*::[*/0x0069/*::]*/: "JS", // Ramastan
	/*::[*/0x00D5/*::]*/: "DZ", // Algeria
	/*::[*/0x00D8/*::]*/: "MA", // Morocco
	/*::[*/0x00DA/*::]*/: "LY", // Libya
	/*::[*/0x015F/*::]*/: "PT", // Portugal
	/*::[*/0x0162/*::]*/: "IS", // Iceland
	/*::[*/0x0166/*::]*/: "FI", // Finland
	/*::[*/0x01A4/*::]*/: "CZ", // Czech Republic
	/*::[*/0x0376/*::]*/: "TW", // Taiwan
	/*::[*/0x03C1/*::]*/: "LB", // Lebanon
	/*::[*/0x03C2/*::]*/: "JO", // Jordan
	/*::[*/0x03C3/*::]*/: "SY", // Syria
	/*::[*/0x03C4/*::]*/: "IQ", // Iraq
	/*::[*/0x03C5/*::]*/: "KW", // Kuwait
	/*::[*/0x03C6/*::]*/: "SA", // Saudi Arabia
	/*::[*/0x03CB/*::]*/: "AE", // United Arab Emirates
	/*::[*/0x03CC/*::]*/: "IL", // Israel
	/*::[*/0x03CE/*::]*/: "QA", // Qatar
	/*::[*/0x03D5/*::]*/: "IR", // Iran
	/*::[*/0xFFFF/*::]*/: "US"  // United States
};

/* [MS-XLS] 2.5.127 */
var XLSFillPattern = [
	null,
	'solid',
	'mediumGray',
	'darkGray',
	'lightGray',
	'darkHorizontal',
	'darkVertical',
	'darkDown',
	'darkUp',
	'darkGrid',
	'darkTrellis',
	'lightHorizontal',
	'lightVertical',
	'lightDown',
	'lightUp',
	'lightGrid',
	'lightTrellis',
	'gray125',
	'gray0625'
];

function rgbify(arr/*:Array<number>*/)/*:Array<[number, number, number]>*/ { return arr.map(function(x) { return [(x>>16)&255,(x>>8)&255,x&255]; }); }

/* [MS-XLS] 2.5.161 */
/* [MS-XLSB] 2.5.75 Icv */
var _XLSIcv = /*#__PURE__*/ rgbify([
	/* Color Constants */
	0x000000,
	0xFFFFFF,
	0xFF0000,
	0x00FF00,
	0x0000FF,
	0xFFFF00,
	0xFF00FF,
	0x00FFFF,

	/* Overridable Defaults */
	0x000000,
	0xFFFFFF,
	0xFF0000,
	0x00FF00,
	0x0000FF,
	0xFFFF00,
	0xFF00FF,
	0x00FFFF,

	0x800000,
	0x008000,
	0x000080,
	0x808000,
	0x800080,
	0x008080,
	0xC0C0C0,
	0x808080,
	0x9999FF,
	0x993366,
	0xFFFFCC,
	0xCCFFFF,
	0x660066,
	0xFF8080,
	0x0066CC,
	0xCCCCFF,

	0x000080,
	0xFF00FF,
	0xFFFF00,
	0x00FFFF,
	0x800080,
	0x800000,
	0x008080,
	0x0000FF,
	0x00CCFF,
	0xCCFFFF,
	0xCCFFCC,
	0xFFFF99,
	0x99CCFF,
	0xFF99CC,
	0xCC99FF,
	0xFFCC99,

	0x3366FF,
	0x33CCCC,
	0x99CC00,
	0xFFCC00,
	0xFF9900,
	0xFF6600,
	0x666699,
	0x969696,
	0x003366,
	0x339966,
	0x003300,
	0x333300,
	0x993300,
	0x993366,
	0x333399,
	0x333333,

	/* Other entries to appease BIFF8/12 */
	0xFFFFFF, /* 0x40 icvForeground ?? */
	0x000000, /* 0x41 icvBackground ?? */
	0x000000, /* 0x42 icvFrame ?? */
	0x000000, /* 0x43 icv3D ?? */
	0x000000, /* 0x44 icv3DText ?? */
	0x000000, /* 0x45 icv3DHilite ?? */
	0x000000, /* 0x46 icv3DShadow ?? */
	0x000000, /* 0x47 icvHilite ?? */
	0x000000, /* 0x48 icvCtlText ?? */
	0x000000, /* 0x49 icvCtlScrl ?? */
	0x000000, /* 0x4A icvCtlInv ?? */
	0x000000, /* 0x4B icvCtlBody ?? */
	0x000000, /* 0x4C icvCtlFrame ?? */
	0x000000, /* 0x4D icvCtlFore ?? */
	0x000000, /* 0x4E icvCtlBack ?? */
	0x000000, /* 0x4F icvCtlNeutral */
	0x000000, /* 0x50 icvInfoBk ?? */
	0x000000 /* 0x51 icvInfoText ?? */
]);
var XLSIcv = /*#__PURE__*/dup(_XLSIcv);

/* [MS-XLSB] 2.5.97.2 */
var BErr = {
	/*::[*/0x00/*::]*/: "#NULL!",
	/*::[*/0x07/*::]*/: "#DIV/0!",
	/*::[*/0x0F/*::]*/: "#VALUE!",
	/*::[*/0x17/*::]*/: "#REF!",
	/*::[*/0x1D/*::]*/: "#NAME?",
	/*::[*/0x24/*::]*/: "#NUM!",
	/*::[*/0x2A/*::]*/: "#N/A",
	/*::[*/0x2B/*::]*/: "#GETTING_DATA",
	/*::[*/0xFF/*::]*/: "#WTF?"
};
//var RBErr = evert_num(BErr);
var RBErr = {
	"#NULL!":        0x00,
	"#DIV/0!":       0x07,
	"#VALUE!":       0x0F,
	"#REF!":         0x17,
	"#NAME?":        0x1D,
	"#NUM!":         0x24,
	"#N/A":          0x2A,
	"#GETTING_DATA": 0x2B,
	"#WTF?":         0xFF
};

/* Parts enumerated in OPC spec, MS-XLSB and MS-XLSX */
/* 12.3 Part Summary <SpreadsheetML> */
/* 14.2 Part Summary <DrawingML> */
/* [MS-XLSX] 2.1 Part Enumerations ; [MS-XLSB] 2.1.7 Part Enumeration */
var ct2type/*{[string]:string}*/ = ({
	/* Workbook */
	"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks",
	"application/vnd.ms-excel.sheet.macroEnabled.main+xml": "workbooks",
	"application/vnd.ms-excel.sheet.binary.macroEnabled.main": "workbooks",
	"application/vnd.ms-excel.addin.macroEnabled.main+xml": "workbooks",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": "workbooks",

	/* Worksheet */
	"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": "sheets",
	"application/vnd.ms-excel.worksheet": "sheets",
	"application/vnd.ms-excel.binIndexWs": "TODO", /* Binary Index */

	/* Chartsheet */
	"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": "charts",
	"application/vnd.ms-excel.chartsheet": "charts",

	/* Macrosheet */
	"application/vnd.ms-excel.macrosheet+xml": "macros",
	"application/vnd.ms-excel.macrosheet": "macros",
	"application/vnd.ms-excel.intlmacrosheet": "TODO",
	"application/vnd.ms-excel.binIndexMs": "TODO", /* Binary Index */

	/* Dialogsheet */
	"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": "dialogs",
	"application/vnd.ms-excel.dialogsheet": "dialogs",

	/* Shared Strings */
	"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml": "strs",
	"application/vnd.ms-excel.sharedStrings": "strs",

	/* Styles */
	"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": "styles",
	"application/vnd.ms-excel.styles": "styles",

	/* File Properties */
	"application/vnd.openxmlformats-package.core-properties+xml": "coreprops",
	"application/vnd.openxmlformats-officedocument.custom-properties+xml": "custprops",
	"application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops",

	/* Custom Data Properties */
	"application/vnd.openxmlformats-officedocument.customXmlProperties+xml": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty": "TODO",

	/* Comments */
	"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": "comments",
	"application/vnd.ms-excel.comments": "comments",
	"application/vnd.ms-excel.threadedcomments+xml": "threadedcomments",
	"application/vnd.ms-excel.person+xml": "people",

	/* Metadata (Stock/Geography and Dynamic Array) */
	"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml": "metadata",
	"application/vnd.ms-excel.sheetMetadata": "metadata",

	/* PivotTable */
	"application/vnd.ms-excel.pivotTable": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml": "TODO",

	/* Chart Objects */
	"application/vnd.openxmlformats-officedocument.drawingml.chart+xml": "TODO",

	/* Chart Colors */
	"application/vnd.ms-office.chartcolorstyle+xml": "TODO",

	/* Chart Style */
	"application/vnd.ms-office.chartstyle+xml": "TODO",

	/* Chart Advanced */
	"application/vnd.ms-office.chartex+xml": "TODO",

	/* Calculation Chain */
	"application/vnd.ms-excel.calcChain": "calcchains",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains",

	/* Printer Settings */
	"application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings": "TODO",

	/* ActiveX */
	"application/vnd.ms-office.activeX": "TODO",
	"application/vnd.ms-office.activeX+xml": "TODO",

	/* Custom Toolbars */
	"application/vnd.ms-excel.attachedToolbars": "TODO",

	/* External Data Connections */
	"application/vnd.ms-excel.connections": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": "TODO",

	/* External Links */
	"application/vnd.ms-excel.externalLink": "links",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml": "links",

	/* PivotCache */
	"application/vnd.ms-excel.pivotCacheDefinition": "TODO",
	"application/vnd.ms-excel.pivotCacheRecords": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml": "TODO",

	/* Query Table */
	"application/vnd.ms-excel.queryTable": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml": "TODO",

	/* Shared Workbook */
	"application/vnd.ms-excel.userNames": "TODO",
	"application/vnd.ms-excel.revisionHeaders": "TODO",
	"application/vnd.ms-excel.revisionLog": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml": "TODO",

	/* Single Cell Table */
	"application/vnd.ms-excel.tableSingleCells": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml": "TODO",

	/* Slicer */
	"application/vnd.ms-excel.slicer": "TODO",
	"application/vnd.ms-excel.slicerCache": "TODO",
	"application/vnd.ms-excel.slicer+xml": "TODO",
	"application/vnd.ms-excel.slicerCache+xml": "TODO",

	/* Sort Map */
	"application/vnd.ms-excel.wsSortMap": "TODO",

	/* Table */
	"application/vnd.ms-excel.table": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": "TODO",

	/* Themes */
	"application/vnd.openxmlformats-officedocument.theme+xml": "themes",

	/* Theme Override */
	"application/vnd.openxmlformats-officedocument.themeOverride+xml": "TODO",

	/* Timeline */
	"application/vnd.ms-excel.Timeline+xml": "TODO", /* verify */
	"application/vnd.ms-excel.TimelineCache+xml": "TODO", /* verify */

	/* VBA */
	"application/vnd.ms-office.vbaProject": "vba",
	"application/vnd.ms-office.vbaProjectSignature": "TODO",

	/* Volatile Dependencies */
	"application/vnd.ms-office.volatileDependencies": "TODO",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml": "TODO",

	/* Control Properties */
	"application/vnd.ms-excel.controlproperties+xml": "TODO",

	/* Data Model */
	"application/vnd.openxmlformats-officedocument.model+data": "TODO",

	/* Survey */
	"application/vnd.ms-excel.Survey+xml": "TODO",

	/* Drawing */
	"application/vnd.openxmlformats-officedocument.drawing+xml": "drawings",
	"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": "TODO",
	"application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml": "TODO",
	"application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml": "TODO",
	"application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml": "TODO",
	"application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml": "TODO",

	/* VML */
	"application/vnd.openxmlformats-officedocument.vmlDrawing": "TODO",

	"application/vnd.openxmlformats-package.relationships+xml": "rels",
	"application/vnd.openxmlformats-officedocument.oleObject": "TODO",

	/* Image */
	"image/png": "TODO",

	"sheet": "js"
}/*:any*/);

var CT_LIST = {
		workbooks: {
			xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
			xlsm: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
			xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
			xlam: "application/vnd.ms-excel.addin.macroEnabled.main+xml",
			xltx: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml"
		},
		strs: { /* Shared Strings */
			xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
			xlsb: "application/vnd.ms-excel.sharedStrings"
		},
		comments: { /* Comments */
			xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
			xlsb: "application/vnd.ms-excel.comments"
		},
		sheets: { /* Worksheet */
			xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
			xlsb: "application/vnd.ms-excel.worksheet"
		},
		charts: { /* Chartsheet */
			xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml",
			xlsb: "application/vnd.ms-excel.chartsheet"
		},
		dialogs: { /* Dialogsheet */
			xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml",
			xlsb: "application/vnd.ms-excel.dialogsheet"
		},
		macros: { /* Macrosheet (Excel 4.0 Macros) */
			xlsx: "application/vnd.ms-excel.macrosheet+xml",
			xlsb: "application/vnd.ms-excel.macrosheet"
		},
		metadata: { /* Metadata (Stock/Geography and Dynamic Array) */
			xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml",
			xlsb: "application/vnd.ms-excel.sheetMetadata"
		},
		styles: { /* Styles */
			xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
			xlsb: "application/vnd.ms-excel.styles"
		}
};

function new_ct()/*:any*/ {
	return ({
		workbooks:[], sheets:[], charts:[], dialogs:[], macros:[],
		rels:[], strs:[], comments:[], threadedcomments:[], links:[],
		coreprops:[], extprops:[], custprops:[], themes:[], styles:[],
		calcchains:[], vba: [], drawings: [], metadata: [], people:[],
		TODO:[], xmlns: "" }/*:any*/);
}

function parse_ct(data/*:?string*/) {
	var ct = new_ct();
	if(!data || !data.match) return ct;
	var ctext = {};
	(data.match(tagregex)||[]).forEach(function(x) {
		var y = parsexmltag(x);
		switch(y[0].replace(nsregex,"<")) {
			case '<?xml': break;
			case '<Types': ct.xmlns = y['xmlns' + (y[0].match(/<(\w+):/)||["",""])[1] ]; break;
			case '<Default': ctext[y.Extension] = y.ContentType; break;
			case '<Override':
				if(ct[ct2type[y.ContentType]] !== undefined) ct[ct2type[y.ContentType]].push(y.PartName);
				break;
		}
	});
	if(ct.xmlns !== XMLNS.CT) throw new Error("Unknown Namespace: " + ct.xmlns);
	ct.calcchain = ct.calcchains.length > 0 ? ct.calcchains[0] : "";
	ct.sst = ct.strs.length > 0 ? ct.strs[0] : "";
	ct.style = ct.styles.length > 0 ? ct.styles[0] : "";
	ct.defaults = ctext;
	delete ct.calcchains;
	return ct;
}

function write_ct(ct, opts)/*:string*/ {
	var type2ct/*{[string]:Array<string>}*/ = evert_arr(ct2type);

	var o/*:Array<string>*/ = [], v;
	o[o.length] = (XML_HEADER);
	o[o.length] = writextag('Types', null, {
		'xmlns': XMLNS.CT,
		'xmlns:xsd': XMLNS.xsd,
		'xmlns:xsi': XMLNS.xsi
	});

	o = o.concat([
		['xml', 'application/xml'],
		['bin', 'application/vnd.ms-excel.sheet.binary.macroEnabled.main'],
		['vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'],
		['data', 'application/vnd.openxmlformats-officedocument.model+data'],
		/* from test files */
		['bmp', 'image/bmp'],
		['png', 'image/png'],
		['gif', 'image/gif'],
		['emf', 'image/x-emf'],
		['wmf', 'image/x-wmf'],
		['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg'],
		['tif', 'image/tiff'], ['tiff', 'image/tiff'],
		['pdf', 'application/pdf'],
		['rels', 'application/vnd.openxmlformats-package.relationships+xml']
	].map(function(x) {
		return writextag('Default', null, {'Extension':x[0], 'ContentType': x[1]});
	}));

	/* only write first instance */
	var f1 = function(w) {
		if(ct[w] && ct[w].length > 0) {
			v = ct[w][0];
			o[o.length] = (writextag('Override', null, {
				'PartName': (v[0] == '/' ? "":"/") + v,
				'ContentType': CT_LIST[w][opts.bookType] || CT_LIST[w]['xlsx']
			}));
		}
	};

	/* book type-specific */
	var f2 = function(w) {
		(ct[w]||[]).forEach(function(v) {
			o[o.length] = (writextag('Override', null, {
				'PartName': (v[0] == '/' ? "":"/") + v,
				'ContentType': CT_LIST[w][opts.bookType] || CT_LIST[w]['xlsx']
			}));
		});
	};

	/* standard type */
	var f3 = function(t) {
		(ct[t]||[]).forEach(function(v) {
			o[o.length] = (writextag('Override', null, {
				'PartName': (v[0] == '/' ? "":"/") + v,
				'ContentType': type2ct[t][0]
			}));
		});
	};

	f1('workbooks');
	f2('sheets');
	f2('charts');
	f3('themes');
	['strs', 'styles'].forEach(f1);
	['coreprops', 'extprops', 'custprops'].forEach(f3);
	f3('vba');
	f3('comments');
	f3('threadedcomments');
	f3('drawings');
	f2('metadata');
	f3('people');
	if(o.length>2){ o[o.length] = ('</Types>'); o[1]=o[1].replace("/>",">"); }
	return o.join("");
}
/* 9.3 Relationships */
var RELS = ({
	WB: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
	SHEET: "http://sheetjs.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
	HLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
	VML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing",
	XPATH: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath",
	XMISS: "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing",
	XLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink",
	CXML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",
	CXMLP: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps",
	CMNT: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
	CORE_PROPS: "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties",
	EXT_PROPS: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
	CUST_PROPS: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties',
	SST: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",
	STY: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
	THEME: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
	CHART: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",
	CHARTEX: "http://schemas.microsoft.com/office/2014/relationships/chartEx",
	CS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet",
	WS: [
		"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
		"http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet"
	],
	DS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/dialogsheet",
	MS: "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet",
	IMG: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
	DRAW: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",
	XLMETA: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",
	TCMNT: "http://schemas.microsoft.com/office/2017/10/relationships/threadedComment",
	PEOPLE: "http://schemas.microsoft.com/office/2017/10/relationships/person",
	VBA: "http://schemas.microsoft.com/office/2006/relationships/vbaProject"
}/*:any*/);


/* 9.3.3 Representing Relationships */
function get_rels_path(file/*:string*/)/*:string*/ {
	var n = file.lastIndexOf("/");
	return file.slice(0,n+1) + '_rels/' + file.slice(n+1) + ".rels";
}

function parse_rels(data/*:?string*/, currentFilePath/*:string*/) {
	var rels = {"!id":{}};
	if (!data) return rels;
	if (currentFilePath.charAt(0) !== '/') {
		currentFilePath = '/'+currentFilePath;
	}
	var hash = {};

	(data.match(tagregex)||[]).forEach(function(x) {
		var y = parsexmltag(x);
		/* 9.3.2.2 OPC_Relationships */
		if (y[0] === '<Relationship') {
			var rel = {}; rel.Type = y.Type; rel.Target = y.Target; rel.Id = y.Id; if(y.TargetMode) rel.TargetMode = y.TargetMode;
			var canonictarget = y.TargetMode === 'External' ? y.Target : resolve_path(y.Target, currentFilePath);
			rels[canonictarget] = rel;
			hash[y.Id] = rel;
		}
	});
	rels["!id"] = hash;
	return rels;
}


/* TODO */
function write_rels(rels)/*:string*/ {
	var o = [XML_HEADER, writextag('Relationships', null, {
		//'xmlns:ns0': XMLNS.RELS,
		'xmlns': XMLNS.RELS
	})];
	keys(rels['!id']).forEach(function(rid) {
		o[o.length] = (writextag('Relationship', null, rels['!id'][rid]));
	});
	if(o.length>2){ o[o.length] = ('</Relationships>'); o[1]=o[1].replace("/>",">"); }
	return o.join("");
}

function add_rels(rels, rId/*:number*/, f, type, relobj, targetmode/*:?string*/)/*:number*/ {
	if(!relobj) relobj = {};
	if(!rels['!id']) rels['!id'] = {};
	if(!rels['!idx']) rels['!idx'] = 1;
	if(rId < 0) for(rId = rels['!idx']; rels['!id']['rId' + rId]; ++rId){/* empty */}
	rels['!idx'] = rId + 1;
	relobj.Id = 'rId' + rId;
	relobj.Type = type;
	relobj.Target = f;
	if(targetmode) relobj.TargetMode = targetmode;
	else if([RELS.HLINK, RELS.XPATH, RELS.XMISS].indexOf(relobj.Type) > -1) relobj.TargetMode = "External";
	if(rels['!id'][relobj.Id]) throw new Error("Cannot rewrite rId " + rId);
	rels['!id'][relobj.Id] = relobj;
	rels[('/' + relobj.Target).replace("//","/")] = relobj;
	return rId;
}
/* Open Document Format for Office Applications (OpenDocument) Version 1.2 */
/* Part 3 Section 4 Manifest File */
var CT_ODS = "application/vnd.oasis.opendocument.spreadsheet";
function parse_manifest(d, opts) {
	var str = xlml_normalize(d);
	var Rn;
	var FEtag;
	while((Rn = xlmlregex.exec(str))) switch(Rn[3]) {
		case 'manifest': break; // 4.2 <manifest:manifest>
		case 'file-entry': // 4.3 <manifest:file-entry>
			FEtag = parsexmltag(Rn[0], false);
			if(FEtag.path == '/' && FEtag.type !== CT_ODS) throw new Error("This OpenDocument is not a spreadsheet");
			break;
		case 'encryption-data': // 4.4 <manifest:encryption-data>
		case 'algorithm': // 4.5 <manifest:algorithm>
		case 'start-key-generation': // 4.6 <manifest:start-key-generation>
		case 'key-derivation': // 4.7 <manifest:key-derivation>
			throw new Error("Unsupported ODS Encryption");
		default: if(opts && opts.WTF) throw Rn;
	}
}

function write_manifest(manifest/*:Array<Array<string> >*/)/*:string*/ {
	var o = [XML_HEADER];
	o.push('<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">\n');
	o.push('  <manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>\n');
	for(var i = 0; i < manifest.length; ++i) o.push('  <manifest:file-entry manifest:full-path="' + manifest[i][0] + '" manifest:media-type="' + manifest[i][1] + '"/>\n');
	o.push('</manifest:manifest>');
	return o.join("");
}

/* Part 3 Section 6 Metadata Manifest File */
function write_rdf_type(file/*:string*/, res/*:string*/, tag/*:?string*/) {
	return [
		'  <rdf:Description rdf:about="' + file + '">\n',
		'    <rdf:type rdf:resource="http://docs.oasis-open.org/ns/office/1.2/meta/' + (tag || "odf") + '#' + res + '"/>\n',
		'  </rdf:Description>\n'
	].join("");
}
function write_rdf_has(base/*:string*/, file/*:string*/) {
	return [
		'  <rdf:Description rdf:about="' + base + '">\n',
		'    <ns0:hasPart xmlns:ns0="http://docs.oasis-open.org/ns/office/1.2/meta/pkg#" rdf:resource="' + file + '"/>\n',
		'  </rdf:Description>\n'
	].join("");
}
function write_rdf(rdf) {
	var o = [XML_HEADER];
	o.push('<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n');
	for(var i = 0; i != rdf.length; ++i) {
		o.push(write_rdf_type(rdf[i][0], rdf[i][1]));
		o.push(write_rdf_has("",rdf[i][0]));
	}
	o.push(write_rdf_type("","Document", "pkg"));
	o.push('</rdf:RDF>');
	return o.join("");
}
/* TODO: pull properties */
function write_meta_ods(/*:: wb: Workbook, opts: any*/)/*:string*/ {
	return '<office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xlink="http://www.w3.org/1999/xlink" office:version="1.2"><office:meta><meta:generator>Sheet' + 'JS ' + XLSX.version + '</meta:generator></office:meta></office:document-meta>';
}

/* ECMA-376 Part II 11.1 Core Properties Part */
/* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
var CORE_PROPS/*:Array<Array<string> >*/ = [
	["cp:category", "Category"],
	["cp:contentStatus", "ContentStatus"],
	["cp:keywords", "Keywords"],
	["cp:lastModifiedBy", "LastAuthor"],
	["cp:lastPrinted", "LastPrinted"],
	["cp:revision", "RevNumber"],
	["cp:version", "Version"],
	["dc:creator", "Author"],
	["dc:description", "Comments"],
	["dc:identifier", "Identifier"],
	["dc:language", "Language"],
	["dc:subject", "Subject"],
	["dc:title", "Title"],
	["dcterms:created", "CreatedDate", 'date'],
	["dcterms:modified", "ModifiedDate", 'date']
];

var CORE_PROPS_REGEX/*:Array<RegExp>*/ = /*#__PURE__*/(function() {
	var r = new Array(CORE_PROPS.length);
	for(var i = 0; i < CORE_PROPS.length; ++i) {
		var f = CORE_PROPS[i];
		var g = "(?:"+ f[0].slice(0,f[0].indexOf(":")) +":)"+ f[0].slice(f[0].indexOf(":")+1);
		r[i] = new RegExp("<" + g + "[^>]*>([\\s\\S]*?)<\/" + g + ">");
	}
	return r;
})();

function parse_core_props(data) {
	var p = {};
	data = utf8read(data);

	for(var i = 0; i < CORE_PROPS.length; ++i) {
		var f = CORE_PROPS[i], cur = data.match(CORE_PROPS_REGEX[i]);
		if(cur != null && cur.length > 0) p[f[1]] = unescapexml(cur[1]);
		if(f[2] === 'date' && p[f[1]]) p[f[1]] = parseDate(p[f[1]]);
	}

	return p;
}

function cp_doit(f, g, h, o, p) {
	if(p[f] != null || g == null || g === "") return;
	p[f] = g;
	g = escapexml(g);
	o[o.length] = (h ? writextag(f,g,h) : writetag(f,g));
}

function write_core_props(cp, _opts) {
	var opts = _opts || {};
	var o = [XML_HEADER, writextag('cp:coreProperties', null, {
		//'xmlns': XMLNS.CORE_PROPS,
		'xmlns:cp': XMLNS.CORE_PROPS,
		'xmlns:dc': XMLNS.dc,
		'xmlns:dcterms': XMLNS.dcterms,
		'xmlns:dcmitype': XMLNS.dcmitype,
		'xmlns:xsi': XMLNS.xsi
	})], p = {};
	if(!cp && !opts.Props) return o.join("");

	if(cp) {
		if(cp.CreatedDate != null) cp_doit("dcterms:created", typeof cp.CreatedDate === "string" ? cp.CreatedDate : write_w3cdtf(cp.CreatedDate, opts.WTF), {"xsi:type":"dcterms:W3CDTF"}, o, p);
		if(cp.ModifiedDate != null) cp_doit("dcterms:modified", typeof cp.ModifiedDate === "string" ? cp.ModifiedDate : write_w3cdtf(cp.ModifiedDate, opts.WTF), {"xsi:type":"dcterms:W3CDTF"}, o, p);
	}

	for(var i = 0; i != CORE_PROPS.length; ++i) {
		var f = CORE_PROPS[i];
		var v = opts.Props && opts.Props[f[1]] != null ? opts.Props[f[1]] : cp ? cp[f[1]] : null;
		if(v === true) v = "1";
		else if(v === false) v = "0";
		else if(typeof v == "number") v = String(v);
		if(v != null) cp_doit(f[0], v, null, o, p);
	}
	if(o.length>2){ o[o.length] = ('</cp:coreProperties>'); o[1]=o[1].replace("/>",">"); }
	return o.join("");
}
/* 15.2.12.3 Extended File Properties Part */
/* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
var EXT_PROPS/*:Array<Array<string> >*/ = [
	["Application", "Application", "string"],
	["AppVersion", "AppVersion", "string"],
	["Company", "Company", "string"],
	["DocSecurity", "DocSecurity", "string"],
	["Manager", "Manager", "string"],
	["HyperlinksChanged", "HyperlinksChanged", "bool"],
	["SharedDoc", "SharedDoc", "bool"],
	["LinksUpToDate", "LinksUpToDate", "bool"],
	["ScaleCrop", "ScaleCrop", "bool"],
	["HeadingPairs", "HeadingPairs", "raw"],
	["TitlesOfParts", "TitlesOfParts", "raw"]
];

var PseudoPropsPairs = [
	"Worksheets",  "SheetNames",
	"NamedRanges", "DefinedNames",
	"Chartsheets", "ChartNames"
];
function load_props_pairs(HP/*:string|Array<Array<any>>*/, TOP, props, opts) {
	var v = [];
	if(typeof HP == "string") v = parseVector(HP, opts);
	else for(var j = 0; j < HP.length; ++j) v = v.concat(HP[j].map(function(hp) { return {v:hp}; }));
	var parts = (typeof TOP == "string") ? parseVector(TOP, opts).map(function (x) { return x.v; }) : TOP;
	var idx = 0, len = 0;
	if(parts.length > 0) for(var i = 0; i !== v.length; i += 2) {
		len = +(v[i+1].v);
		switch(v[i].v) {
			case "Worksheets":
			case "工作表":
			case "Листы":
			case "أوراق العمل":
			case "ワークシート":
			case "גליונות עבודה":
			case "Arbeitsblätter":
			case "Çalışma Sayfaları":
			case "Feuilles de calcul":
			case "Fogli di lavoro":
			case "Folhas de cálculo":
			case "Planilhas":
			case "Regneark":
			case "Hojas de cálculo":
			case "Werkbladen":
				props.Worksheets = len;
				props.SheetNames = parts.slice(idx, idx + len);
				break;

			case "Named Ranges":
			case "Rangos con nombre":
			case "名前付き一覧":
			case "Benannte Bereiche":
			case "Navngivne områder":
				props.NamedRanges = len;
				props.DefinedNames = parts.slice(idx, idx + len);
				break;

			case "Charts":
			case "Diagramme":
				props.Chartsheets = len;
				props.ChartNames = parts.slice(idx, idx + len);
				break;
		}
		idx += len;
	}
}

function parse_ext_props(data, p, opts) {
	var q = {}; if(!p) p = {};
	data = utf8read(data);

	EXT_PROPS.forEach(function(f) {
		var xml = (data.match(matchtag(f[0]))||[])[1];
		switch(f[2]) {
			case "string": if(xml) p[f[1]] = unescapexml(xml); break;
			case "bool": p[f[1]] = xml === "true"; break;
			case "raw":
				var cur = data.match(new RegExp("<" + f[0] + "[^>]*>([\\s\\S]*?)<\/" + f[0] + ">"));
				if(cur && cur.length > 0) q[f[1]] = cur[1];
				break;
		}
	});

	if(q.HeadingPairs && q.TitlesOfParts) load_props_pairs(q.HeadingPairs, q.TitlesOfParts, p, opts);

	return p;
}

function write_ext_props(cp/*::, opts*/)/*:string*/ {
	var o/*:Array<string>*/ = [], W = writextag;
	if(!cp) cp = {};
	cp.Application = "SheetJS";
	o[o.length] = (XML_HEADER);
	o[o.length] = (writextag('Properties', null, {
		'xmlns': XMLNS.EXT_PROPS,
		'xmlns:vt': XMLNS.vt
	}));

	EXT_PROPS.forEach(function(f) {
		if(cp[f[1]] === undefined) return;
		var v;
		switch(f[2]) {
			case 'string': v = escapexml(String(cp[f[1]])); break;
			case 'bool': v = cp[f[1]] ? 'true' : 'false'; break;
		}
		if(v !== undefined) o[o.length] = (W(f[0], v));
	});

	/* TODO: HeadingPairs, TitlesOfParts */
	o[o.length] = (W('HeadingPairs', W('vt:vector', W('vt:variant', '<vt:lpstr>Worksheets</vt:lpstr>')+W('vt:variant', W('vt:i4', String(cp.Worksheets))), {size:2, baseType:"variant"})));
	o[o.length] = (W('TitlesOfParts', W('vt:vector', cp.SheetNames.map(function(s) { return "<vt:lpstr>" + escapexml(s) + "</vt:lpstr>"; }).join(""), {size: cp.Worksheets, baseType:"lpstr"})));
	if(o.length>2){ o[o.length] = ('</Properties>'); o[1]=o[1].replace("/>",">"); }
	return o.join("");
}
/* 15.2.12.2 Custom File Properties Part */
var custregex = /<[^>]+>[^<]*/g;
function parse_cust_props(data/*:string*/, opts) {
	var p = {}, name = "";
	var m = data.match(custregex);
	if(m) for(var i = 0; i != m.length; ++i) {
		var x = m[i], y = parsexmltag(x);
		switch(y[0]) {
			case '<?xml': break;
			case '<Properties': break;
			case '<property': name = unescapexml(y.name); break;
			case '</property>': name = null; break;
			default: if (x.indexOf('<vt:') === 0) {
				var toks = x.split('>');
				var type = toks[0].slice(4), text = toks[1];
				/* 22.4.2.32 (CT_Variant). Omit the binary types from 22.4 (Variant Types) */
				switch(type) {
					case 'lpstr': case 'bstr': case 'lpwstr':
						p[name] = unescapexml(text);
						break;
					case 'bool':
						p[name] = parsexmlbool(text);
						break;
					case 'i1': case 'i2': case 'i4': case 'i8': case 'int': case 'uint':
						p[name] = parseInt(text, 10);
						break;
					case 'r4': case 'r8': case 'decimal':
						p[name] = parseFloat(text);
						break;
					case 'filetime': case 'date':
						p[name] = parseDate(text);
						break;
					case 'cy': case 'error':
						p[name] = unescapexml(text);
						break;
					default:
						if(type.slice(-1) == '/') break;
						if(opts.WTF && typeof console !== 'undefined') console.warn('Unexpected', x, type, toks);
				}
			} else if(x.slice(0,2) === "</") {/* empty */
			} else if(opts.WTF) throw new Error(x);
		}
	}
	return p;
}

function write_cust_props(cp/*::, opts*/)/*:string*/ {
	var o = [XML_HEADER, writextag('Properties', null, {
		'xmlns': XMLNS.CUST_PROPS,
		'xmlns:vt': XMLNS.vt
	})];
	if(!cp) return o.join("");
	var pid = 1;
	keys(cp).forEach(function custprop(k) { ++pid;
		o[o.length] = (writextag('property', write_vt(cp[k], true), {
			'fmtid': '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}',
			'pid': pid,
			'name': escapexml(k)
		}));
	});
	if(o.length>2){ o[o.length] = '</Properties>'; o[1]=o[1].replace("/>",">"); }
	return o.join("");
}
/* Common Name -> XLML Name */
var XLMLDocPropsMap = {
	Title: 'Title',
	Subject: 'Subject',
	Author: 'Author',
	Keywords: 'Keywords',
	Comments: 'Description',
	LastAuthor: 'LastAuthor',
	RevNumber: 'Revision',
	Application: 'AppName',
	/* TotalTime: 'TotalTime', */
	LastPrinted: 'LastPrinted',
	CreatedDate: 'Created',
	ModifiedDate: 'LastSaved',
	/* Pages */
	/* Words */
	/* Characters */
	Category: 'Category',
	/* PresentationFormat */
	Manager: 'Manager',
	Company: 'Company',
	/* Guid */
	/* HyperlinkBase */
	/* Bytes */
	/* Lines */
	/* Paragraphs */
	/* CharactersWithSpaces */
	AppVersion: 'Version',

	ContentStatus: 'ContentStatus', /* NOTE: missing from schema */
	Identifier: 'Identifier', /* NOTE: missing from schema */
	Language: 'Language' /* NOTE: missing from schema */
};
var evert_XLMLDPM;

function xlml_set_prop(Props, tag/*:string*/, val) {
	if(!evert_XLMLDPM) evert_XLMLDPM = evert(XLMLDocPropsMap);
	tag = evert_XLMLDPM[tag] || tag;
	Props[tag] = val;
}

function xlml_write_docprops(Props, opts) {
	var o/*:Array<string>*/ = [];
	keys(XLMLDocPropsMap).map(function(m) {
		for(var i = 0; i < CORE_PROPS.length; ++i) if(CORE_PROPS[i][1] == m) return CORE_PROPS[i];
		for(i = 0; i < EXT_PROPS.length; ++i) if(EXT_PROPS[i][1] == m) return EXT_PROPS[i];
		throw m;
	}).forEach(function(p) {
		if(Props[p[1]] == null) return;
		var m = opts && opts.Props && opts.Props[p[1]] != null ? opts.Props[p[1]] : Props[p[1]];
		switch(p[2]) {
			case 'date': m = new Date(m).toISOString().replace(/\.\d*Z/,"Z"); break;
		}
		if(typeof m == 'number') m = String(m);
		else if(m === true || m === false) { m = m ? "1" : "0"; }
		else if(m instanceof Date) m = new Date(m).toISOString().replace(/\.\d*Z/,"");
		o.push(writetag(XLMLDocPropsMap[p[1]] || p[1], m));
	});
	return writextag('DocumentProperties', o.join(""), {xmlns:XLMLNS.o });
}
function xlml_write_custprops(Props, Custprops/*::, opts*/) {
	var BLACKLIST = ["Worksheets","SheetNames"];
	var T = 'CustomDocumentProperties';
	var o/*:Array<string>*/ = [];
	if(Props) keys(Props).forEach(function(k) {
		/*:: if(!Props) return; */
		if(!Object.prototype.hasOwnProperty.call(Props, k)) return;
		for(var i = 0; i < CORE_PROPS.length; ++i) if(k == CORE_PROPS[i][1]) return;
		for(i = 0; i < EXT_PROPS.length; ++i) if(k == EXT_PROPS[i][1]) return;
		for(i = 0; i < BLACKLIST.length; ++i) if(k == BLACKLIST[i]) return;

		var m = Props[k];
		var t = "string";
		if(typeof m == 'number') { t = "float"; m = String(m); }
		else if(m === true || m === false) { t = "boolean"; m = m ? "1" : "0"; }
		else m = String(m);
		o.push(writextag(escapexmltag(k), m, {"dt:dt":t}));
	});
	if(Custprops) keys(Custprops).forEach(function(k) {
		/*:: if(!Custprops) return; */
		if(!Object.prototype.hasOwnProperty.call(Custprops, k)) return;
		if(Props && Object.prototype.hasOwnProperty.call(Props, k)) return;
		var m = Custprops[k];
		var t = "string";
		if(typeof m == 'number') { t = "float"; m = String(m); }
		else if(m === true || m === false) { t = "boolean"; m = m ? "1" : "0"; }
		else if(m instanceof Date) { t = "dateTime.tz"; m = m.toISOString(); }
		else m = String(m);
		o.push(writextag(escapexmltag(k), m, {"dt:dt":t}));
	});
	return '<' + T + ' xmlns="' + XLMLNS.o + '">' + o.join("") + '</' + T + '>';
}
/* [MS-DTYP] 2.3.3 FILETIME */
/* [MS-OLEDS] 2.1.3 FILETIME (Packet Version) */
/* [MS-OLEPS] 2.8 FILETIME (Packet Version) */
function parse_FILETIME(blob) {
	var dwLowDateTime = blob.read_shift(4), dwHighDateTime = blob.read_shift(4);
	return new Date(((dwHighDateTime/1e7*Math.pow(2,32) + dwLowDateTime/1e7) - 11644473600)*1000).toISOString().replace(/\.000/,"");
}
function write_FILETIME(time/*:string|Date*/) {
	var date = (typeof time == "string") ? new Date(Date.parse(time)) : time;
	var t = date.getTime() / 1000 + 11644473600;
	var l = t % Math.pow(2,32), h = (t - l) / Math.pow(2,32);
	l *= 1e7; h *= 1e7;
	var w = (l / Math.pow(2,32)) | 0;
	if(w > 0) { l = l % Math.pow(2,32); h += w; }
	var o = new_buf(8); o.write_shift(4, l); o.write_shift(4, h); return o;
}

/* [MS-OSHARED] 2.3.3.1.4 Lpstr */
function parse_lpstr(blob, type, pad/*:?number*/) {
	var start = blob.l;
	var str = blob.read_shift(0, 'lpstr-cp');
	if(pad) while((blob.l - start) & 3) ++blob.l;
	return str;
}

/* [MS-OSHARED] 2.3.3.1.6 Lpwstr */
function parse_lpwstr(blob, type, pad) {
	var str = blob.read_shift(0, 'lpwstr');
	if(pad) blob.l += (4 - ((str.length+1) & 3)) & 3;
	return str;
}


/* [MS-OSHARED] 2.3.3.1.11 VtString */
/* [MS-OSHARED] 2.3.3.1.12 VtUnalignedString */
function parse_VtStringBase(blob, stringType, pad) {
	if(stringType === 0x1F /*VT_LPWSTR*/) return parse_lpwstr(blob);
	return parse_lpstr(blob, stringType, pad);
}

function parse_VtString(blob, t/*:number*/, pad/*:?boolean*/) { return parse_VtStringBase(blob, t, pad === false ? 0: 4); }
function parse_VtUnalignedString(blob, t/*:number*/) { if(!t) throw new Error("VtUnalignedString must have positive length"); return parse_VtStringBase(blob, t, 0); }

/* [MS-OSHARED] 2.3.3.1.7 VtVecLpwstrValue */
function parse_VtVecLpwstrValue(blob)/*:Array<string>*/ {
	var length = blob.read_shift(4);
	var ret/*:Array<string>*/ = [];
	for(var i = 0; i != length; ++i) {
		var start = blob.l;
		ret[i] = blob.read_shift(0, 'lpwstr').replace(chr0,'');
		if((blob.l - start) & 0x02) blob.l += 2;
	}
	return ret;
}

/* [MS-OSHARED] 2.3.3.1.9 VtVecUnalignedLpstrValue */
function parse_VtVecUnalignedLpstrValue(blob)/*:Array<string>*/ {
	var length = blob.read_shift(4);
	var ret/*:Array<string>*/ = [];
	for(var i = 0; i != length; ++i) ret[i] = blob.read_shift(0, 'lpstr-cp').replace(chr0,'');
	return ret;
}


/* [MS-OSHARED] 2.3.3.1.13 VtHeadingPair */
function parse_VtHeadingPair(blob) {
	var start = blob.l;
	var headingString = parse_TypedPropertyValue(blob, VT_USTR);
	if(blob[blob.l] == 0x00 && blob[blob.l+1] == 0x00 && ((blob.l - start) & 0x02)) blob.l += 2;
	var headerParts = parse_TypedPropertyValue(blob, VT_I4);
	return [headingString, headerParts];
}

/* [MS-OSHARED] 2.3.3.1.14 VtVecHeadingPairValue */
function parse_VtVecHeadingPairValue(blob) {
	var cElements = blob.read_shift(4);
	var out = [];
	for(var i = 0; i < cElements / 2; ++i) out.push(parse_VtHeadingPair(blob));
	return out;
}

/* [MS-OLEPS] 2.18.1 Dictionary (uses 2.17, 2.16) */
function parse_dictionary(blob,CodePage) {
	var cnt = blob.read_shift(4);
	var dict/*:{[number]:string}*/ = ({}/*:any*/);
	for(var j = 0; j != cnt; ++j) {
		var pid = blob.read_shift(4);
		var len = blob.read_shift(4);
		dict[pid] = blob.read_shift(len, (CodePage === 0x4B0 ?'utf16le':'utf8')).replace(chr0,'').replace(chr1,'!');
		if(CodePage === 0x4B0 && (len % 2)) blob.l += 2;
	}
	if(blob.l & 3) blob.l = (blob.l>>2+1)<<2;
	return dict;
}

/* [MS-OLEPS] 2.9 BLOB */
function parse_BLOB(blob) {
	var size = blob.read_shift(4);
	var bytes = blob.slice(blob.l,blob.l+size);
	blob.l += size;
	if((size & 3) > 0) blob.l += (4 - (size & 3)) & 3;
	return bytes;
}

/* [MS-OLEPS] 2.11 ClipboardData */
function parse_ClipboardData(blob) {
	// TODO
	var o = {};
	o.Size = blob.read_shift(4);
	//o.Format = blob.read_shift(4);
	blob.l += o.Size + 3 - (o.Size - 1) % 4;
	return o;
}

/* [MS-OLEPS] 2.15 TypedPropertyValue */
function parse_TypedPropertyValue(blob, type/*:number*/, _opts)/*:any*/ {
	var t = blob.read_shift(2), ret, opts = _opts||{};
	blob.l += 2;
	if(type !== VT_VARIANT)
	if(t !== type && VT_CUSTOM.indexOf(type)===-1 && !((type & 0xFFFE) == 0x101E && (t & 0xFFFE) == 0x101E)) throw new Error('Expected type ' + type + ' saw ' + t);
	switch(type === VT_VARIANT ? t : type) {
		case 0x02 /*VT_I2*/: ret = blob.read_shift(2, 'i'); if(!opts.raw) blob.l += 2; return ret;
		case 0x03 /*VT_I4*/: ret = blob.read_shift(4, 'i'); return ret;
		case 0x0B /*VT_BOOL*/: return blob.read_shift(4) !== 0x0;
		case 0x13 /*VT_UI4*/: ret = blob.read_shift(4); return ret;
		case 0x1E /*VT_LPSTR*/: return parse_lpstr(blob, t, 4).replace(chr0,'');
		case 0x1F /*VT_LPWSTR*/: return parse_lpwstr(blob);
		case 0x40 /*VT_FILETIME*/: return parse_FILETIME(blob);
		case 0x41 /*VT_BLOB*/: return parse_BLOB(blob);
		case 0x47 /*VT_CF*/: return parse_ClipboardData(blob);
		case 0x50 /*VT_STRING*/: return parse_VtString(blob, t, !opts.raw).replace(chr0,'');
		case 0x51 /*VT_USTR*/: return parse_VtUnalignedString(blob, t/*, 4*/).replace(chr0,'');
		case 0x100C /*VT_VECTOR|VT_VARIANT*/: return parse_VtVecHeadingPairValue(blob);
		case 0x101E /*VT_VECTOR|VT_LPSTR*/:
		case 0x101F /*VT_VECTOR|VT_LPWSTR*/:
			return t == 0x101F ? parse_VtVecLpwstrValue(blob) : parse_VtVecUnalignedLpstrValue(blob);
		default: throw new Error("TypedPropertyValue unrecognized type " + type + " " + t);
	}
}
function write_TypedPropertyValue(type/*:number*/, value) {
	var o = new_buf(4), p = new_buf(4);
	o.write_shift(4, type == 0x50 ? 0x1F : type);
	switch(type) {
		case 0x03 /*VT_I4*/: p.write_shift(-4, value); break;
		case 0x05 /*VT_I4*/: p = new_buf(8); p.write_shift(8, value, 'f'); break;
		case 0x0B /*VT_BOOL*/: p.write_shift(4, value ? 0x01 : 0x00); break;
		case 0x40 /*VT_FILETIME*/: /*:: if(typeof value !== "string" && !(value instanceof Date)) throw "unreachable"; */ p = write_FILETIME(value); break;
		case 0x1F /*VT_LPWSTR*/:
		case 0x50 /*VT_STRING*/:
			/*:: if(typeof value !== "string") throw "unreachable"; */
			p = new_buf(4 + 2 * (value.length + 1) + (value.length % 2 ? 0 : 2));
			p.write_shift(4, value.length + 1);
			p.write_shift(0, value, "dbcs");
			while(p.l != p.length) p.write_shift(1, 0);
			break;
		default: throw new Error("TypedPropertyValue unrecognized type " + type + " " + value);
	}
	return bconcat([o, p]);
}

/* [MS-OLEPS] 2.20 PropertySet */
function parse_PropertySet(blob, PIDSI) {
	var start_addr = blob.l;
	var size = blob.read_shift(4);
	var NumProps = blob.read_shift(4);
	var Props = [], i = 0;
	var CodePage = 0;
	var Dictionary = -1, DictObj/*:{[number]:string}*/ = ({}/*:any*/);
	for(i = 0; i != NumProps; ++i) {
		var PropID = blob.read_shift(4);
		var Offset = blob.read_shift(4);
		Props[i] = [PropID, Offset + start_addr];
	}
	Props.sort(function(x,y) { return x[1] - y[1]; });
	var PropH = {};
	for(i = 0; i != NumProps; ++i) {
		if(blob.l !== Props[i][1]) {
			var fail = true;
			if(i>0 && PIDSI) switch(PIDSI[Props[i-1][0]].t) {
				case 0x02 /*VT_I2*/: if(blob.l+2 === Props[i][1]) { blob.l+=2; fail = false; } break;
				case 0x50 /*VT_STRING*/: if(blob.l <= Props[i][1]) { blob.l=Props[i][1]; fail = false; } break;
				case 0x100C /*VT_VECTOR|VT_VARIANT*/: if(blob.l <= Props[i][1]) { blob.l=Props[i][1]; fail = false; } break;
			}
			if((!PIDSI||i==0) && blob.l <= Props[i][1]) { fail=false; blob.l = Props[i][1]; }
			if(fail) throw new Error("Read Error: Expected address " + Props[i][1] + ' at ' + blob.l + ' :' + i);
		}
		if(PIDSI) {
			var piddsi = PIDSI[Props[i][0]];
			PropH[piddsi.n] = parse_TypedPropertyValue(blob, piddsi.t, {raw:true});
			if(piddsi.p === 'version') PropH[piddsi.n] = String(PropH[piddsi.n] >> 16) + "." + ("0000" + String(PropH[piddsi.n] & 0xFFFF)).slice(-4);
			if(piddsi.n == "CodePage") switch(PropH[piddsi.n]) {
				case 0: PropH[piddsi.n] = 1252;
					/* falls through */
				case 874:
				case 932:
				case 936:
				case 949:
				case 950:
				case 1250:
				case 1251:
				case 1253:
				case 1254:
				case 1255:
				case 1256:
				case 1257:
				case 1258:
				case 10000:
				case 1200:
				case 1201:
				case 1252:
				case 65000: case -536:
				case 65001: case -535:
					set_cp(CodePage = (PropH[piddsi.n]>>>0) & 0xFFFF); break;
				default: throw new Error("Unsupported CodePage: " + PropH[piddsi.n]);
			}
		} else {
			if(Props[i][0] === 0x1) {
				CodePage = PropH.CodePage = (parse_TypedPropertyValue(blob, VT_I2)/*:number*/);
				set_cp(CodePage);
				if(Dictionary !== -1) {
					var oldpos = blob.l;
					blob.l = Props[Dictionary][1];
					DictObj = parse_dictionary(blob,CodePage);
					blob.l = oldpos;
				}
			} else if(Props[i][0] === 0) {
				if(CodePage === 0) { Dictionary = i; blob.l = Props[i+1][1]; continue; }
				DictObj = parse_dictionary(blob,CodePage);
			} else {
				var name = DictObj[Props[i][0]];
				var val;
				/* [MS-OSHARED] 2.3.3.2.3.1.2 + PROPVARIANT */
				switch(blob[blob.l]) {
					case 0x41 /*VT_BLOB*/: blob.l += 4; val = parse_BLOB(blob); break;
					case 0x1E /*VT_LPSTR*/: blob.l += 4; val = parse_VtString(blob, blob[blob.l-4]).replace(/\u0000+$/,""); break;
					case 0x1F /*VT_LPWSTR*/: blob.l += 4; val = parse_VtString(blob, blob[blob.l-4]).replace(/\u0000+$/,""); break;
					case 0x03 /*VT_I4*/: blob.l += 4; val = blob.read_shift(4, 'i'); break;
					case 0x13 /*VT_UI4*/: blob.l += 4; val = blob.read_shift(4); break;
					case 0x05 /*VT_R8*/: blob.l += 4; val = blob.read_shift(8, 'f'); break;
					case 0x0B /*VT_BOOL*/: blob.l += 4; val = parsebool(blob, 4); break;
					case 0x40 /*VT_FILETIME*/: blob.l += 4; val = parseDate(parse_FILETIME(blob)); break;
					default: throw new Error("unparsed value: " + blob[blob.l]);
				}
				PropH[name] = val;
			}
		}
	}
	blob.l = start_addr + size; /* step ahead to skip padding */
	return PropH;
}
var XLSPSSkip = [ "CodePage", "Thumbnail", "_PID_LINKBASE", "_PID_HLINKS", "SystemIdentifier", "FMTID" ]; //.concat(PseudoPropsPairs);
function guess_property_type(val/*:any*/)/*:number*/ {
	switch(typeof val) {
		case "boolean": return 0x0B;
		case "number": return ((val|0)==val) ? 0x03 : 0x05;
		case "string": return 0x1F;
		case "object": if(val instanceof Date) return 0x40; break;
	}
	return -1;
}
function write_PropertySet(entries, RE, PIDSI) {
	var hdr = new_buf(8), piao = [], prop = [];
	var sz = 8, i = 0;

	var pr = new_buf(8), pio = new_buf(8);
	pr.write_shift(4, 0x0002);
	pr.write_shift(4, 0x04B0);
	pio.write_shift(4, 0x0001);
	prop.push(pr); piao.push(pio);
	sz += 8 + pr.length;

	if(!RE) {
		pio = new_buf(8);
		pio.write_shift(4, 0);
		piao.unshift(pio);

		var bufs = [new_buf(4)];
		bufs[0].write_shift(4, entries.length);
		for(i = 0; i < entries.length; ++i) {
			var value = entries[i][0];
			pr = new_buf(4 + 4 + 2 * (value.length + 1) + (value.length % 2 ? 0 : 2));
			pr.write_shift(4, i+2);
			pr.write_shift(4, value.length + 1);
			pr.write_shift(0, value, "dbcs");
			while(pr.l != pr.length) pr.write_shift(1, 0);
			bufs.push(pr);
		}
		pr = bconcat(bufs);
		prop.unshift(pr);
		sz += 8 + pr.length;
	}

	for(i = 0; i < entries.length; ++i) {
		if(RE && !RE[entries[i][0]]) continue;
		if(XLSPSSkip.indexOf(entries[i][0]) > -1 || PseudoPropsPairs.indexOf(entries[i][0]) > -1) continue;
		if(entries[i][1] == null) continue;

		var val = entries[i][1], idx = 0;
		if(RE) {
			idx = +RE[entries[i][0]];
			var pinfo = (PIDSI/*:: || {}*/)[idx]/*:: || {} */;
			if(pinfo.p == "version" && typeof val == "string") {
				/*:: if(typeof val !== "string") throw "unreachable"; */
				var arr = val.split(".");
				val = ((+arr[0])<<16) + ((+arr[1])||0);
			}
			pr = write_TypedPropertyValue(pinfo.t, val);
		} else {
			var T = guess_property_type(val);
			if(T == -1) { T = 0x1F; val = String(val); }
			pr = write_TypedPropertyValue(T, val);
		}
		prop.push(pr);

		pio = new_buf(8);
		pio.write_shift(4, !RE ? 2+i : idx);
		piao.push(pio);

		sz += 8 + pr.length;
	}

	var w = 8 * (prop.length + 1);
	for(i = 0; i < prop.length; ++i) { piao[i].write_shift(4, w); w += prop[i].length; }
	hdr.write_shift(4, sz);
	hdr.write_shift(4, prop.length);
	return bconcat([hdr].concat(piao).concat(prop));
}

/* [MS-OLEPS] 2.21 PropertySetStream */
function parse_PropertySetStream(file, PIDSI, clsid) {
	var blob = file.content;
	if(!blob) return ({}/*:any*/);
	prep_blob(blob, 0);

	var NumSets, FMTID0, FMTID1, Offset0, Offset1 = 0;
	blob.chk('feff', 'Byte Order: ');

	/*var vers = */blob.read_shift(2); // TODO: check version
	var SystemIdentifier = blob.read_shift(4);
	var CLSID = blob.read_shift(16);
	if(CLSID !== CFB.utils.consts.HEADER_CLSID && CLSID !== clsid) throw new Error("Bad PropertySet CLSID " + CLSID);
	NumSets = blob.read_shift(4);
	if(NumSets !== 1 && NumSets !== 2) throw new Error("Unrecognized #Sets: " + NumSets);
	FMTID0 = blob.read_shift(16); Offset0 = blob.read_shift(4);

	if(NumSets === 1 && Offset0 !== blob.l) throw new Error("Length mismatch: " + Offset0 + " !== " + blob.l);
	else if(NumSets === 2) { FMTID1 = blob.read_shift(16); Offset1 = blob.read_shift(4); }
	var PSet0 = parse_PropertySet(blob, PIDSI);

	var rval = ({ SystemIdentifier: SystemIdentifier }/*:any*/);
	for(var y in PSet0) rval[y] = PSet0[y];
	//rval.blob = blob;
	rval.FMTID = FMTID0;
	//rval.PSet0 = PSet0;
	if(NumSets === 1) return rval;
	if(Offset1 - blob.l == 2) blob.l += 2;
	if(blob.l !== Offset1) throw new Error("Length mismatch 2: " + blob.l + " !== " + Offset1);
	var PSet1;
	try { PSet1 = parse_PropertySet(blob, null); } catch(e) {/* empty */}
	for(y in PSet1) rval[y] = PSet1[y];
	rval.FMTID = [FMTID0, FMTID1]; // TODO: verify FMTID0/1
	return rval;
}
function write_PropertySetStream(entries, clsid, RE, PIDSI/*:{[key:string|number]:any}*/, entries2/*:?any*/, clsid2/*:?any*/) {
	var hdr = new_buf(entries2 ? 68 : 48);
	var bufs = [hdr];
	hdr.write_shift(2, 0xFFFE);
	hdr.write_shift(2, 0x0000); /* TODO: type 1 props */
	hdr.write_shift(4, 0x32363237);
	hdr.write_shift(16, CFB.utils.consts.HEADER_CLSID, "hex");
	hdr.write_shift(4, (entries2 ? 2 : 1));
	hdr.write_shift(16, clsid, "hex");
	hdr.write_shift(4, (entries2 ? 68 : 48));
	var ps0 = write_PropertySet(entries, RE, PIDSI);
	bufs.push(ps0);

	if(entries2) {
		var ps1 = write_PropertySet(entries2, null, null);
		hdr.write_shift(16, clsid2, "hex");
		hdr.write_shift(4, 68 + ps0.length);
		bufs.push(ps1);
	}
	return bconcat(bufs);
}

function parsenoop2(blob, length) { blob.read_shift(length); return null; }
function writezeroes(n, o) { if(!o) o=new_buf(n); for(var j=0; j<n; ++j) o.write_shift(1, 0); return o; }

function parslurp(blob, length, cb) {
	var arr = [], target = blob.l + length;
	while(blob.l < target) arr.push(cb(blob, target - blob.l));
	if(target !== blob.l) throw new Error("Slurp error");
	return arr;
}

function parsebool(blob, length/*:number*/) { return blob.read_shift(length) === 0x1; }
function writebool(v/*:any*/, o) { if(!o) o=new_buf(2); o.write_shift(2, +!!v); return o; }

function parseuint16(blob/*::, length:?number, opts:?any*/) { return blob.read_shift(2, 'u'); }
function writeuint16(v/*:number*/, o) { if(!o) o=new_buf(2); o.write_shift(2, v); return o; }
function parseuint16a(blob, length/*:: :?number, opts:?any*/) { return parslurp(blob,length,parseuint16);}

/* --- 2.5 Structures --- */

/* [MS-XLS] 2.5.10 Bes (boolean or error) */
function parse_Bes(blob/*::, length*/) {
	var v = blob.read_shift(1), t = blob.read_shift(1);
	return t === 0x01 ? v : v === 0x01;
}
function write_Bes(v, t/*:string*/, o) {
	if(!o) o = new_buf(2);
	o.write_shift(1, ((t == 'e') ? +v : +!!v));
	o.write_shift(1, ((t == 'e') ? 1 : 0));
	return o;
}

/* [MS-XLS] 2.5.240 ShortXLUnicodeString */
function parse_ShortXLUnicodeString(blob, length, opts) {
	var cch = blob.read_shift(opts && opts.biff >= 12 ? 2 : 1);
	var encoding = 'sbcs-cont';
	var cp = current_codepage;
	if(opts && opts.biff >= 8) current_codepage = 1200;
	if(!opts || opts.biff == 8 ) {
		var fHighByte = blob.read_shift(1);
		if(fHighByte) { encoding = 'dbcs-cont'; }
	} else if(opts.biff == 12) {
		encoding = 'wstr';
	}
	if(opts.biff >= 2 && opts.biff <= 5) encoding = 'cpstr';
	var o = cch ? blob.read_shift(cch, encoding) : "";
	current_codepage = cp;
	return o;
}

/* 2.5.293 XLUnicodeRichExtendedString */
function parse_XLUnicodeRichExtendedString(blob) {
	var cp = current_codepage;
	current_codepage = 1200;
	var cch = blob.read_shift(2), flags = blob.read_shift(1);
	var /*fHighByte = flags & 0x1,*/ fExtSt = flags & 0x4, fRichSt = flags & 0x8;
	var width = 1 + (flags & 0x1); // 0x0 -> utf8, 0x1 -> dbcs
	var cRun = 0, cbExtRst;
	var z = {};
	if(fRichSt) cRun = blob.read_shift(2);
	if(fExtSt) cbExtRst = blob.read_shift(4);
	var encoding = width == 2 ? 'dbcs-cont' : 'sbcs-cont';
	var msg = cch === 0 ? "" : blob.read_shift(cch, encoding);
	if(fRichSt) blob.l += 4 * cRun; //TODO: parse this
	if(fExtSt) blob.l += cbExtRst; //TODO: parse this
	z.t = msg;
	if(!fRichSt) { z.raw = "<t>" + z.t + "</t>"; z.r = z.t; }
	current_codepage = cp;
	return z;
}
function write_XLUnicodeRichExtendedString(xlstr/*:: :XLString, opts*/) {
	var str = (xlstr.t||""), nfmts = 1;

	var hdr = new_buf(3 + (nfmts > 1 ? 2 : 0));
	hdr.write_shift(2, str.length);
	hdr.write_shift(1, (nfmts > 1 ? 0x08 : 0x00) | 0x01);
	if(nfmts > 1) hdr.write_shift(2, nfmts);

	var otext = new_buf(2 * str.length);
	otext.write_shift(2 * str.length, str, 'utf16le');

	var out = [hdr, otext];

	return bconcat(out);
}

/* 2.5.296 XLUnicodeStringNoCch */
function parse_XLUnicodeStringNoCch(blob, cch, opts) {
	var retval;
	if(opts) {
		if(opts.biff >= 2 && opts.biff <= 5) return blob.read_shift(cch, 'cpstr');
		if(opts.biff >= 12) return blob.read_shift(cch, 'dbcs-cont');
	}
	var fHighByte = blob.read_shift(1);
	if(fHighByte===0) { retval = blob.read_shift(cch, 'sbcs-cont'); }
	else { retval = blob.read_shift(cch, 'dbcs-cont'); }
	return retval;
}

/* 2.5.294 XLUnicodeString */
function parse_XLUnicodeString(blob, length, opts) {
	var cch = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
	if(cch === 0) { blob.l++; return ""; }
	return parse_XLUnicodeStringNoCch(blob, cch, opts);
}
/* BIFF5 override */
function parse_XLUnicodeString2(blob, length, opts) {
	if(opts.biff > 5) return parse_XLUnicodeString(blob, length, opts);
	var cch = blob.read_shift(1);
	if(cch === 0) { blob.l++; return ""; }
	return blob.read_shift(cch, (opts.biff <= 4 || !blob.lens ) ? 'cpstr' : 'sbcs-cont');
}
/* TODO: BIFF5 and lower, codepage awareness */
function write_XLUnicodeString(str, opts, o) {
	if(!o) o = new_buf(3 + 2 * str.length);
	o.write_shift(2, str.length);
	o.write_shift(1, 1);
	o.write_shift(31, str, 'utf16le');
	return o;
}

/* [MS-XLS] 2.5.61 ControlInfo */
function parse_ControlInfo(blob/*::, length, opts*/) {
	var flags = blob.read_shift(1);
	blob.l++;
	var accel = blob.read_shift(2);
	blob.l += 2;
	return [flags, accel];
}

/* [MS-OSHARED] 2.3.7.6 URLMoniker TODO: flags */
function parse_URLMoniker(blob/*::, length, opts*/) {
	var len = blob.read_shift(4), start = blob.l;
	var extra = false;
	if(len > 24) {
		/* look ahead */
		blob.l += len - 24;
		if(blob.read_shift(16) === "795881f43b1d7f48af2c825dc4852763") extra = true;
		blob.l = start;
	}
	var url = blob.read_shift((extra?len-24:len)>>1, 'utf16le').replace(chr0,"");
	if(extra) blob.l += 24;
	return url;
}

/* [MS-OSHARED] 2.3.7.8 FileMoniker TODO: all fields */
function parse_FileMoniker(blob/*::, length*/) {
	var cAnti = blob.read_shift(2);
	var preamble = ""; while(cAnti-- > 0) preamble += "../";
	var ansiPath = blob.read_shift(0, 'lpstr-ansi');
	blob.l += 2; //var endServer = blob.read_shift(2);
	if(blob.read_shift(2) != 0xDEAD) throw new Error("Bad FileMoniker");
	var sz = blob.read_shift(4);
	if(sz === 0) return preamble + ansiPath.replace(/\\/g,"/");
	var bytes = blob.read_shift(4);
	if(blob.read_shift(2) != 3) throw new Error("Bad FileMoniker");
	var unicodePath = blob.read_shift(bytes>>1, 'utf16le').replace(chr0,"");
	return preamble + unicodePath;
}

/* [MS-OSHARED] 2.3.7.2 HyperlinkMoniker TODO: all the monikers */
function parse_HyperlinkMoniker(blob, length) {
	var clsid = blob.read_shift(16); length -= 16;
	switch(clsid) {
		case "e0c9ea79f9bace118c8200aa004ba90b": return parse_URLMoniker(blob, length);
		case "0303000000000000c000000000000046": return parse_FileMoniker(blob, length);
		default: throw new Error("Unsupported Moniker " + clsid);
	}
}

/* [MS-OSHARED] 2.3.7.9 HyperlinkString */
function parse_HyperlinkString(blob/*::, length*/) {
	var len = blob.read_shift(4);
	var o = len > 0 ? blob.read_shift(len, 'utf16le').replace(chr0, "") : "";
	return o;
}
function write_HyperlinkString(str/*:string*/, o) {
	if(!o) o = new_buf(6 + str.length * 2);
	o.write_shift(4, 1 + str.length);
	for(var i = 0; i < str.length; ++i) o.write_shift(2, str.charCodeAt(i));
	o.write_shift(2, 0);
	return o;
}

/* [MS-OSHARED] 2.3.7.1 Hyperlink Object */
function parse_Hyperlink(blob, length)/*:Hyperlink*/ {
	var end = blob.l + length;
	var sVer = blob.read_shift(4);
	if(sVer !== 2) throw new Error("Unrecognized streamVersion: " + sVer);
	var flags = blob.read_shift(2);
	blob.l += 2;
	var displayName, targetFrameName, moniker, oleMoniker, Loc="", guid, fileTime;
	if(flags & 0x0010) displayName = parse_HyperlinkString(blob, end - blob.l);
	if(flags & 0x0080) targetFrameName = parse_HyperlinkString(blob, end - blob.l);
	if((flags & 0x0101) === 0x0101) moniker = parse_HyperlinkString(blob, end - blob.l);
	if((flags & 0x0101) === 0x0001) oleMoniker = parse_HyperlinkMoniker(blob, end - blob.l);
	if(flags & 0x0008) Loc = parse_HyperlinkString(blob, end - blob.l);
	if(flags & 0x0020) guid = blob.read_shift(16);
	if(flags & 0x0040) fileTime = parse_FILETIME(blob/*, 8*/);
	blob.l = end;
	var target = targetFrameName||moniker||oleMoniker||"";
	if(target && Loc) target+="#"+Loc;
	if(!target) target = "#" + Loc;
	if((flags & 0x0002) && target.charAt(0) == "/" && target.charAt(1) != "/") target = "file://" + target;
	var out = ({Target:target}/*:any*/);
	if(guid) out.guid = guid;
	if(fileTime) out.time = fileTime;
	if(displayName) out.Tooltip = displayName;
	return out;
}
function write_Hyperlink(hl) {
	var out = new_buf(512), i = 0;
	var Target = hl.Target;
	if(Target.slice(0,7) == "file://") Target = Target.slice(7);
	var hashidx = Target.indexOf("#");
	var F = hashidx > -1 ? 0x1f : 0x17;
	switch(Target.charAt(0)) { case "#": F=0x1c; break; case ".": F&=~2; break; }
	out.write_shift(4,2); out.write_shift(4, F);
	var data = [8,6815827,6619237,4849780,83]; for(i = 0; i < data.length; ++i) out.write_shift(4, data[i]);
	if(F == 0x1C) {
		Target = Target.slice(1);
		write_HyperlinkString(Target, out);
	} else if(F & 0x02) {
		data = "e0 c9 ea 79 f9 ba ce 11 8c 82 00 aa 00 4b a9 0b".split(" ");
		for(i = 0; i < data.length; ++i) out.write_shift(1, parseInt(data[i], 16));
		var Pretarget = hashidx > -1 ? Target.slice(0, hashidx) : Target;
		out.write_shift(4, 2*(Pretarget.length + 1));
		for(i = 0; i < Pretarget.length; ++i) out.write_shift(2, Pretarget.charCodeAt(i));
		out.write_shift(2, 0);
		if(F & 0x08) write_HyperlinkString(hashidx > -1 ? Target.slice(hashidx+1): "", out);
	} else {
		data = "03 03 00 00 00 00 00 00 c0 00 00 00 00 00 00 46".split(" ");
		for(i = 0; i < data.length; ++i) out.write_shift(1, parseInt(data[i], 16));
		var P = 0;
		while(Target.slice(P*3,P*3+3)=="../"||Target.slice(P*3,P*3+3)=="..\\") ++P;
		out.write_shift(2, P);
		out.write_shift(4, Target.length - 3 * P + 1);
		for(i = 0; i < Target.length - 3 * P; ++i) out.write_shift(1, Target.charCodeAt(i + 3 * P) & 0xFF);
		out.write_shift(1, 0);
		out.write_shift(2, 0xFFFF);
		out.write_shift(2, 0xDEAD);
		for(i = 0; i < 6; ++i) out.write_shift(4, 0);
	}
	return out.slice(0, out.l);
}

/* 2.5.178 LongRGBA */
function parse_LongRGBA(blob/*::, length*/) { var r = blob.read_shift(1), g = blob.read_shift(1), b = blob.read_shift(1), a = blob.read_shift(1); return [r,g,b,a]; }

/* 2.5.177 LongRGB */
function parse_LongRGB(blob, length) { var x = parse_LongRGBA(blob, length); x[3] = 0; return x; }


/* [MS-XLS] 2.5.19 */
function parse_XLSCell(blob/*::, length*/)/*:Cell*/ {
	var rw = blob.read_shift(2); // 0-indexed
	var col = blob.read_shift(2);
	var ixfe = blob.read_shift(2);
	return ({r:rw, c:col, ixfe:ixfe}/*:any*/);
}
function write_XLSCell(R/*:number*/, C/*:number*/, ixfe/*:?number*/, o) {
	if(!o) o = new_buf(6);
	o.write_shift(2, R);
	o.write_shift(2, C);
	o.write_shift(2, ixfe||0);
	return o;
}

/* [MS-XLS] 2.5.134 */
function parse_frtHeader(blob) {
	var rt = blob.read_shift(2);
	var flags = blob.read_shift(2); // TODO: parse these flags
	blob.l += 8;
	return {type: rt, flags: flags};
}



function parse_OptXLUnicodeString(blob, length, opts) { return length === 0 ? "" : parse_XLUnicodeString2(blob, length, opts); }

/* [MS-XLS] 2.5.344 */
function parse_XTI(blob, length, opts) {
	var w = opts.biff > 8 ? 4 : 2;
	var iSupBook = blob.read_shift(w), itabFirst = blob.read_shift(w,'i'), itabLast = blob.read_shift(w,'i');
	return [iSupBook, itabFirst, itabLast];
}

/* [MS-XLS] 2.5.218 */
function parse_RkRec(blob) {
	var ixfe = blob.read_shift(2);
	var RK = parse_RkNumber(blob);
	return [ixfe, RK];
}

/* [MS-XLS] 2.5.1 */
function parse_AddinUdf(blob, length, opts) {
	blob.l += 4; length -= 4;
	var l = blob.l + length;
	var udfName = parse_ShortXLUnicodeString(blob, length, opts);
	var cb = blob.read_shift(2);
	l -= blob.l;
	if(cb !== l) throw new Error("Malformed AddinUdf: padding = " + l + " != " + cb);
	blob.l += cb;
	return udfName;
}

/* [MS-XLS] 2.5.209 TODO: Check sizes */
function parse_Ref8U(blob/*::, length*/) {
	var rwFirst = blob.read_shift(2);
	var rwLast = blob.read_shift(2);
	var colFirst = blob.read_shift(2);
	var colLast = blob.read_shift(2);
	return {s:{c:colFirst, r:rwFirst}, e:{c:colLast,r:rwLast}};
}
function write_Ref8U(r/*:Range*/, o) {
	if(!o) o = new_buf(8);
	o.write_shift(2, r.s.r);
	o.write_shift(2, r.e.r);
	o.write_shift(2, r.s.c);
	o.write_shift(2, r.e.c);
	return o;
}

/* [MS-XLS] 2.5.211 */
function parse_RefU(blob/*::, length*/) {
	var rwFirst = blob.read_shift(2);
	var rwLast = blob.read_shift(2);
	var colFirst = blob.read_shift(1);
	var colLast = blob.read_shift(1);
	return {s:{c:colFirst, r:rwFirst}, e:{c:colLast,r:rwLast}};
}

/* [MS-XLS] 2.5.207 */
var parse_Ref = parse_RefU;

/* [MS-XLS] 2.5.143 */
function parse_FtCmo(blob/*::, length*/) {
	blob.l += 4;
	var ot = blob.read_shift(2);
	var id = blob.read_shift(2);
	var flags = blob.read_shift(2);
	blob.l+=12;
	return [id, ot, flags];
}

/* [MS-XLS] 2.5.149 */
function parse_FtNts(blob) {
	var out = {};
	blob.l += 4;
	blob.l += 16; // GUID TODO
	out.fSharedNote = blob.read_shift(2);
	blob.l += 4;
	return out;
}

/* [MS-XLS] 2.5.142 */
function parse_FtCf(blob) {
	var out = {};
	blob.l += 4;
	blob.cf = blob.read_shift(2);
	return out;
}

/* [MS-XLS] 2.5.140 - 2.5.154 and friends */
function parse_FtSkip(blob) { blob.l += 2; blob.l += blob.read_shift(2); }
var FtTab = {
	/*::[*/0x00/*::]*/: parse_FtSkip,      /* FtEnd */
	/*::[*/0x04/*::]*/: parse_FtSkip,      /* FtMacro */
	/*::[*/0x05/*::]*/: parse_FtSkip,      /* FtButton */
	/*::[*/0x06/*::]*/: parse_FtSkip,      /* FtGmo */
	/*::[*/0x07/*::]*/: parse_FtCf,        /* FtCf */
	/*::[*/0x08/*::]*/: parse_FtSkip,      /* FtPioGrbit */
	/*::[*/0x09/*::]*/: parse_FtSkip,      /* FtPictFmla */
	/*::[*/0x0A/*::]*/: parse_FtSkip,      /* FtCbls */
	/*::[*/0x0B/*::]*/: parse_FtSkip,      /* FtRbo */
	/*::[*/0x0C/*::]*/: parse_FtSkip,      /* FtSbs */
	/*::[*/0x0D/*::]*/: parse_FtNts,       /* FtNts */
	/*::[*/0x0E/*::]*/: parse_FtSkip,      /* FtSbsFmla */
	/*::[*/0x0F/*::]*/: parse_FtSkip,      /* FtGboData */
	/*::[*/0x10/*::]*/: parse_FtSkip,      /* FtEdoData */
	/*::[*/0x11/*::]*/: parse_FtSkip,      /* FtRboData */
	/*::[*/0x12/*::]*/: parse_FtSkip,      /* FtCblsData */
	/*::[*/0x13/*::]*/: parse_FtSkip,      /* FtLbsData */
	/*::[*/0x14/*::]*/: parse_FtSkip,      /* FtCblsFmla */
	/*::[*/0x15/*::]*/: parse_FtCmo
};
function parse_FtArray(blob, length/*::, ot*/) {
	var tgt = blob.l + length;
	var fts = [];
	while(blob.l < tgt) {
		var ft = blob.read_shift(2);
		blob.l-=2;
		try {
			fts.push(FtTab[ft](blob, tgt - blob.l));
		} catch(e) { blob.l = tgt; return fts; }
	}
	if(blob.l != tgt) blob.l = tgt; //throw new Error("bad Object Ft-sequence");
	return fts;
}

/* --- 2.4 Records --- */

/* [MS-XLS] 2.4.21 */
function parse_BOF(blob, length) {
	var o = {BIFFVer:0, dt:0};
	o.BIFFVer = blob.read_shift(2); length -= 2;
	if(length >= 2) { o.dt = blob.read_shift(2); blob.l -= 2; }
	switch(o.BIFFVer) {
		case 0x0600: /* BIFF8 */
		case 0x0500: /* BIFF5 */
		case 0x0400: /* BIFF4 */
		case 0x0300: /* BIFF3 */
		case 0x0200: /* BIFF2 */
		case 0x0002: case 0x0007: /* BIFF2 */
			break;
		default: if(length > 6) throw new Error("Unexpected BIFF Ver " + o.BIFFVer);
	}

	blob.read_shift(length);
	return o;
}
function write_BOF(wb/*:Workbook*/, t/*:number*/, o) {
	var h = 0x0600, w = 16;
	switch(o.bookType) {
		case 'biff8': break;
		case 'biff5': h = 0x0500; w = 8; break;
		case 'biff4': h = 0x0004; w = 6; break;
		case 'biff3': h = 0x0003; w = 6; break;
		case 'biff2': h = 0x0002; w = 4; break;
		case 'xla': break;
		default: throw new Error("unsupported BIFF version");
	}
	var out = new_buf(w);
	out.write_shift(2, h);
	out.write_shift(2, t);
	if(w > 4) out.write_shift(2, 0x7262);
	if(w > 6) out.write_shift(2, 0x07CD);
	if(w > 8) {
		out.write_shift(2, 0xC009);
		out.write_shift(2, 0x0001);
		out.write_shift(2, 0x0706);
		out.write_shift(2, 0x0000);
	}
	return out;
}


/* [MS-XLS] 2.4.146 */
function parse_InterfaceHdr(blob, length) {
	if(length === 0) return 0x04b0;
	if((blob.read_shift(2))!==0x04b0){/* empty */}
	return 0x04b0;
}


/* [MS-XLS] 2.4.349 */
function parse_WriteAccess(blob, length, opts) {
	if(opts.enc) { blob.l += length; return ""; }
	var l = blob.l;
	// TODO: make sure XLUnicodeString doesnt overrun
	var UserName = parse_XLUnicodeString2(blob, 0, opts);
	blob.read_shift(length + l - blob.l);
	return UserName;
}
function write_WriteAccess(s/*:string*/, opts) {
	var b8 = !opts || opts.biff == 8;
	var o = new_buf(b8 ? 112 : 54);
	o.write_shift(opts.biff == 8 ? 2 : 1, 7);
	if(b8) o.write_shift(1, 0);
	o.write_shift(4, 0x33336853);
	o.write_shift(4, (0x00534A74 | (b8 ? 0 : 0x20000000)));
	while(o.l < o.length) o.write_shift(1, (b8 ? 0 : 32));
	return o;
}

/* [MS-XLS] 2.4.351 */
function parse_WsBool(blob, length, opts) {
	var flags = opts && opts.biff == 8 || length == 2 ? blob.read_shift(2) : (blob.l += length, 0);
	return { fDialog: flags & 0x10, fBelow: flags & 0x40, fRight: flags & 0x80 };
}

/* [MS-XLS] 2.4.28 */
function parse_BoundSheet8(blob, length, opts) {
	var pos = blob.read_shift(4);
	var hidden = blob.read_shift(1) & 0x03;
	var dt = blob.read_shift(1);
	switch(dt) {
		case 0: dt = 'Worksheet'; break;
		case 1: dt = 'Macrosheet'; break;
		case 2: dt = 'Chartsheet'; break;
		case 6: dt = 'VBAModule'; break;
	}
	var name = parse_ShortXLUnicodeString(blob, 0, opts);
	if(name.length === 0) name = "Sheet1";
	return { pos:pos, hs:hidden, dt:dt, name:name };
}
function write_BoundSheet8(data, opts) {
	var w = (!opts || opts.biff >= 8 ? 2 : 1);
	var o = new_buf(8 + w * data.name.length);
	o.write_shift(4, data.pos);
	o.write_shift(1, data.hs || 0);
	o.write_shift(1, data.dt);
	o.write_shift(1, data.name.length);
	if(opts.biff >= 8) o.write_shift(1, 1);
	o.write_shift(w * data.name.length, data.name, opts.biff < 8 ? 'sbcs' : 'utf16le');
	var out = o.slice(0, o.l);
	out.l = o.l; return out;
}

/* [MS-XLS] 2.4.265 TODO */
function parse_SST(blob, length)/*:SST*/ {
	var end = blob.l + length;
	var cnt = blob.read_shift(4);
	var ucnt = blob.read_shift(4);
	var strs/*:SST*/ = ([]/*:any*/);
	for(var i = 0; i != ucnt && blob.l < end; ++i) {
		strs.push(parse_XLUnicodeRichExtendedString(blob));
	}
	strs.Count = cnt; strs.Unique = ucnt;
	return strs;
}
function write_SST(sst, opts) {
	var header = new_buf(8);
	header.write_shift(4, sst.Count);
	header.write_shift(4, sst.Unique);
	var strs = [];
	for(var j = 0; j < sst.length; ++j) strs[j] = write_XLUnicodeRichExtendedString(sst[j], opts);
	var o = bconcat([header].concat(strs));
	/*::(*/o/*:: :any)*/.parts = [header.length].concat(strs.map(function(str) { return str.length; }));
	return o;
}

/* [MS-XLS] 2.4.107 */
function parse_ExtSST(blob, length) {
	var extsst = {};
	extsst.dsst = blob.read_shift(2);
	blob.l += length-2;
	return extsst;
}


/* [MS-XLS] 2.4.221 TODO: check BIFF2-4 */
function parse_Row(blob) {
	var z = ({}/*:any*/);
	z.r = blob.read_shift(2);
	z.c = blob.read_shift(2);
	z.cnt = blob.read_shift(2) - z.c;
	var miyRw = blob.read_shift(2);
	blob.l += 4; // reserved(2), unused(2)
	var flags = blob.read_shift(1); // various flags
	blob.l += 3; // reserved(8), ixfe(12), flags(4)
	if(flags & 0x07) z.level = flags & 0x07;
	// collapsed: flags & 0x10
	if(flags & 0x20) z.hidden = true;
	if(flags & 0x40) z.hpt = miyRw / 20;
	return z;
}


/* [MS-XLS] 2.4.125 */
function parse_ForceFullCalculation(blob) {
	var header = parse_frtHeader(blob);
	if(header.type != 0x08A3) throw new Error("Invalid Future Record " + header.type);
	var fullcalc = blob.read_shift(4);
	return fullcalc !== 0x0;
}





/* [MS-XLS] 2.4.215 rt */
function parse_RecalcId(blob) {
	blob.read_shift(2);
	return blob.read_shift(4);
}

/* [MS-XLS] 2.4.87 */
function parse_DefaultRowHeight(blob, length, opts) {
	var f = 0;
	if(!(opts && opts.biff == 2)) {
		f = blob.read_shift(2);
	}
	var miyRw = blob.read_shift(2);
	if((opts && opts.biff == 2)) {
		f = 1 - (miyRw >> 15); miyRw &= 0x7fff;
	}
	var fl = {Unsynced:f&1,DyZero:(f&2)>>1,ExAsc:(f&4)>>2,ExDsc:(f&8)>>3};
	return [fl, miyRw];
}

/* [MS-XLS] 2.4.345 TODO */
function parse_Window1(blob) {
	var xWn = blob.read_shift(2), yWn = blob.read_shift(2), dxWn = blob.read_shift(2), dyWn = blob.read_shift(2);
	var flags = blob.read_shift(2), iTabCur = blob.read_shift(2), iTabFirst = blob.read_shift(2);
	var ctabSel = blob.read_shift(2), wTabRatio = blob.read_shift(2);
	return { Pos: [xWn, yWn], Dim: [dxWn, dyWn], Flags: flags, CurTab: iTabCur,
		FirstTab: iTabFirst, Selected: ctabSel, TabRatio: wTabRatio };
}
function write_Window1(/*::opts*/) {
	var o = new_buf(18);
	o.write_shift(2, 0);
	o.write_shift(2, 0);
	o.write_shift(2, 0x7260);
	o.write_shift(2, 0x44c0);
	o.write_shift(2, 0x38);
	o.write_shift(2, 0);
	o.write_shift(2, 0);
	o.write_shift(2, 1);
	o.write_shift(2, 0x01f4);
	return o;
}
/* [MS-XLS] 2.4.346 TODO */
function parse_Window2(blob, length, opts) {
	if(opts && opts.biff >= 2 && opts.biff < 5) return {};
	var f = blob.read_shift(2);
	return { RTL: f & 0x40 };
}
function write_Window2(view) {
	var o = new_buf(18), f = 0x6b6;
	if(view && view.RTL) f |= 0x40;
	o.write_shift(2, f);
	o.write_shift(4, 0);
	o.write_shift(4, 64);
	o.write_shift(4, 0);
	o.write_shift(4, 0);
	return o;
}

/* [MS-XLS] 2.4.189 TODO */
function parse_Pane(/*blob, length, opts*/) {
}

/* [MS-XLS] 2.4.122 TODO */
function parse_Font(blob, length, opts) {
	var o/*:any*/ = {
		dyHeight: blob.read_shift(2),
		fl: blob.read_shift(2)
	};
	switch((opts && opts.biff) || 8) {
		case 2: break;
		case 3: case 4: blob.l += 2; break;
		default: blob.l += 10; break;
	}
	o.name = parse_ShortXLUnicodeString(blob, 0, opts);
	return o;
}
function write_Font(data, opts) {
	var name = data.name || "Arial";
	var b5 = (opts && (opts.biff == 5)), w = (b5 ? (15 + name.length) : (16 + 2 * name.length));
	var o = new_buf(w);
	o.write_shift(2, (data.sz || 12) * 20);
	o.write_shift(4, 0);
	o.write_shift(2, 400);
	o.write_shift(4, 0);
	o.write_shift(2, 0);
	o.write_shift(1, name.length);
	if(!b5) o.write_shift(1, 1);
	o.write_shift((b5 ? 1 : 2) * name.length, name, (b5 ? "sbcs" : "utf16le"));
	return o;
}

/* [MS-XLS] 2.4.149 */
function parse_LabelSst(blob) {
	var cell = parse_XLSCell(blob);
	cell.isst = blob.read_shift(4);
	return cell;
}
function write_LabelSst(R/*:number*/, C/*:number*/, v/*:number*/, os/*:number*/ /*::, opts*/) {
	var o = new_buf(10);
	write_XLSCell(R, C, os, o);
	o.write_shift(4, v);
	return o;
}

/* [MS-XLS] 2.4.148 */
function parse_Label(blob, length, opts) {
	if(opts.biffguess && opts.biff == 2) opts.biff = 5;
	var target = blob.l + length;
	var cell = parse_XLSCell(blob, 6);
	if(opts.biff == 2) blob.l++;
	var str = parse_XLUnicodeString(blob, target - blob.l, opts);
	cell.val = str;
	return cell;
}
function write_Label(R/*:number*/, C/*:number*/, v/*:string*/, os/*:number*/, opts) {
	var b8 = !opts || opts.biff == 8;
	var o = new_buf(6 + 2 + (+b8) + (1 + b8) * v.length);
	write_XLSCell(R, C, os, o);
	o.write_shift(2, v.length);
	if(b8) o.write_shift(1, 1);
	o.write_shift((1 + b8) * v.length, v, b8 ? 'utf16le' : 'sbcs');
	return o;
}


/* [MS-XLS] 2.4.126 Number Formats */
function parse_Format(blob, length, opts) {
	var numFmtId = blob.read_shift(2);
	var fmtstr = parse_XLUnicodeString2(blob, 0, opts);
	return [numFmtId, fmtstr];
}
function write_Format(i/*:number*/, f/*:string*/, opts, o) {
	var b5 = (opts && (opts.biff == 5));
	if(!o) o = new_buf(b5 ? (3 + f.length) : (5 + 2 * f.length));
	o.write_shift(2, i);
	o.write_shift((b5 ? 1 : 2), f.length);
	if(!b5) o.write_shift(1, 1);
	o.write_shift((b5 ? 1 : 2) * f.length, f, (b5 ? 'sbcs' : 'utf16le'));
	var out = (o.length > o.l) ? o.slice(0, o.l) : o;
	if(out.l == null) out.l = out.length;
	return out;
}
var parse_BIFF2Format = parse_XLUnicodeString2;

/* [MS-XLS] 2.4.90 */
function parse_Dimensions(blob, length, opts) {
	var end = blob.l + length;
	var w = opts.biff == 8 || !opts.biff ? 4 : 2;
	var r = blob.read_shift(w), R = blob.read_shift(w);
	var c = blob.read_shift(2), C = blob.read_shift(2);
	blob.l = end;
	return {s: {r:r, c:c}, e: {r:R, c:C}};
}
function write_Dimensions(range, opts) {
	var w = opts.biff == 8 || !opts.biff ? 4 : 2;
	var o = new_buf(2*w + 6);
	o.write_shift(w, range.s.r);
	o.write_shift(w, range.e.r + 1);
	o.write_shift(2, range.s.c);
	o.write_shift(2, range.e.c + 1);
	o.write_shift(2, 0);
	return o;
}

/* [MS-XLS] 2.4.220 */
function parse_RK(blob) {
	var rw = blob.read_shift(2), col = blob.read_shift(2);
	var rkrec = parse_RkRec(blob);
	return {r:rw, c:col, ixfe:rkrec[0], rknum:rkrec[1]};
}

/* [MS-XLS] 2.4.175 */
function parse_MulRk(blob, length) {
	var target = blob.l + length - 2;
	var rw = blob.read_shift(2), col = blob.read_shift(2);
	var rkrecs = [];
	while(blob.l < target) rkrecs.push(parse_RkRec(blob));
	if(blob.l !== target) throw new Error("MulRK read error");
	var lastcol = blob.read_shift(2);
	if(rkrecs.length != lastcol - col + 1) throw new Error("MulRK length mismatch");
	return {r:rw, c:col, C:lastcol, rkrec:rkrecs};
}
/* [MS-XLS] 2.4.174 */
function parse_MulBlank(blob, length) {
	var target = blob.l + length - 2;
	var rw = blob.read_shift(2), col = blob.read_shift(2);
	var ixfes = [];
	while(blob.l < target) ixfes.push(blob.read_shift(2));
	if(blob.l !== target) throw new Error("MulBlank read error");
	var lastcol = blob.read_shift(2);
	if(ixfes.length != lastcol - col + 1) throw new Error("MulBlank length mismatch");
	return {r:rw, c:col, C:lastcol, ixfe:ixfes};
}

/* [MS-XLS] 2.5.20 2.5.249 TODO: interpret values here */
function parse_CellStyleXF(blob, length, style, opts) {
	var o = {};
	var a = blob.read_shift(4), b = blob.read_shift(4);
	var c = blob.read_shift(4), d = blob.read_shift(2);
	o.patternType = XLSFillPattern[c >> 26];

	if(!opts.cellStyles) return o;
	o.alc = a & 0x07;
	o.fWrap = (a >> 3) & 0x01;
	o.alcV = (a >> 4) & 0x07;
	o.fJustLast = (a >> 7) & 0x01;
	o.trot = (a >> 8) & 0xFF;
	o.cIndent = (a >> 16) & 0x0F;
	o.fShrinkToFit = (a >> 20) & 0x01;
	o.iReadOrder = (a >> 22) & 0x02;
	o.fAtrNum = (a >> 26) & 0x01;
	o.fAtrFnt = (a >> 27) & 0x01;
	o.fAtrAlc = (a >> 28) & 0x01;
	o.fAtrBdr = (a >> 29) & 0x01;
	o.fAtrPat = (a >> 30) & 0x01;
	o.fAtrProt = (a >> 31) & 0x01;

	o.dgLeft = b & 0x0F;
	o.dgRight = (b >> 4) & 0x0F;
	o.dgTop = (b >> 8) & 0x0F;
	o.dgBottom = (b >> 12) & 0x0F;
	o.icvLeft = (b >> 16) & 0x7F;
	o.icvRight = (b >> 23) & 0x7F;
	o.grbitDiag = (b >> 30) & 0x03;

	o.icvTop = c & 0x7F;
	o.icvBottom = (c >> 7) & 0x7F;
	o.icvDiag = (c >> 14) & 0x7F;
	o.dgDiag = (c >> 21) & 0x0F;

	o.icvFore = d & 0x7F;
	o.icvBack = (d >> 7) & 0x7F;
	o.fsxButton = (d >> 14) & 0x01;
	return o;
}
//function parse_CellXF(blob, length, opts) {return parse_CellStyleXF(blob,length,0, opts);}
//function parse_StyleXF(blob, length, opts) {return parse_CellStyleXF(blob,length,1, opts);}

/* [MS-XLS] 2.4.353 TODO: actually do this right */
function parse_XF(blob, length, opts) {
	var o = {};
	o.ifnt = blob.read_shift(2); o.numFmtId = blob.read_shift(2); o.flags = blob.read_shift(2);
	o.fStyle = (o.flags >> 2) & 0x01;
	length -= 6;
	o.data = parse_CellStyleXF(blob, length, o.fStyle, opts);
	return o;
}
function write_XF(data, ixfeP, opts, o) {
	var b5 = (opts && (opts.biff == 5));
	if(!o) o = new_buf(b5 ? 16 : 20);
	o.write_shift(2, 0);
	if(data.style) {
		o.write_shift(2, (data.numFmtId||0));
		o.write_shift(2, 0xFFF4);
	} else {
		o.write_shift(2, (data.numFmtId||0));
		o.write_shift(2, (ixfeP<<4));
	}
	var f = 0;
	if(data.numFmtId > 0 && b5) f |= 0x0400;
	o.write_shift(4, f);
	o.write_shift(4, 0);
	if(!b5) o.write_shift(4, 0);
	o.write_shift(2, 0);
	return o;
}

/* [MS-XLS] 2.4.134 */
function parse_Guts(blob) {
	blob.l += 4;
	var out = [blob.read_shift(2), blob.read_shift(2)];
	if(out[0] !== 0) out[0]--;
	if(out[1] !== 0) out[1]--;
	if(out[0] > 7 || out[1] > 7) throw new Error("Bad Gutters: " + out.join("|"));
	return out;
}
function write_Guts(guts/*:Array<number>*/) {
	var o = new_buf(8);
	o.write_shift(4, 0);
	o.write_shift(2, guts[0] ? guts[0] + 1 : 0);
	o.write_shift(2, guts[1] ? guts[1] + 1 : 0);
	return o;
}

/* [MS-XLS] 2.4.24 */
function parse_BoolErr(blob, length, opts) {
	var cell = parse_XLSCell(blob, 6);
	if(opts.biff == 2 || length == 9) ++blob.l;
	var val = parse_Bes(blob, 2);
	cell.val = val;
	cell.t = (val === true || val === false) ? 'b' : 'e';
	return cell;
}
function write_BoolErr(R/*:number*/, C/*:number*/, v, os/*:number*/, opts, t/*:string*/) {
	var o = new_buf(8);
	write_XLSCell(R, C, os, o);
	write_Bes(v, t, o);
	return o;
}

/* [MS-XLS] 2.4.180 Number */
function parse_Number(blob, length, opts) {
	if(opts.biffguess && opts.biff == 2) opts.biff = 5;
	var cell = parse_XLSCell(blob, 6);
	var xnum = parse_Xnum(blob, 8);
	cell.val = xnum;
	return cell;
}
function write_Number(R/*:number*/, C/*:number*/, v, os/*:: :number, opts*/) {
	var o = new_buf(14);
	write_XLSCell(R, C, os, o);
	write_Xnum(v, o);
	return o;
}

var parse_XLHeaderFooter = parse_OptXLUnicodeString; // TODO: parse 2.4.136

/* [MS-XLS] 2.4.271 */
function parse_SupBook(blob, length, opts) {
	var end = blob.l + length;
	var ctab = blob.read_shift(2);
	var cch = blob.read_shift(2);
	opts.sbcch = cch;
	if(cch == 0x0401 || cch == 0x3A01) return [cch, ctab];
	if(cch < 0x01 || cch >0xff) throw new Error("Unexpected SupBook type: "+cch);
	var virtPath = parse_XLUnicodeStringNoCch(blob, cch);
	/* TODO: 2.5.277 Virtual Path */
	var rgst = [];
	while(end > blob.l) rgst.push(parse_XLUnicodeString(blob));
	return [cch, ctab, virtPath, rgst];
}

/* [MS-XLS] 2.4.105 TODO */
function parse_ExternName(blob, length, opts) {
	var flags = blob.read_shift(2);
	var body;
	var o = ({
		fBuiltIn: flags & 0x01,
		fWantAdvise: (flags >>> 1) & 0x01,
		fWantPict: (flags >>> 2) & 0x01,
		fOle: (flags >>> 3) & 0x01,
		fOleLink: (flags >>> 4) & 0x01,
		cf: (flags >>> 5) & 0x3FF,
		fIcon: flags >>> 15 & 0x01
	}/*:any*/);
	if(opts.sbcch === 0x3A01) body = parse_AddinUdf(blob, length-2, opts);
	//else throw new Error("unsupported SupBook cch: " + opts.sbcch);
	o.body = body || blob.read_shift(length-2);
	if(typeof body === "string") o.Name = body;
	return o;
}

/* [MS-XLS] 2.4.150 TODO */
var XLSLblBuiltIn = [
	"_xlnm.Consolidate_Area",
	"_xlnm.Auto_Open",
	"_xlnm.Auto_Close",
	"_xlnm.Extract",
	"_xlnm.Database",
	"_xlnm.Criteria",
	"_xlnm.Print_Area",
	"_xlnm.Print_Titles",
	"_xlnm.Recorder",
	"_xlnm.Data_Form",
	"_xlnm.Auto_Activate",
	"_xlnm.Auto_Deactivate",
	"_xlnm.Sheet_Title",
	"_xlnm._FilterDatabase"
];
function parse_Lbl(blob, length, opts) {
	var target = blob.l + length;
	var flags = blob.read_shift(2);
	var chKey = blob.read_shift(1);
	var cch = blob.read_shift(1);
	var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
	var itab = 0;
	if(!opts || opts.biff >= 5) {
		if(opts.biff != 5) blob.l += 2;
		itab = blob.read_shift(2);
		if(opts.biff == 5) blob.l += 2;
		blob.l += 4;
	}
	var name = parse_XLUnicodeStringNoCch(blob, cch, opts);
	if(flags & 0x20) name = XLSLblBuiltIn[name.charCodeAt(0)];
	var npflen = target - blob.l; if(opts && opts.biff == 2) --npflen;
	/*jshint -W018 */
	var rgce = (target == blob.l || cce === 0 || !(npflen > 0)) ? [] : parse_NameParsedFormula(blob, npflen, opts, cce);
	/*jshint +W018 */
	return {
		chKey: chKey,
		Name: name,
		itab: itab,
		rgce: rgce
	};
}

/* [MS-XLS] 2.4.106 TODO: verify filename encoding */
function parse_ExternSheet(blob, length, opts) {
	if(opts.biff < 8) return parse_BIFF5ExternSheet(blob, length, opts);
	var o = [], target = blob.l + length, len = blob.read_shift(opts.biff > 8 ? 4 : 2);
	while(len-- !== 0) o.push(parse_XTI(blob, opts.biff > 8 ? 12 : 6, opts));
		// [iSupBook, itabFirst, itabLast];
	if(blob.l != target) throw new Error("Bad ExternSheet: " + blob.l + " != " + target);
	return o;
}
function parse_BIFF5ExternSheet(blob, length, opts) {
	if(blob[blob.l + 1] == 0x03) blob[blob.l]++;
	var o = parse_ShortXLUnicodeString(blob, length, opts);
	return o.charCodeAt(0) == 0x03 ? o.slice(1) : o;
}

/* [MS-XLS] 2.4.176 TODO: check older biff */
function parse_NameCmt(blob, length, opts) {
	if(opts.biff < 8) { blob.l += length; return; }
	var cchName = blob.read_shift(2);
	var cchComment = blob.read_shift(2);
	var name = parse_XLUnicodeStringNoCch(blob, cchName, opts);
	var comment = parse_XLUnicodeStringNoCch(blob, cchComment, opts);
	return [name, comment];
}

/* [MS-XLS] 2.4.260 */
function parse_ShrFmla(blob, length, opts) {
	var ref = parse_RefU(blob, 6);
	blob.l++;
	var cUse = blob.read_shift(1);
	length -= 8;
	return [parse_SharedParsedFormula(blob, length, opts), cUse, ref];
}

/* [MS-XLS] 2.4.4 TODO */
function parse_Array(blob, length, opts) {
	var ref = parse_Ref(blob, 6);
	/* TODO: fAlwaysCalc */
	switch(opts.biff) {
		case 2: blob.l ++; length -= 7; break;
		case 3: case 4: blob.l += 2; length -= 8; break;
		default: blob.l += 6; length -= 12;
	}
	return [ref, parse_ArrayParsedFormula(blob, length, opts, ref)];
}

/* [MS-XLS] 2.4.173 */
function parse_MTRSettings(blob) {
	var fMTREnabled = blob.read_shift(4) !== 0x00;
	var fUserSetThreadCount = blob.read_shift(4) !== 0x00;
	var cUserThreadCount = blob.read_shift(4);
	return [fMTREnabled, fUserSetThreadCount, cUserThreadCount];
}

/* [MS-XLS] 2.5.186 TODO: BIFF5 */
function parse_NoteSh(blob, length, opts) {
	if(opts.biff < 8) return;
	var row = blob.read_shift(2), col = blob.read_shift(2);
	var flags = blob.read_shift(2), idObj = blob.read_shift(2);
	var stAuthor = parse_XLUnicodeString2(blob, 0, opts);
	if(opts.biff < 8) blob.read_shift(1);
	return [{r:row,c:col}, stAuthor, idObj, flags];
}

/* [MS-XLS] 2.4.179 */
function parse_Note(blob, length, opts) {
	/* TODO: Support revisions */
	return parse_NoteSh(blob, length, opts);
}

/* [MS-XLS] 2.4.168 */
function parse_MergeCells(blob, length)/*:Array<Range>*/ {
	var merges/*:Array<Range>*/ = [];
	var cmcs = blob.read_shift(2);
	while (cmcs--) merges.push(parse_Ref8U(blob,length));
	return merges;
}
function write_MergeCells(merges/*:Array<Range>*/) {
	var o = new_buf(2 + merges.length * 8);
	o.write_shift(2, merges.length);
	for(var i = 0; i < merges.length; ++i) write_Ref8U(merges[i], o);
	return o;
}

/* [MS-XLS] 2.4.181 TODO: parse all the things! */
function parse_Obj(blob, length, opts) {
	if(opts && opts.biff < 8) return parse_BIFF5Obj(blob, length, opts);
	var cmo = parse_FtCmo(blob, 22); // id, ot, flags
	var fts = parse_FtArray(blob, length-22, cmo[1]);
	return { cmo: cmo, ft:fts };
}
/* from older spec */
var parse_BIFF5OT = {
0x08: function(blob, length) {
	var tgt = blob.l + length;
	blob.l += 10; // todo
	var cf = blob.read_shift(2);
	blob.l += 4;
	blob.l += 2; //var cbPictFmla = blob.read_shift(2);
	blob.l += 2;
	blob.l += 2; //var grbit = blob.read_shift(2);
	blob.l += 4;
	var cchName = blob.read_shift(1);
	blob.l += cchName; // TODO: stName
	blob.l = tgt; // TODO: fmla
	return { fmt:cf };
}
};

function parse_BIFF5Obj(blob, length, opts) {
	blob.l += 4; //var cnt = blob.read_shift(4);
	var ot = blob.read_shift(2);
	var id = blob.read_shift(2);
	var grbit = blob.read_shift(2);
	blob.l += 2; //var colL = blob.read_shift(2);
	blob.l += 2; //var dxL = blob.read_shift(2);
	blob.l += 2; //var rwT = blob.read_shift(2);
	blob.l += 2; //var dyT = blob.read_shift(2);
	blob.l += 2; //var colR = blob.read_shift(2);
	blob.l += 2; //var dxR = blob.read_shift(2);
	blob.l += 2; //var rwB = blob.read_shift(2);
	blob.l += 2; //var dyB = blob.read_shift(2);
	blob.l += 2; //var cbMacro = blob.read_shift(2);
	blob.l += 6;
	length -= 36;
	var fts = [];
	fts.push((parse_BIFF5OT[ot]||parsenoop)(blob, length, opts));
	return { cmo: [id, ot, grbit], ft:fts };
}

/* [MS-XLS] 2.4.329 TODO: parse properly */
function parse_TxO(blob, length, opts) {
	var s = blob.l;
	var texts = "";
try {
	blob.l += 4;
	var ot = (opts.lastobj||{cmo:[0,0]}).cmo[1];
	var controlInfo; // eslint-disable-line no-unused-vars
	if([0,5,7,11,12,14].indexOf(ot) == -1) blob.l += 6;
	else controlInfo = parse_ControlInfo(blob, 6, opts); // eslint-disable-line no-unused-vars
	var cchText = blob.read_shift(2);
	/*var cbRuns = */blob.read_shift(2);
	/*var ifntEmpty = */parseuint16(blob, 2);
	var len = blob.read_shift(2);
	blob.l += len;
	//var fmla = parse_ObjFmla(blob, s + length - blob.l);

	for(var i = 1; i < blob.lens.length-1; ++i) {
		if(blob.l-s != blob.lens[i]) throw new Error("TxO: bad continue record");
		var hdr = blob[blob.l];
		var t = parse_XLUnicodeStringNoCch(blob, blob.lens[i+1]-blob.lens[i]-1);
		texts += t;
		if(texts.length >= (hdr ? cchText : 2*cchText)) break;
	}
	if(texts.length !== cchText && texts.length !== cchText*2) {
		throw new Error("cchText: " + cchText + " != " + texts.length);
	}

	blob.l = s + length;
	/* [MS-XLS] 2.5.272 TxORuns */
//	var rgTxoRuns = [];
//	for(var j = 0; j != cbRuns/8-1; ++j) blob.l += 8;
//	var cchText2 = blob.read_shift(2);
//	if(cchText2 !== cchText) throw new Error("TxOLastRun mismatch: " + cchText2 + " " + cchText);
//	blob.l += 6;
//	if(s + length != blob.l) throw new Error("TxO " + (s + length) + ", at " + blob.l);
	return { t: texts };
} catch(e) { blob.l = s + length; return { t: texts }; }
}

/* [MS-XLS] 2.4.140 */
function parse_HLink(blob, length) {
	var ref = parse_Ref8U(blob, 8);
	blob.l += 16; /* CLSID */
	var hlink = parse_Hyperlink(blob, length-24);
	return [ref, hlink];
}
function write_HLink(hl) {
	var O = new_buf(24);
	var ref = decode_cell(hl[0]);
	O.write_shift(2, ref.r); O.write_shift(2, ref.r);
	O.write_shift(2, ref.c); O.write_shift(2, ref.c);
	var clsid = "d0 c9 ea 79 f9 ba ce 11 8c 82 00 aa 00 4b a9 0b".split(" ");
	for(var i = 0; i < 16; ++i) O.write_shift(1, parseInt(clsid[i], 16));
	return bconcat([O, write_Hyperlink(hl[1])]);
}


/* [MS-XLS] 2.4.141 */
function parse_HLinkTooltip(blob, length) {
	blob.read_shift(2);
	var ref = parse_Ref8U(blob, 8);
	var wzTooltip = blob.read_shift((length-10)/2, 'dbcs-cont');
	wzTooltip = wzTooltip.replace(chr0,"");
	return [ref, wzTooltip];
}
function write_HLinkTooltip(hl) {
	var TT = hl[1].Tooltip;
	var O = new_buf(10 + 2 * (TT.length + 1));
	O.write_shift(2, 0x0800);
	var ref = decode_cell(hl[0]);
	O.write_shift(2, ref.r); O.write_shift(2, ref.r);
	O.write_shift(2, ref.c); O.write_shift(2, ref.c);
	for(var i = 0; i < TT.length; ++i) O.write_shift(2, TT.charCodeAt(i));
	O.write_shift(2, 0);
	return O;
}

/* [MS-XLS] 2.4.63 */
function parse_Country(blob)/*:[string|number, string|number]*/ {
	var o = [0,0], d;
	d = blob.read_shift(2); o[0] = CountryEnum[d] || d;
	d = blob.read_shift(2); o[1] = CountryEnum[d] || d;
	return o;
}
function write_Country(o) {
	if(!o) o = new_buf(4);
	o.write_shift(2, 0x01);
	o.write_shift(2, 0x01);
	return o;
}

/* [MS-XLS] 2.4.50 ClrtClient */
function parse_ClrtClient(blob) {
	var ccv = blob.read_shift(2);
	var o = [];
	while(ccv-->0) o.push(parse_LongRGB(blob, 8));
	return o;
}

/* [MS-XLS] 2.4.188 */
function parse_Palette(blob) {
	var ccv = blob.read_shift(2);
	var o = [];
	while(ccv-->0) o.push(parse_LongRGB(blob, 8));
	return o;
}

/* [MS-XLS] 2.4.354 */
function parse_XFCRC(blob) {
	blob.l += 2;
	var o = {cxfs:0, crc:0};
	o.cxfs = blob.read_shift(2);
	o.crc = blob.read_shift(4);
	return o;
}

/* [MS-XLS] 2.4.53 TODO: parse flags */
/* [MS-XLSB] 2.4.323 TODO: parse flags */
function parse_ColInfo(blob, length, opts) {
	if(!opts.cellStyles) return parsenoop(blob, length);
	var w = opts && opts.biff >= 12 ? 4 : 2;
	var colFirst = blob.read_shift(w);
	var colLast = blob.read_shift(w);
	var coldx = blob.read_shift(w);
	var ixfe = blob.read_shift(w);
	var flags = blob.read_shift(2);
	if(w == 2) blob.l += 2;
	var o = ({s:colFirst, e:colLast, w:coldx, ixfe:ixfe, flags:flags}/*:any*/);
	if(opts.biff >= 5 || !opts.biff) o.level = (flags >> 8) & 0x7;
	return o;
}
function write_ColInfo(col, idx) {
	var o = new_buf(12);
	o.write_shift(2, idx);
	o.write_shift(2, idx);
	o.write_shift(2, col.width * 256);
	o.write_shift(2, 0);
	var f = 0;
	if(col.hidden) f |= 1;
	o.write_shift(1, f);
	f = col.level || 0;
	o.write_shift(1, f);
	o.write_shift(2, 0);
	return o;
}

/* [MS-XLS] 2.4.257 */
function parse_Setup(blob, length) {
	var o = {};
	if(length < 32) return o;
	blob.l += 16;
	o.header = parse_Xnum(blob, 8);
	o.footer = parse_Xnum(blob, 8);
	blob.l += 2;
	return o;
}

/* [MS-XLS] 2.4.261 */
function parse_ShtProps(blob, length, opts) {
	var def = {area:false};
	if(opts.biff != 5) { blob.l += length; return def; }
	var d = blob.read_shift(1); blob.l += 3;
	if((d & 0x10)) def.area = true;
	return def;
}

/* [MS-XLS] 2.4.241 */
function write_RRTabId(n/*:number*/) {
	var out = new_buf(2 * n);
	for(var i = 0; i < n; ++i) out.write_shift(2, i+1);
	return out;
}

var parse_Blank = parse_XLSCell; /* [MS-XLS] 2.4.20 Just the cell */
var parse_Scl = parseuint16a; /* [MS-XLS] 2.4.247 num, den */
var parse_String = parse_XLUnicodeString; /* [MS-XLS] 2.4.268 */

/* --- Specific to versions before BIFF8 --- */
function parse_ImData(blob) {
	var cf = blob.read_shift(2);
	var env = blob.read_shift(2);
	var lcb = blob.read_shift(4);
	var o = {fmt:cf, env:env, len:lcb, data:blob.slice(blob.l,blob.l+lcb)};
	blob.l += lcb;
	return o;
}

/* BIFF2_??? where ??? is the name from [XLS] */
function parse_BIFF2STR(blob, length, opts) {
	if(opts.biffguess && opts.biff == 5) opts.biff = 2;
	var cell = parse_XLSCell(blob, 6);
	++blob.l;
	var str = parse_XLUnicodeString2(blob, length-7, opts);
	cell.t = 'str';
	cell.val = str;
	return cell;
}

function parse_BIFF2NUM(blob/*::, length*/) {
	var cell = parse_XLSCell(blob, 6);
	++blob.l;
	var num = parse_Xnum(blob, 8);
	cell.t = 'n';
	cell.val = num;
	return cell;
}
function write_BIFF2NUM(r/*:number*/, c/*:number*/, val/*:number*/) {
	var out = new_buf(15);
	write_BIFF2Cell(out, r, c);
	out.write_shift(8, val, 'f');
	return out;
}

function parse_BIFF2INT(blob) {
	var cell = parse_XLSCell(blob, 6);
	++blob.l;
	var num = blob.read_shift(2);
	cell.t = 'n';
	cell.val = num;
	return cell;
}
function write_BIFF2INT(r/*:number*/, c/*:number*/, val/*:number*/) {
	var out = new_buf(9);
	write_BIFF2Cell(out, r, c);
	out.write_shift(2, val);
	return out;
}

function parse_BIFF2STRING(blob) {
	var cch = blob.read_shift(1);
	if(cch === 0) { blob.l++; return ""; }
	return blob.read_shift(cch, 'sbcs-cont');
}

/* TODO: convert to BIFF8 font struct */
function parse_BIFF2FONTXTRA(blob, length) {
	blob.l += 6; // unknown
	blob.l += 2; // font weight "bls"
	blob.l += 1; // charset
	blob.l += 3; // unknown
	blob.l += 1; // font family
	blob.l += length - 13;
}

/* TODO: parse rich text runs */
function parse_RString(blob, length, opts) {
	var end = blob.l + length;
	var cell = parse_XLSCell(blob, 6);
	var cch = blob.read_shift(2);
	var str = parse_XLUnicodeStringNoCch(blob, cch, opts);
	blob.l = end;
	cell.t = 'str';
	cell.val = str;
	return cell;
}
/* from js-harb (C) 2014-present  SheetJS */
var DBF_SUPPORTED_VERSIONS = [0x02, 0x03, 0x30, 0x31, 0x83, 0x8B, 0x8C, 0xF5];
var DBF = /*#__PURE__*/(function() {
var dbf_codepage_map = {
	/* Code Pages Supported by Visual FoxPro */
	/*::[*/0x01/*::]*/:   437,           /*::[*/0x02/*::]*/:   850,
	/*::[*/0x03/*::]*/:  1252,           /*::[*/0x04/*::]*/: 10000,
	/*::[*/0x64/*::]*/:   852,           /*::[*/0x65/*::]*/:   866,
	/*::[*/0x66/*::]*/:   865,           /*::[*/0x67/*::]*/:   861,
	/*::[*/0x68/*::]*/:   895,           /*::[*/0x69/*::]*/:   620,
	/*::[*/0x6A/*::]*/:   737,           /*::[*/0x6B/*::]*/:   857,
	/*::[*/0x78/*::]*/:   950,           /*::[*/0x79/*::]*/:   949,
	/*::[*/0x7A/*::]*/:   936,           /*::[*/0x7B/*::]*/:   932,
	/*::[*/0x7C/*::]*/:   874,           /*::[*/0x7D/*::]*/:  1255,
	/*::[*/0x7E/*::]*/:  1256,           /*::[*/0x96/*::]*/: 10007,
	/*::[*/0x97/*::]*/: 10029,           /*::[*/0x98/*::]*/: 10006,
	/*::[*/0xC8/*::]*/:  1250,           /*::[*/0xC9/*::]*/:  1251,
	/*::[*/0xCA/*::]*/:  1254,           /*::[*/0xCB/*::]*/:  1253,

	/* shapefile DBF extension */
	/*::[*/0x00/*::]*/: 20127,           /*::[*/0x08/*::]*/:   865,
	/*::[*/0x09/*::]*/:   437,           /*::[*/0x0A/*::]*/:   850,
	/*::[*/0x0B/*::]*/:   437,           /*::[*/0x0D/*::]*/:   437,
	/*::[*/0x0E/*::]*/:   850,           /*::[*/0x0F/*::]*/:   437,
	/*::[*/0x10/*::]*/:   850,           /*::[*/0x11/*::]*/:   437,
	/*::[*/0x12/*::]*/:   850,           /*::[*/0x13/*::]*/:   932,
	/*::[*/0x14/*::]*/:   850,           /*::[*/0x15/*::]*/:   437,
	/*::[*/0x16/*::]*/:   850,           /*::[*/0x17/*::]*/:   865,
	/*::[*/0x18/*::]*/:   437,           /*::[*/0x19/*::]*/:   437,
	/*::[*/0x1A/*::]*/:   850,           /*::[*/0x1B/*::]*/:   437,
	/*::[*/0x1C/*::]*/:   863,           /*::[*/0x1D/*::]*/:   850,
	/*::[*/0x1F/*::]*/:   852,           /*::[*/0x22/*::]*/:   852,
	/*::[*/0x23/*::]*/:   852,           /*::[*/0x24/*::]*/:   860,
	/*::[*/0x25/*::]*/:   850,           /*::[*/0x26/*::]*/:   866,
	/*::[*/0x37/*::]*/:   850,           /*::[*/0x40/*::]*/:   852,
	/*::[*/0x4D/*::]*/:   936,           /*::[*/0x4E/*::]*/:   949,
	/*::[*/0x4F/*::]*/:   950,           /*::[*/0x50/*::]*/:   874,
	/*::[*/0x57/*::]*/:  1252,           /*::[*/0x58/*::]*/:  1252,
	/*::[*/0x59/*::]*/:  1252,           /*::[*/0x6C/*::]*/:   863,
	/*::[*/0x86/*::]*/:   737,           /*::[*/0x87/*::]*/:   852,
	/*::[*/0x88/*::]*/:   857,           /*::[*/0xCC/*::]*/:  1257,

	/*::[*/0xFF/*::]*/: 16969
};
var dbf_reverse_map = evert({
	/*::[*/0x01/*::]*/:   437,           /*::[*/0x02/*::]*/:   850,
	/*::[*/0x03/*::]*/:  1252,           /*::[*/0x04/*::]*/: 10000,
	/*::[*/0x64/*::]*/:   852,           /*::[*/0x65/*::]*/:   866,
	/*::[*/0x66/*::]*/:   865,           /*::[*/0x67/*::]*/:   861,
	/*::[*/0x68/*::]*/:   895,           /*::[*/0x69/*::]*/:   620,
	/*::[*/0x6A/*::]*/:   737,           /*::[*/0x6B/*::]*/:   857,
	/*::[*/0x78/*::]*/:   950,           /*::[*/0x79/*::]*/:   949,
	/*::[*/0x7A/*::]*/:   936,           /*::[*/0x7B/*::]*/:   932,
	/*::[*/0x7C/*::]*/:   874,           /*::[*/0x7D/*::]*/:  1255,
	/*::[*/0x7E/*::]*/:  1256,           /*::[*/0x96/*::]*/: 10007,
	/*::[*/0x97/*::]*/: 10029,           /*::[*/0x98/*::]*/: 10006,
	/*::[*/0xC8/*::]*/:  1250,           /*::[*/0xC9/*::]*/:  1251,
	/*::[*/0xCA/*::]*/:  1254,           /*::[*/0xCB/*::]*/:  1253,
	/*::[*/0x00/*::]*/: 20127
});
/* TODO: find an actual specification */
function dbf_to_aoa(buf, opts)/*:AOA*/ {
	var out/*:AOA*/ = [];
	var d/*:Block*/ = (new_raw_buf(1)/*:any*/);
	switch(opts.type) {
		case 'base64': d = s2a(Base64_decode(buf)); break;
		case 'binary': d = s2a(buf); break;
		case 'buffer':
		case 'array': d = buf; break;
	}
	prep_blob(d, 0);

	/* header */
	var ft = d.read_shift(1);
	var memo = !!(ft & 0x88);
	var vfp = false, l7 = false;
	switch(ft) {
		case 0x02: break; // dBASE II
		case 0x03: break; // dBASE III
		case 0x30: vfp = true; memo = true; break; // VFP
		case 0x31: vfp = true; memo = true; break; // VFP with autoincrement
		// 0x43 dBASE IV SQL table files
		// 0x63 dBASE IV SQL system files
		case 0x83: break; // dBASE III with memo
		case 0x8B: break; // dBASE IV with memo
		case 0x8C: l7 = true; break; // dBASE Level 7 with memo
		// case 0xCB dBASE IV SQL table files with memo
		case 0xF5: break; // FoxPro 2.x with memo
		// case 0xFB FoxBASE
		default: throw new Error("DBF Unsupported Version: " + ft.toString(16));
	}

	var nrow = 0, fpos = 0x0209;
	if(ft == 0x02) nrow = d.read_shift(2);
	d.l += 3; // dBASE II stores DDMMYY date, others use YYMMDD
	if(ft != 0x02) nrow = d.read_shift(4);
	if(nrow > 1048576) nrow = 1e6;

	if(ft != 0x02) fpos = d.read_shift(2); // header length
	var rlen = d.read_shift(2); // record length

	var /*flags = 0,*/ current_cp = opts.codepage || 1252;
	if(ft != 0x02) { // 20 reserved bytes
		d.l+=16;
		/*flags = */d.read_shift(1);
		//if(memo && ((flags & 0x02) === 0)) throw new Error("DBF Flags " + flags.toString(16) + " ft " + ft.toString(16));

		/* codepage present in FoxPro and dBASE Level 7 */
		if(d[d.l] !== 0) current_cp = dbf_codepage_map[d[d.l]];
		d.l+=1;

		d.l+=2;
	}
	if(l7) d.l += 36; // Level 7: 32 byte "Language driver name", 4 byte reserved

/*:: type DBFField = { name:string; len:number; type:string; } */
	var fields/*:Array<DBFField>*/ = [], field/*:DBFField*/ = ({}/*:any*/);
	var hend = Math.min(d.length, (ft == 0x02 ? 0x209 : (fpos - 10 - (vfp ? 264 : 0))));
	var ww = l7 ? 32 : 11;
	while(d.l < hend && d[d.l] != 0x0d) {
		field = ({}/*:any*/);
		field.name = $cptable.utils.decode(current_cp, d.slice(d.l, d.l+ww)).replace(/[\u0000\r\n].*$/g,"");
		d.l += ww;
		field.type = String.fromCharCode(d.read_shift(1));
		if(ft != 0x02 && !l7) field.offset = d.read_shift(4);
		field.len = d.read_shift(1);
		if(ft == 0x02) field.offset = d.read_shift(2);
		field.dec = d.read_shift(1);
		if(field.name.length) fields.push(field);
		if(ft != 0x02) d.l += l7 ? 13 : 14;
		switch(field.type) {
			case 'B': // Double (VFP) / Binary (dBASE L7)
				if((!vfp || field.len != 8) && opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
				break;
			case 'G': // General (FoxPro and dBASE L7)
			case 'P': // Picture (FoxPro and dBASE L7)
				if(opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
				break;
			case '+': // Autoincrement (dBASE L7 only)
			case '0': // _NullFlags (VFP only)
			case '@': // Timestamp (dBASE L7 only)
			case 'C': // Character (dBASE II)
			case 'D': // Date (dBASE III)
			case 'F': // Float (dBASE IV)
			case 'I': // Long (VFP and dBASE L7)
			case 'L': // Logical (dBASE II)
			case 'M': // Memo (dBASE III)
			case 'N': // Number (dBASE II)
			case 'O': // Double (dBASE L7 only)
			case 'T': // Datetime (VFP only)
			case 'Y': // Currency (VFP only)
				break;
			default: throw new Error('Unknown Field Type: ' + field.type);
		}
	}

	if(d[d.l] !== 0x0D) d.l = fpos-1;
	if(d.read_shift(1) !== 0x0D) throw new Error("DBF Terminator not found " + d.l + " " + d[d.l]);
	d.l = fpos;

	/* data */
	var R = 0, C = 0;
	out[0] = [];
	for(C = 0; C != fields.length; ++C) out[0][C] = fields[C].name;
	while(nrow-- > 0) {
		if(d[d.l] === 0x2A) {
			// TODO: record marked as deleted -- create a hidden row?
			d.l+=rlen;
			continue;
		}
		++d.l;
		out[++R] = []; C = 0;
		for(C = 0; C != fields.length; ++C) {
			var dd = d.slice(d.l, d.l+fields[C].len); d.l+=fields[C].len;
			prep_blob(dd, 0);
			var s = $cptable.utils.decode(current_cp, dd);
			switch(fields[C].type) {
				case 'C':
					// NOTE: it is conventional to write '  /  /  ' for empty dates
					if(s.trim().length) out[R][C] = s.replace(/\s+$/,"");
					break;
				case 'D':
					if(s.length === 8) out[R][C] = new Date(+s.slice(0,4), +s.slice(4,6)-1, +s.slice(6,8));
					else out[R][C] = s;
					break;
				case 'F': out[R][C] = parseFloat(s.trim()); break;
				case '+': case 'I': out[R][C] = l7 ? dd.read_shift(-4, 'i') ^ 0x80000000 : dd.read_shift(4, 'i'); break;
				case 'L': switch(s.trim().toUpperCase()) {
					case 'Y': case 'T': out[R][C] = true; break;
					case 'N': case 'F': out[R][C] = false; break;
					case '': case '?': break;
					default: throw new Error("DBF Unrecognized L:|" + s + "|");
					} break;
				case 'M': /* TODO: handle memo files */
					if(!memo) throw new Error("DBF Unexpected MEMO for type " + ft.toString(16));
					out[R][C] = "##MEMO##" + (l7 ? parseInt(s.trim(), 10): dd.read_shift(4));
					break;
				case 'N':
					s = s.replace(/\u0000/g,"").trim();
					// NOTE: dBASE II interprets "  .  " as 0
					if(s && s != ".") out[R][C] = +s || 0; break;
				case '@':
					// NOTE: dBASE specs appear to be incorrect
					out[R][C] = new Date(dd.read_shift(-8, 'f') - 0x388317533400);
					break;
				case 'T': out[R][C] = new Date((dd.read_shift(4) - 0x253D8C) * 0x5265C00 + dd.read_shift(4)); break;
				case 'Y': out[R][C] = dd.read_shift(4,'i')/1e4 + (dd.read_shift(4, 'i')/1e4)*Math.pow(2,32); break;
				case 'O': out[R][C] = -dd.read_shift(-8, 'f'); break;
				case 'B': if(vfp && fields[C].len == 8) { out[R][C] = dd.read_shift(8,'f'); break; }
					/* falls through */
				case 'G': case 'P': dd.l += fields[C].len; break;
				case '0':
					if(fields[C].name === '_NullFlags') break;
					/* falls through */
				default: throw new Error("DBF Unsupported data type " + fields[C].type);
			}
		}
	}
	if(ft != 0x02) if(d.l < d.length && d[d.l++] != 0x1A) throw new Error("DBF EOF Marker missing " + (d.l-1) + " of " + d.length + " " + d[d.l-1].toString(16));
	if(opts && opts.sheetRows) out = out.slice(0, opts.sheetRows);
	opts.DBF = fields;
	return out;
}

function dbf_to_sheet(buf, opts)/*:Worksheet*/ {
	var o = opts || {};
	if(!o.dateNF) o.dateNF = "yyyymmdd";
	var ws = aoa_to_sheet(dbf_to_aoa(buf, o), o);
	ws["!cols"] = o.DBF.map(function(field) { return {
		wch: field.len,
		DBF: field
	};});
	delete o.DBF;
	return ws;
}

function dbf_to_workbook(buf, opts)/*:Workbook*/ {
	try { return sheet_to_workbook(dbf_to_sheet(buf, opts), opts); }
	catch(e) { if(opts && opts.WTF) throw e; }
	return ({SheetNames:[],Sheets:{}});
}

var _RLEN = { 'B': 8, 'C': 250, 'L': 1, 'D': 8, '?': 0, '': 0 };
function sheet_to_dbf(ws/*:Worksheet*/, opts/*:WriteOpts*/) {
	var o = opts || {};
	if(+o.codepage >= 0) set_cp(+o.codepage);
	if(o.type == "string") throw new Error("Cannot write DBF to JS string");
	var ba = buf_array();
	var aoa/*:AOA*/ = sheet_to_json(ws, {header:1, raw:true, cellDates:true});
	var headers = aoa[0], data = aoa.slice(1), cols = ws["!cols"] || [];
	var i = 0, j = 0, hcnt = 0, rlen = 1;
	for(i = 0; i < headers.length; ++i) {
		if(((cols[i]||{}).DBF||{}).name) { headers[i] = cols[i].DBF.name; ++hcnt; continue; }
		if(headers[i] == null) continue;
		++hcnt;
		if(typeof headers[i] === 'number') headers[i] = headers[i].toString(10);
		if(typeof headers[i] !== 'string') throw new Error("DBF Invalid column name " + headers[i] + " |" + (typeof headers[i]) + "|");
		if(headers.indexOf(headers[i]) !== i) for(j=0; j<1024;++j)
			if(headers.indexOf(headers[i] + "_" + j) == -1) { headers[i] += "_" + j; break; }
	}
	var range = safe_decode_range(ws['!ref']);
	var coltypes/*:Array<string>*/ = [];
	var colwidths/*:Array<number>*/ = [];
	var coldecimals/*:Array<number>*/ = [];
	for(i = 0; i <= range.e.c - range.s.c; ++i) {
		var guess = '', _guess = '', maxlen = 0;
		var col/*:Array<any>*/ = [];
		for(j=0; j < data.length; ++j) {
			if(data[j][i] != null) col.push(data[j][i]);
		}
		if(col.length == 0 || headers[i] == null) { coltypes[i] = '?'; continue; }
		for(j = 0; j < col.length; ++j) {
			switch(typeof col[j]) {
				/* TODO: check if L2 compat is desired */
				case 'number': _guess = 'B'; break;
				case 'string': _guess = 'C'; break;
				case 'boolean': _guess = 'L'; break;
				case 'object': _guess = col[j] instanceof Date ? 'D' : 'C'; break;
				default: _guess = 'C';
			}
			maxlen = Math.max(maxlen, String(col[j]).length);
			guess = guess && guess != _guess ? 'C' : _guess;
			//if(guess == 'C') break;
		}
		if(maxlen > 250) maxlen = 250;
		_guess = ((cols[i]||{}).DBF||{}).type;
		/* TODO: more fine grained control over DBF type resolution */
		if(_guess == 'C') {
			if(cols[i].DBF.len > maxlen) maxlen = cols[i].DBF.len;
		}
		if(guess == 'B' && _guess == 'N') {
			guess = 'N';
			coldecimals[i] = cols[i].DBF.dec;
			maxlen = cols[i].DBF.len;
		}
		colwidths[i] = guess == 'C' || _guess == 'N' ? maxlen : (_RLEN[guess] || 0);
		rlen += colwidths[i];
		coltypes[i] = guess;
	}

	var h = ba.next(32);
	h.write_shift(4, 0x13021130);
	h.write_shift(4, data.length);
	h.write_shift(2, 296 + 32 * hcnt);
	h.write_shift(2, rlen);
	for(i=0; i < 4; ++i) h.write_shift(4, 0);
	h.write_shift(4, 0x00000000 | ((+dbf_reverse_map[/*::String(*/current_ansi/*::)*/] || 0x03)<<8));

	for(i = 0, j = 0; i < headers.length; ++i) {
		if(headers[i] == null) continue;
		var hf = ba.next(32);
		var _f = (headers[i].slice(-10) + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00").slice(0, 11);
		hf.write_shift(1, _f, "sbcs");
		hf.write_shift(1, coltypes[i] == '?' ? 'C' : coltypes[i], "sbcs");
		hf.write_shift(4, j);
		hf.write_shift(1, colwidths[i] || _RLEN[coltypes[i]] || 0);
		hf.write_shift(1, coldecimals[i] || 0);
		hf.write_shift(1, 0x02);
		hf.write_shift(4, 0);
		hf.write_shift(1, 0);
		hf.write_shift(4, 0);
		hf.write_shift(4, 0);
		j += (colwidths[i] || _RLEN[coltypes[i]] || 0);
	}

	var hb = ba.next(264);
	hb.write_shift(4, 0x0000000D);
	for(i=0; i < 65;++i) hb.write_shift(4, 0x00000000);
	for(i=0; i < data.length; ++i) {
		var rout = ba.next(rlen);
		rout.write_shift(1, 0);
		for(j=0; j<headers.length; ++j) {
			if(headers[j] == null) continue;
			switch(coltypes[j]) {
				case 'L': rout.write_shift(1, data[i][j] == null ? 0x3F : data[i][j] ? 0x54 : 0x46); break;
				case 'B': rout.write_shift(8, data[i][j]||0, 'f'); break;
				case 'N':
					var _n = "0";
					if(typeof data[i][j] == "number") _n = data[i][j].toFixed(coldecimals[j]||0);
					for(hcnt=0; hcnt < colwidths[j]-_n.length; ++hcnt) rout.write_shift(1, 0x20);
					rout.write_shift(1, _n, "sbcs");
					break;
				case 'D':
					if(!data[i][j]) rout.write_shift(8, "00000000", "sbcs");
					else {
						rout.write_shift(4, ("0000"+data[i][j].getFullYear()).slice(-4), "sbcs");
						rout.write_shift(2, ("00"+(data[i][j].getMonth()+1)).slice(-2), "sbcs");
						rout.write_shift(2, ("00"+data[i][j].getDate()).slice(-2), "sbcs");
					} break;
				case 'C':
					var _s = String(data[i][j] != null ? data[i][j] : "").slice(0, colwidths[j]);
					rout.write_shift(1, _s, "sbcs");
					for(hcnt=0; hcnt < colwidths[j]-_s.length; ++hcnt) rout.write_shift(1, 0x20); break;
			}
		}
		// data
	}
	ba.next(1).write_shift(1, 0x1A);
	return ba.end();
}
	return {
		to_workbook: dbf_to_workbook,
		to_sheet: dbf_to_sheet,
		from_sheet: sheet_to_dbf
	};
})();

var SYLK = /*#__PURE__*/(function() {
	/* TODO: stress test sequences */
	var sylk_escapes = ({
		AA:'À', BA:'Á', CA:'Â', DA:195, HA:'Ä', JA:197,
		AE:'È', BE:'É', CE:'Ê',         HE:'Ë',
		AI:'Ì', BI:'Í', CI:'Î',         HI:'Ï',
		AO:'Ò', BO:'Ó', CO:'Ô', DO:213, HO:'Ö',
		AU:'Ù', BU:'Ú', CU:'Û',         HU:'Ü',
		Aa:'à', Ba:'á', Ca:'â', Da:227, Ha:'ä', Ja:229,
		Ae:'è', Be:'é', Ce:'ê',         He:'ë',
		Ai:'ì', Bi:'í', Ci:'î',         Hi:'ï',
		Ao:'ò', Bo:'ó', Co:'ô', Do:245, Ho:'ö',
		Au:'ù', Bu:'ú', Cu:'û',         Hu:'ü',
		KC:'Ç', Kc:'ç', q:'æ',  z:'œ',  a:'Æ',  j:'Œ',
		DN:209, Dn:241, Hy:255,
		S:169,  c:170,  R:174,  "B ":180,
		/*::[*/0/*::]*/:176,    /*::[*/1/*::]*/:177,  /*::[*/2/*::]*/:178,
		/*::[*/3/*::]*/:179,    /*::[*/5/*::]*/:181,  /*::[*/6/*::]*/:182,
		/*::[*/7/*::]*/:183,    Q:185,  k:186,  b:208,  i:216,  l:222,  s:240,  y:248,
		"!":161, '"':162, "#":163, "(":164, "%":165, "'":167, "H ":168,
		"+":171, ";":187, "<":188, "=":189, ">":190, "?":191, "{":223
	}/*:any*/);
	var sylk_char_regex = new RegExp("\u001BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g,"\\$1") + "|\\|)", "gm");
	var sylk_char_fn = function(_, $1){ var o = sylk_escapes[$1]; return typeof o == "number" ? _getansi(o) : o; };
	var decode_sylk_char = function($$, $1, $2) { var newcc = (($1.charCodeAt(0) - 0x20)<<4) | ($2.charCodeAt(0) - 0x30); return newcc == 59 ? $$ : _getansi(newcc); };
	sylk_escapes["|"] = 254;
	/* TODO: find an actual specification */
	function sylk_to_aoa(d/*:RawData*/, opts)/*:[AOA, Worksheet]*/ {
		switch(opts.type) {
			case 'base64': return sylk_to_aoa_str(Base64_decode(d), opts);
			case 'binary': return sylk_to_aoa_str(d, opts);
			case 'buffer': return sylk_to_aoa_str(has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d), opts);
			case 'array': return sylk_to_aoa_str(cc2str(d), opts);
		}
		throw new Error("Unrecognized type " + opts.type);
	}
	function sylk_to_aoa_str(str/*:string*/, opts)/*:[AOA, Worksheet]*/ {
		var records = str.split(/[\n\r]+/), R = -1, C = -1, ri = 0, rj = 0, arr/*:AOA*/ = [];
		var formats/*:Array<string>*/ = [];
		var next_cell_format/*:string|null*/ = null;
		var sht = {}, rowinfo/*:Array<RowInfo>*/ = [], colinfo/*:Array<ColInfo>*/ = [], cw/*:Array<string>*/ = [];
		var Mval = 0, j;
		if(+opts.codepage >= 0) set_cp(+opts.codepage);
		for (; ri !== records.length; ++ri) {
			Mval = 0;
			var rstr=records[ri].trim().replace(/\x1B([\x20-\x2F])([\x30-\x3F])/g, decode_sylk_char).replace(sylk_char_regex, sylk_char_fn);
			var record=rstr.replace(/;;/g, "\u0000").split(";").map(function(x) { return x.replace(/\u0000/g, ";"); });
			var RT=record[0], val;
			if(rstr.length > 0) switch(RT) {
			case 'ID': break; /* header */
			case 'E': break; /* EOF */
			case 'B': break; /* dimensions */
			case 'O': break; /* options? */
			case 'W': break; /* window? */
			case 'P':
				if(record[1].charAt(0) == 'P')
					formats.push(rstr.slice(3).replace(/;;/g, ";"));
				break;
			case 'C':
			var C_seen_K = false, C_seen_X = false, C_seen_S = false, C_seen_E = false, _R = -1, _C = -1;
			for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
				case 'A': break; // TODO: comment
				case 'X': C = parseInt(record[rj].slice(1))-1; C_seen_X = true; break;
				case 'Y':
					R = parseInt(record[rj].slice(1))-1; if(!C_seen_X) C = 0;
					for(j = arr.length; j <= R; ++j) arr[j] = [];
					break;
				case 'K':
					val = record[rj].slice(1);
					if(val.charAt(0) === '"') val = val.slice(1,val.length - 1);
					else if(val === 'TRUE') val = true;
					else if(val === 'FALSE') val = false;
					else if(!isNaN(fuzzynum(val))) {
						val = fuzzynum(val);
						if(next_cell_format !== null && fmt_is_date(next_cell_format)) val = numdate(val);
					} else if(!isNaN(fuzzydate(val).getDate())) {
						val = parseDate(val);
					}
					if(typeof $cptable !== 'undefined' && typeof val == "string" && ((opts||{}).type != "string") && (opts||{}).codepage) val = $cptable.utils.decode(opts.codepage, val);
					C_seen_K = true;
					break;
				case 'E':
					C_seen_E = true;
					var formula = rc_to_a1(record[rj].slice(1), {r:R,c:C});
					arr[R][C] = [arr[R][C], formula];
					break;
				case 'S':
					C_seen_S = true;
					arr[R][C] = [arr[R][C], "S5S"];
					break;
				case 'G': break; // unknown
				case 'R': _R = parseInt(record[rj].slice(1))-1; break;
				case 'C': _C = parseInt(record[rj].slice(1))-1; break;
				default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
			}
			if(C_seen_K) {
				if(arr[R][C] && arr[R][C].length == 2) arr[R][C][0] = val;
				else arr[R][C] = val;
				next_cell_format = null;
			}
			if(C_seen_S) {
				if(C_seen_E) throw new Error("SYLK shared formula cannot have own formula");
				var shrbase = _R > -1 && arr[_R][_C];
				if(!shrbase || !shrbase[1]) throw new Error("SYLK shared formula cannot find base");
				arr[R][C][1] = shift_formula_str(shrbase[1], {r: R - _R, c: C - _C});
			}
			break;
			case 'F':
			var F_seen = 0;
			for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
				case 'X': C = parseInt(record[rj].slice(1))-1; ++F_seen; break;
				case 'Y':
					R = parseInt(record[rj].slice(1))-1; /*C = 0;*/
					for(j = arr.length; j <= R; ++j) arr[j] = [];
					break;
				case 'M': Mval = parseInt(record[rj].slice(1)) / 20; break;
				case 'F': break; /* ??? */
				case 'G': break; /* hide grid */
				case 'P':
					next_cell_format = formats[parseInt(record[rj].slice(1))];
					break;
				case 'S': break; /* cell style */
				case 'D': break; /* column */
				case 'N': break; /* font */
				case 'W':
					cw = record[rj].slice(1).split(" ");
					for(j = parseInt(cw[0], 10); j <= parseInt(cw[1], 10); ++j) {
						Mval = parseInt(cw[2], 10);
						colinfo[j-1] = Mval === 0 ? {hidden:true}: {wch:Mval}; process_col(colinfo[j-1]);
					} break;
				case 'C': /* default column format */
					C = parseInt(record[rj].slice(1))-1;
					if(!colinfo[C]) colinfo[C] = {};
					break;
				case 'R': /* row properties */
					R = parseInt(record[rj].slice(1))-1;
					if(!rowinfo[R]) rowinfo[R] = {};
					if(Mval > 0) { rowinfo[R].hpt = Mval; rowinfo[R].hpx = pt2px(Mval); }
					else if(Mval === 0) rowinfo[R].hidden = true;
					break;
				default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
			}
			if(F_seen < 1) next_cell_format = null; break;
			default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
			}
		}
		if(rowinfo.length > 0) sht['!rows'] = rowinfo;
		if(colinfo.length > 0) sht['!cols'] = colinfo;
		if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
		return [arr, sht];
	}

	function sylk_to_sheet(d/*:RawData*/, opts)/*:Worksheet*/ {
		var aoasht = sylk_to_aoa(d, opts);
		var aoa = aoasht[0], ws = aoasht[1];
		var o = aoa_to_sheet(aoa, opts);
		keys(ws).forEach(function(k) { o[k] = ws[k]; });
		return o;
	}

	function sylk_to_workbook(d/*:RawData*/, opts)/*:Workbook*/ { return sheet_to_workbook(sylk_to_sheet(d, opts), opts); }

	function write_ws_cell_sylk(cell/*:Cell*/, ws/*:Worksheet*/, R/*:number*/, C/*:number*//*::, opts*/)/*:string*/ {
		var o = "C;Y" + (R+1) + ";X" + (C+1) + ";K";
		switch(cell.t) {
			case 'n':
				o += (cell.v||0);
				if(cell.f && !cell.F) o += ";E" + a1_to_rc(cell.f, {r:R, c:C}); break;
			case 'b': o += cell.v ? "TRUE" : "FALSE"; break;
			case 'e': o += cell.w || cell.v; break;
			case 'd': o += '"' + (cell.w || cell.v) + '"'; break;
			case 's': o += '"' + cell.v.replace(/"/g,"").replace(/;/g, ";;") + '"'; break;
		}
		return o;
	}

	function write_ws_cols_sylk(out, cols) {
		cols.forEach(function(col, i) {
			var rec = "F;W" + (i+1) + " " + (i+1) + " ";
			if(col.hidden) rec += "0";
			else {
				if(typeof col.width == 'number' && !col.wpx) col.wpx = width2px(col.width);
				if(typeof col.wpx == 'number' && !col.wch) col.wch = px2char(col.wpx);
				if(typeof col.wch == 'number') rec += Math.round(col.wch);
			}
			if(rec.charAt(rec.length - 1) != " ") out.push(rec);
		});
	}

	function write_ws_rows_sylk(out/*:Array<string>*/, rows/*:Array<RowInfo>*/) {
		rows.forEach(function(row, i) {
			var rec = "F;";
			if(row.hidden) rec += "M0;";
			else if(row.hpt) rec += "M" + 20 * row.hpt + ";";
			else if(row.hpx) rec += "M" + 20 * px2pt(row.hpx) + ";";
			if(rec.length > 2) out.push(rec + "R" + (i+1));
		});
	}

	function sheet_to_sylk(ws/*:Worksheet*/, opts/*:?any*/)/*:string*/ {
		var preamble/*:Array<string>*/ = ["ID;PWXL;N;E"], o/*:Array<string>*/ = [];
		var r = safe_decode_range(ws['!ref']), cell/*:Cell*/;
		var dense = Array.isArray(ws);
		var RS = "\r\n";

		preamble.push("P;PGeneral");
		preamble.push("F;P0;DG0G8;M255");
		if(ws['!cols']) write_ws_cols_sylk(preamble, ws['!cols']);
		if(ws['!rows']) write_ws_rows_sylk(preamble, ws['!rows']);

		preamble.push("B;Y" + (r.e.r - r.s.r + 1) + ";X" + (r.e.c - r.s.c + 1) + ";D" + [r.s.c,r.s.r,r.e.c,r.e.r].join(" "));
		for(var R = r.s.r; R <= r.e.r; ++R) {
			for(var C = r.s.c; C <= r.e.c; ++C) {
				var coord = encode_cell({r:R,c:C});
				cell = dense ? (ws[R]||[])[C]: ws[coord];
				if(!cell || (cell.v == null && (!cell.f || cell.F))) continue;
				o.push(write_ws_cell_sylk(cell, ws, R, C, opts));
			}
		}
		return preamble.join(RS) + RS + o.join(RS) + RS + "E" + RS;
	}

	return {
		to_workbook: sylk_to_workbook,
		to_sheet: sylk_to_sheet,
		from_sheet: sheet_to_sylk
	};
})();

var DIF = /*#__PURE__*/(function() {
	function dif_to_aoa(d/*:RawData*/, opts)/*:AOA*/ {
		switch(opts.type) {
			case 'base64': return dif_to_aoa_str(Base64_decode(d), opts);
			case 'binary': return dif_to_aoa_str(d, opts);
			case 'buffer': return dif_to_aoa_str(has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d), opts);
			case 'array': return dif_to_aoa_str(cc2str(d), opts);
		}
		throw new Error("Unrecognized type " + opts.type);
	}
	function dif_to_aoa_str(str/*:string*/, opts)/*:AOA*/ {
		var records = str.split('\n'), R = -1, C = -1, ri = 0, arr/*:AOA*/ = [];
		for (; ri !== records.length; ++ri) {
			if (records[ri].trim() === 'BOT') { arr[++R] = []; C = 0; continue; }
			if (R < 0) continue;
			var metadata = records[ri].trim().split(",");
			var type = metadata[0], value = metadata[1];
			++ri;
			var data = records[ri] || "";
			while(((data.match(/["]/g)||[]).length & 1) && ri < records.length - 1) data += "\n" + records[++ri];
			data = data.trim();
			switch (+type) {
				case -1:
					if (data === 'BOT') { arr[++R] = []; C = 0; continue; }
					else if (data !== 'EOD') throw new Error("Unrecognized DIF special command " + data);
					break;
				case 0:
					if(data === 'TRUE') arr[R][C] = true;
					else if(data === 'FALSE') arr[R][C] = false;
					else if(!isNaN(fuzzynum(value))) arr[R][C] = fuzzynum(value);
					else if(!isNaN(fuzzydate(value).getDate())) arr[R][C] = parseDate(value);
					else arr[R][C] = value;
					++C; break;
				case 1:
					data = data.slice(1,data.length-1);
					data = data.replace(/""/g, '"');
					if(DIF_XL && data && data.match(/^=".*"$/)) data = data.slice(2, -1);
					arr[R][C++] = data !== '' ? data : null;
					break;
			}
			if (data === 'EOD') break;
		}
		if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
		return arr;
	}

	function dif_to_sheet(str/*:string*/, opts)/*:Worksheet*/ { return aoa_to_sheet(dif_to_aoa(str, opts), opts); }
	function dif_to_workbook(str/*:string*/, opts)/*:Workbook*/ { return sheet_to_workbook(dif_to_sheet(str, opts), opts); }

	var sheet_to_dif = /*#__PURE__*/(function() {
		var push_field = function pf(o/*:Array<string>*/, topic/*:string*/, v/*:number*/, n/*:number*/, s/*:string*/) {
			o.push(topic);
			o.push(v + "," + n);
			o.push('"' + s.replace(/"/g,'""') + '"');
		};
		var push_value = function po(o/*:Array<string>*/, type/*:number*/, v/*:any*/, s/*:string*/) {
			o.push(type + "," + v);
			o.push(type == 1 ? '"' + s.replace(/"/g,'""') + '"' : s);
		};
		return function sheet_to_dif(ws/*:Worksheet*//*::, opts:?any*/)/*:string*/ {
			var o/*:Array<string>*/ = [];
			var r = safe_decode_range(ws['!ref']), cell/*:Cell*/;
			var dense = Array.isArray(ws);
			push_field(o, "TABLE", 0, 1, "sheetjs");
			push_field(o, "VECTORS", 0, r.e.r - r.s.r + 1,"");
			push_field(o, "TUPLES", 0, r.e.c - r.s.c + 1,"");
			push_field(o, "DATA", 0, 0,"");
			for(var R = r.s.r; R <= r.e.r; ++R) {
				push_value(o, -1, 0, "BOT");
				for(var C = r.s.c; C <= r.e.c; ++C) {
					var coord = encode_cell({r:R,c:C});
					cell = dense ? (ws[R]||[])[C] : ws[coord];
					if(!cell) { push_value(o, 1, 0, ""); continue;}
					switch(cell.t) {
						case 'n':
							var val = DIF_XL ? cell.w : cell.v;
							if(!val && cell.v != null) val = cell.v;
							if(val == null) {
								if(DIF_XL && cell.f && !cell.F) push_value(o, 1, 0, "=" + cell.f);
								else push_value(o, 1, 0, "");
							}
							else push_value(o, 0, val, "V");
							break;
						case 'b':
							push_value(o, 0, cell.v ? 1 : 0, cell.v ? "TRUE" : "FALSE");
							break;
						case 's':
							push_value(o, 1, 0, (!DIF_XL || isNaN(cell.v)) ? cell.v : '="' + cell.v + '"');
							break;
						case 'd':
							if(!cell.w) cell.w = SSF_format(cell.z || table_fmt[14], datenum(parseDate(cell.v)));
							if(DIF_XL) push_value(o, 0, cell.w, "V");
							else push_value(o, 1, 0, cell.w);
							break;
						default: push_value(o, 1, 0, "");
					}
				}
			}
			push_value(o, -1, 0, "EOD");
			var RS = "\r\n";
			var oo = o.join(RS);
			//while((oo.length & 0x7F) != 0) oo += "\0";
			return oo;
		};
	})();
	return {
		to_workbook: dif_to_workbook,
		to_sheet: dif_to_sheet,
		from_sheet: sheet_to_dif
	};
})();

var ETH = /*#__PURE__*/(function() {
	function decode(s/*:string*/)/*:string*/ { return s.replace(/\\b/g,"\\").replace(/\\c/g,":").replace(/\\n/g,"\n"); }
	function encode(s/*:string*/)/*:string*/ { return s.replace(/\\/g, "\\b").replace(/:/g, "\\c").replace(/\n/g,"\\n"); }

	function eth_to_aoa(str/*:string*/, opts)/*:AOA*/ {
		var records = str.split('\n'), R = -1, C = -1, ri = 0, arr/*:AOA*/ = [];
		for (; ri !== records.length; ++ri) {
			var record = records[ri].trim().split(":");
			if(record[0] !== 'cell') continue;
			var addr = decode_cell(record[1]);
			if(arr.length <= addr.r) for(R = arr.length; R <= addr.r; ++R) if(!arr[R]) arr[R] = [];
			R = addr.r; C = addr.c;
			switch(record[2]) {
				case 't': arr[R][C] = decode(record[3]); break;
				case 'v': arr[R][C] = +record[3]; break;
				case 'vtf': var _f = record[record.length - 1];
					/* falls through */
				case 'vtc':
					switch(record[3]) {
						case 'nl': arr[R][C] = +record[4] ? true : false; break;
						default: arr[R][C] = +record[4]; break;
					}
					if(record[2] == 'vtf') arr[R][C] = [arr[R][C], _f];
			}
		}
		if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
		return arr;
	}

	function eth_to_sheet(d/*:string*/, opts)/*:Worksheet*/ { return aoa_to_sheet(eth_to_aoa(d, opts), opts); }
	function eth_to_workbook(d/*:string*/, opts)/*:Workbook*/ { return sheet_to_workbook(eth_to_sheet(d, opts), opts); }

	var header = [
		"socialcalc:version:1.5",
		"MIME-Version: 1.0",
		"Content-Type: multipart/mixed; boundary=SocialCalcSpreadsheetControlSave"
	].join("\n");

	var sep = [
		"--SocialCalcSpreadsheetControlSave",
		"Content-type: text/plain; charset=UTF-8"
	].join("\n") + "\n";

	/* TODO: the other parts */
	var meta = [
		"# SocialCalc Spreadsheet Control Save",
		"part:sheet"
	].join("\n");

	var end = "--SocialCalcSpreadsheetControlSave--";

	function sheet_to_eth_data(ws/*:Worksheet*/)/*:string*/ {
		if(!ws || !ws['!ref']) return "";
		var o/*:Array<string>*/ = [], oo/*:Array<string>*/ = [], cell, coord = "";
		var r = decode_range(ws['!ref']);
		var dense = Array.isArray(ws);
		for(var R = r.s.r; R <= r.e.r; ++R) {
			for(var C = r.s.c; C <= r.e.c; ++C) {
				coord = encode_cell({r:R,c:C});
				cell = dense ? (ws[R]||[])[C] : ws[coord];
				if(!cell || cell.v == null || cell.t === 'z') continue;
				oo = ["cell", coord, 't'];
				switch(cell.t) {
					case 's': case 'str': oo.push(encode(cell.v)); break;
					case 'n':
						if(!cell.f) { oo[2]='v'; oo[3]=cell.v; }
						else { oo[2]='vtf'; oo[3]='n'; oo[4]=cell.v; oo[5]=encode(cell.f); }
						break;
					case 'b':
						oo[2] = 'vt'+(cell.f?'f':'c'); oo[3]='nl'; oo[4]=cell.v?"1":"0";
						oo[5] = encode(cell.f||(cell.v?'TRUE':'FALSE'));
						break;
					case 'd':
						var t = datenum(parseDate(cell.v));
						oo[2] = 'vtc'; oo[3] = 'nd'; oo[4] = ""+t;
						oo[5] = cell.w || SSF_format(cell.z || table_fmt[14], t);
						break;
					case 'e': continue;
				}
				o.push(oo.join(":"));
			}
		}
		o.push("sheet:c:" + (r.e.c-r.s.c+1) + ":r:" + (r.e.r-r.s.r+1) + ":tvf:1");
		o.push("valueformat:1:text-wiki");
		//o.push("copiedfrom:" + ws['!ref']); // clipboard only
		return o.join("\n");
	}

	function sheet_to_eth(ws/*:Worksheet*//*::, opts:?any*/)/*:string*/ {
		return [header, sep, meta, sep, sheet_to_eth_data(ws), end].join("\n");
		// return ["version:1.5", sheet_to_eth_data(ws)].join("\n"); // clipboard form
	}

	return {
		to_workbook: eth_to_workbook,
		to_sheet: eth_to_sheet,
		from_sheet: sheet_to_eth
	};
})();

var PRN = /*#__PURE__*/(function() {
	function set_text_arr(data/*:string*/, arr/*:AOA*/, R/*:number*/, C/*:number*/, o/*:any*/) {
		if(o.raw) arr[R][C] = data;
		else if(data === ""){/* empty */}
		else if(data === 'TRUE') arr[R][C] = true;
		else if(data === 'FALSE') arr[R][C] = false;
		else if(!isNaN(fuzzynum(data))) arr[R][C] = fuzzynum(data);
		else if(!isNaN(fuzzydate(data).getDate())) arr[R][C] = parseDate(data);
		else arr[R][C] = data;
	}

	function prn_to_aoa_str(f/*:string*/, opts)/*:AOA*/ {
		var o = opts || {};
		var arr/*:AOA*/ = ([]/*:any*/);
		if(!f || f.length === 0) return arr;
		var lines = f.split(/[\r\n]/);
		var L = lines.length - 1;
		while(L >= 0 && lines[L].length === 0) --L;
		var start = 10, idx = 0;
		var R = 0;
		for(; R <= L; ++R) {
			idx = lines[R].indexOf(" ");
			if(idx == -1) idx = lines[R].length; else idx++;
			start = Math.max(start, idx);
		}
		for(R = 0; R <= L; ++R) {
			arr[R] = [];
			/* TODO: confirm that widths are always 10 */
			var C = 0;
			set_text_arr(lines[R].slice(0, start).trim(), arr, R, C, o);
			for(C = 1; C <= (lines[R].length - start)/10 + 1; ++C)
				set_text_arr(lines[R].slice(start+(C-1)*10,start+C*10).trim(),arr,R,C,o);
		}
		if(o.sheetRows) arr = arr.slice(0, o.sheetRows);
		return arr;
	}

	// List of accepted CSV separators
	var guess_seps = {
		/*::[*/0x2C/*::]*/: ',',
		/*::[*/0x09/*::]*/: "\t",
		/*::[*/0x3B/*::]*/: ';',
		/*::[*/0x7C/*::]*/: '|'
	};

	// CSV separator weights to be used in case of equal numbers
	var guess_sep_weights = {
		/*::[*/0x2C/*::]*/: 3,
		/*::[*/0x09/*::]*/: 2,
		/*::[*/0x3B/*::]*/: 1,
		/*::[*/0x7C/*::]*/: 0
	};

	function guess_sep(str) {
		var cnt = {}, instr = false, end = 0, cc = 0;
		for(;end < str.length;++end) {
			if((cc=str.charCodeAt(end)) == 0x22) instr = !instr;
			else if(!instr && cc in guess_seps) cnt[cc] = (cnt[cc]||0)+1;
		}

		cc = [];
		for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
			cc.push([ cnt[end], end ]);
		}

		if ( !cc.length ) {
			cnt = guess_sep_weights;
			for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
				cc.push([ cnt[end], end ]);
			}
		}

		cc.sort(function(a, b) { return a[0] - b[0] || guess_sep_weights[a[1]] - guess_sep_weights[b[1]]; });

		return guess_seps[cc.pop()[1]] || 0x2C;
	}

	function dsv_to_sheet_str(str/*:string*/, opts)/*:Worksheet*/ {
		var o = opts || {};
		var sep = "";
		if(DENSE != null && o.dense == null) o.dense = DENSE;
		var ws/*:Worksheet*/ = o.dense ? ([]/*:any*/) : ({}/*:any*/);
		var range/*:Range*/ = ({s: {c:0, r:0}, e: {c:0, r:0}}/*:any*/);

		if(str.slice(0,4) == "sep=") {
			// If the line ends in \r\n
			if(str.charCodeAt(5) == 13 && str.charCodeAt(6) == 10 ) {
				sep = str.charAt(4); str = str.slice(7);
			}
			// If line ends in \r OR \n
			else if(str.charCodeAt(5) == 13 || str.charCodeAt(5) == 10 ) {
				sep = str.charAt(4); str = str.slice(6);
			}
			else sep = guess_sep(str.slice(0,1024));
		}
		else if(o && o.FS) sep = o.FS;
		else sep = guess_sep(str.slice(0,1024));
		var R = 0, C = 0, v = 0;
		var start = 0, end = 0, sepcc = sep.charCodeAt(0), instr = false, cc=0, startcc=str.charCodeAt(0);
		str = str.replace(/\r\n/mg, "\n");
		var _re/*:?RegExp*/ = o.dateNF != null ? dateNF_regex(o.dateNF) : null;
		function finish_cell() {
			var s = str.slice(start, end);
			var cell = ({}/*:any*/);
			if(s.charAt(0) == '"' && s.charAt(s.length - 1) == '"') s = s.slice(1,-1).replace(/""/g,'"');
			if(s.length === 0) cell.t = 'z';
			else if(o.raw) { cell.t = 's'; cell.v = s; }
			else if(s.trim().length === 0) { cell.t = 's'; cell.v = s; }
			else if(s.charCodeAt(0) == 0x3D) {
				if(s.charCodeAt(1) == 0x22 && s.charCodeAt(s.length - 1) == 0x22) { cell.t = 's'; cell.v = s.slice(2,-1).replace(/""/g,'"'); }
				else if(fuzzyfmla(s)) { cell.t = 'n'; cell.f = s.slice(1); }
				else { cell.t = 's'; cell.v = s; } }
			else if(s == "TRUE") { cell.t = 'b'; cell.v = true; }
			else if(s == "FALSE") { cell.t = 'b'; cell.v = false; }
			else if(!isNaN(v = fuzzynum(s))) { cell.t = 'n'; if(o.cellText !== false) cell.w = s; cell.v = v; }
			else if(!isNaN(fuzzydate(s).getDate()) || _re && s.match(_re)) {
				cell.z = o.dateNF || table_fmt[14];
				var k = 0;
				if(_re && s.match(_re)){ s=dateNF_fix(s, o.dateNF, (s.match(_re)||[])); k=1; }
				if(o.cellDates) { cell.t = 'd'; cell.v = parseDate(s, k); }
				else { cell.t = 'n'; cell.v = datenum(parseDate(s, k)); }
				if(o.cellText !== false) cell.w = SSF_format(cell.z, cell.v instanceof Date ? datenum(cell.v):cell.v);
				if(!o.cellNF) delete cell.z;
			} else {
				cell.t = 's';
				cell.v = s;
			}
			if(cell.t == 'z'){}
			else if(o.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = cell; }
			else ws[encode_cell({c:C,r:R})] = cell;
			start = end+1; startcc = str.charCodeAt(start);
			if(range.e.c < C) range.e.c = C;
			if(range.e.r < R) range.e.r = R;
			if(cc == sepcc) ++C; else { C = 0; ++R; if(o.sheetRows && o.sheetRows <= R) return true; }
		}
		outer: for(;end < str.length;++end) switch((cc=str.charCodeAt(end))) {
			case 0x22: if(startcc === 0x22) instr = !instr; break;
			case sepcc: case 0x0a: case 0x0d: if(!instr && finish_cell()) break outer; break;
			default: break;
		}
		if(end - start > 0) finish_cell();

		ws['!ref'] = encode_range(range);
		return ws;
	}

	function prn_to_sheet_str(str/*:string*/, opts)/*:Worksheet*/ {
		if(!(opts && opts.PRN)) return dsv_to_sheet_str(str, opts);
		if(opts.FS) return dsv_to_sheet_str(str, opts);
		if(str.slice(0,4) == "sep=") return dsv_to_sheet_str(str, opts);
		if(str.indexOf("\t") >= 0 || str.indexOf(",") >= 0 || str.indexOf(";") >= 0) return dsv_to_sheet_str(str, opts);
		return aoa_to_sheet(prn_to_aoa_str(str, opts), opts);
	}

	function prn_to_sheet(d/*:RawData*/, opts)/*:Worksheet*/ {
		var str = "", bytes = opts.type == 'string' ? [0,0,0,0] : firstbyte(d, opts);
		switch(opts.type) {
			case 'base64': str = Base64_decode(d); break;
			case 'binary': str = d; break;
			case 'buffer':
				if(opts.codepage == 65001) str = d.toString('utf8'); // TODO: test if buf
				else if(opts.codepage && typeof $cptable !== 'undefined') str = $cptable.utils.decode(opts.codepage, d);
				else str = has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d);
				break;
			case 'array': str = cc2str(d); break;
			case 'string': str = d; break;
			default: throw new Error("Unrecognized type " + opts.type);
		}
		if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str.slice(3));
		else if(opts.type != 'string' && opts.type != 'buffer' && opts.codepage == 65001) str = utf8read(str);
		else if((opts.type == 'binary') && typeof $cptable !== 'undefined' && opts.codepage)  str = $cptable.utils.decode(opts.codepage, $cptable.utils.encode(28591,str));
		if(str.slice(0,19) == "socialcalc:version:") return ETH.to_sheet(opts.type == 'string' ? str : utf8read(str), opts);
		return prn_to_sheet_str(str, opts);
	}

	function prn_to_workbook(d/*:RawData*/, opts)/*:Workbook*/ { return sheet_to_workbook(prn_to_sheet(d, opts), opts); }

	function sheet_to_prn(ws/*:Worksheet*//*::, opts:?any*/)/*:string*/ {
		var o/*:Array<string>*/ = [];
		var r = safe_decode_range(ws['!ref']), cell/*:Cell*/;
		var dense = Array.isArray(ws);
		for(var R = r.s.r; R <= r.e.r; ++R) {
			var oo/*:Array<string>*/ = [];
			for(var C = r.s.c; C <= r.e.c; ++C) {
				var coord = encode_cell({r:R,c:C});
				cell = dense ? (ws[R]||[])[C] : ws[coord];
				if(!cell || cell.v == null) { oo.push("          "); continue; }
				var w = (cell.w || (format_cell(cell), cell.w) || "").slice(0,10);
				while(w.length < 10) w += " ";
				oo.push(w + (C === 0 ? " " : ""));
			}
			o.push(oo.join(""));
		}
		return o.join("\n");
	}

	return {
		to_workbook: prn_to_workbook,
		to_sheet: prn_to_sheet,
		from_sheet: sheet_to_prn
	};
})();

/* Excel defaults to SYLK but warns if data is not valid */
function read_wb_ID(d, opts) {
	var o = opts || {}, OLD_WTF = !!o.WTF; o.WTF = true;
	try {
		var out = SYLK.to_workbook(d, o);
		o.WTF = OLD_WTF;
		return out;
	} catch(e) {
		o.WTF = OLD_WTF;
		if(!e.message.match(/SYLK bad record ID/) && OLD_WTF) throw e;
		return PRN.to_workbook(d, opts);
	}
}

var WK_ = /*#__PURE__*/(function() {
	function lotushopper(data, cb/*:RecordHopperCB*/, opts/*:any*/) {
		if(!data) return;
		prep_blob(data, data.l || 0);
		var Enum = opts.Enum || WK1Enum;
		while(data.l < data.length) {
			var RT = data.read_shift(2);
			var R = Enum[RT] || Enum[0xFFFF];
			var length = data.read_shift(2);
			var tgt = data.l + length;
			var d = R.f && R.f(data, length, opts);
			data.l = tgt;
			if(cb(d, R, RT)) return;
		}
	}

	function lotus_to_workbook(d/*:RawData*/, opts) {
		switch(opts.type) {
			case 'base64': return lotus_to_workbook_buf(s2a(Base64_decode(d)), opts);
			case 'binary': return lotus_to_workbook_buf(s2a(d), opts);
			case 'buffer':
			case 'array': return lotus_to_workbook_buf(d, opts);
		}
		throw "Unsupported type " + opts.type;
	}

	function lotus_to_workbook_buf(d, opts)/*:Workbook*/ {
		if(!d) return d;
		var o = opts || {};
		if(DENSE != null && o.dense == null) o.dense = DENSE;
		var s/*:Worksheet*/ = ((o.dense ? [] : {})/*:any*/), n = "Sheet1", next_n = "", sidx = 0;
		var sheets = {}, snames = [], realnames = [];

		var refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
		var sheetRows = o.sheetRows || 0;

		if(d[2] == 0x00) {
			if(d[3] == 0x08 || d[3] == 0x09) {
				if(d.length >= 16 && d[14] == 0x05 && d[15] === 0x6c) throw new Error("Unsupported Works 3 for Mac file");
			}
		}

		if(d[2] == 0x02) {
			o.Enum = WK1Enum;
			lotushopper(d, function(val, R, RT) { switch(RT) {
				case 0x00: /* BOF */
					o.vers = val;
					if(val >= 0x1000) o.qpro = true;
					break;
				case 0x06: refguess = val; break; /* RANGE */
				case 0xCC: if(val) next_n = val; break; /* SHEETNAMECS */
				case 0xDE: next_n = val; break; /* SHEETNAMELP */
				case 0x0F: /* LABEL */
				case 0x33: /* STRING */
					if(!o.qpro) val[1].v = val[1].v.slice(1);
					/* falls through */
				case 0x0D: /* INTEGER */
				case 0x0E: /* NUMBER */
				case 0x10: /* FORMULA */
					/* TODO: actual translation of the format code */
					if(RT == 0x0E && (val[2] & 0x70) == 0x70 && (val[2] & 0x0F) > 1 && (val[2] & 0x0F) < 15) {
						val[1].z = o.dateNF || table_fmt[14];
						if(o.cellDates) { val[1].t = 'd'; val[1].v = numdate(val[1].v); }
					}

					if(o.qpro) {
						if(val[3] > sidx) {
							s["!ref"] = encode_range(refguess);
							sheets[n] = s;
							snames.push(n);
							s = (o.dense ? [] : {});
							refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
							sidx = val[3]; n = next_n || "Sheet" + (sidx + 1); next_n = "";
						}
					}

					var tmpcell = o.dense ? (s[val[0].r]||[])[val[0].c] : s[encode_cell(val[0])];
					if(tmpcell) {
						tmpcell.t = val[1].t; tmpcell.v = val[1].v;
						if(val[1].z != null) tmpcell.z = val[1].z;
						if(val[1].f != null) tmpcell.f = val[1].f;
						break;
					}
					if(o.dense) {
						if(!s[val[0].r]) s[val[0].r] = [];
						s[val[0].r][val[0].c] = val[1];
					} else s[encode_cell(val[0])] = val[1];
					break;
				default:
			}}, o);
		} else if(d[2] == 0x1A || d[2] == 0x0E) {
			o.Enum = WK3Enum;
			if(d[2] == 0x0E) { o.qpro = true; d.l = 0; }
			lotushopper(d, function(val, R, RT) { switch(RT) {
				case 0xCC: n = val; break; /* SHEETNAMECS */
				case 0x16: /* LABEL16 */
					val[1].v = val[1].v.slice(1);
					/* falls through */
				case 0x17: /* NUMBER17 */
				case 0x18: /* NUMBER18 */
				case 0x19: /* FORMULA19 */
				case 0x25: /* NUMBER25 */
				case 0x27: /* NUMBER27 */
				case 0x28: /* FORMULA28 */
					if(val[3] > sidx) {
						s["!ref"] = encode_range(refguess);
						sheets[n] = s;
						snames.push(n);
						s = (o.dense ? [] : {});
						refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
						sidx = val[3]; n = "Sheet" + (sidx + 1);
					}
					if(sheetRows > 0 && val[0].r >= sheetRows) break;
					if(o.dense) {
						if(!s[val[0].r]) s[val[0].r] = [];
						s[val[0].r][val[0].c] = val[1];
					} else s[encode_cell(val[0])] = val[1];
					if(refguess.e.c < val[0].c) refguess.e.c = val[0].c;
					if(refguess.e.r < val[0].r) refguess.e.r = val[0].r;
					break;
				case 0x1B: /* XFORMAT */
					if(val[0x36b0]) realnames[val[0x36b0][0]] = val[0x36b0][1];
					break;
				case 0x0601: /* SHEETINFOQP */
					realnames[val[0]] = val[1]; if(val[0] == sidx) n = val[1]; break;
				default: break;
			}}, o);
		} else throw new Error("Unrecognized LOTUS BOF " + d[2]);
		s["!ref"] = encode_range(refguess);
		sheets[next_n || n] = s;
		snames.push(next_n || n);
		if(!realnames.length) return { SheetNames: snames, Sheets: sheets };
		var osheets = {}, rnames = [];
		/* TODO: verify no collisions */
		for(var i = 0; i < realnames.length; ++i) if(sheets[snames[i]]) {
			rnames.push(realnames[i] || snames[i]);
			osheets[realnames[i]] = sheets[realnames[i]] || sheets[snames[i]];
		} else {
			rnames.push(realnames[i]);
			osheets[realnames[i]] = ({ "!ref": "A1" });
		}
		return { SheetNames: rnames, Sheets: osheets };
	}

	function sheet_to_wk1(ws/*:Worksheet*/, opts/*:WriteOpts*/) {
		var o = opts || {};
		if(+o.codepage >= 0) set_cp(+o.codepage);
		if(o.type == "string") throw new Error("Cannot write WK1 to JS string");
		var ba = buf_array();
		var range = safe_decode_range(ws["!ref"]);
		var dense = Array.isArray(ws);
		var cols = [];

		write_biff_rec(ba, 0x00, write_BOF_WK1(0x0406));
		write_biff_rec(ba, 0x06, write_RANGE(range));
		var max_R = Math.min(range.e.r, 8191);
		for(var R = range.s.r; R <= max_R; ++R) {
			var rr = encode_row(R);
			for(var C = range.s.c; C <= range.e.c; ++C) {
				if(R === range.s.r) cols[C] = encode_col(C);
				var ref = cols[C] + rr;
				var cell = dense ? (ws[R]||[])[C] : ws[ref];
				if(!cell || cell.t == "z") continue;
				/* TODO: formula records */
				if(cell.t == "n") {
					if((cell.v|0)==cell.v && cell.v >= -32768 && cell.v <= 32767) write_biff_rec(ba, 0x0d, write_INTEGER(R, C, cell.v));
					else write_biff_rec(ba, 0x0e, write_NUMBER(R, C, cell.v));
				} else {
					var str = format_cell(cell);
					write_biff_rec(ba, 0x0F, write_LABEL(R, C, str.slice(0, 239)));
				}
			}
		}

		write_biff_rec(ba, 0x01);
		return ba.end();
	}

	function book_to_wk3(wb/*:Workbook*/, opts/*:WriteOpts*/) {
		var o = opts || {};
		if(+o.codepage >= 0) set_cp(+o.codepage);
		if(o.type == "string") throw new Error("Cannot write WK3 to JS string");
		var ba = buf_array();

		write_biff_rec(ba, 0x00, write_BOF_WK3(wb));

		for(var i = 0, cnt = 0; i < wb.SheetNames.length; ++i) if((wb.Sheets[wb.SheetNames[i]] || {})["!ref"]) write_biff_rec(ba, 0x1b, write_XFORMAT_SHEETNAME(wb.SheetNames[i], cnt++));

		var wsidx = 0;
		for(i = 0; i < wb.SheetNames.length; ++i) {
			var ws = wb.Sheets[wb.SheetNames[i]];
			if(!ws || !ws["!ref"]) continue;
			var range = safe_decode_range(ws["!ref"]);
			var dense = Array.isArray(ws);
			var cols = [];
			var max_R = Math.min(range.e.r, 8191);
			for(var R = range.s.r; R <= max_R; ++R) {
				var rr = encode_row(R);
				for(var C = range.s.c; C <= range.e.c; ++C) {
					if(R === range.s.r) cols[C] = encode_col(C);
					var ref = cols[C] + rr;
					var cell = dense ? (ws[R]||[])[C] : ws[ref];
					if(!cell || cell.t == "z") continue;
					/* TODO: FORMULA19 NUMBER18 records */
					if(cell.t == "n") {
						write_biff_rec(ba, 0x17, write_NUMBER_17(R, C, wsidx, cell.v));
					} else {
						var str = format_cell(cell);
						/* TODO: max len? */
						write_biff_rec(ba, 0x16, write_LABEL_16(R, C, wsidx, str.slice(0, 239)));
					}
				}
			}
			++wsidx;
		}

		write_biff_rec(ba, 0x01);
		return ba.end();
	}


	function write_BOF_WK1(v/*:number*/) {
		var out = new_buf(2);
		out.write_shift(2, v);
		return out;
	}

	function write_BOF_WK3(wb/*:Workbook*/) {
		var out = new_buf(26);
		out.write_shift(2, 0x1000);
		out.write_shift(2, 0x0004);
		out.write_shift(4, 0x0000);
		var rows = 0, cols = 0, wscnt = 0;
		for(var i = 0; i < wb.SheetNames.length; ++i) {
			var name = wb.SheetNames[i];
			var ws = wb.Sheets[name];
			if(!ws || !ws["!ref"]) continue;
			++wscnt;
			var range = decode_range(ws["!ref"]);
			if(rows < range.e.r) rows = range.e.r;
			if(cols < range.e.c) cols = range.e.c;
		}
		if(rows > 8191) rows = 8191;
		out.write_shift(2, rows);
		out.write_shift(1, wscnt);
		out.write_shift(1, cols);
		out.write_shift(2, 0x00);
		out.write_shift(2, 0x00);
		out.write_shift(1, 0x01);
		out.write_shift(1, 0x02);
		out.write_shift(4, 0);
		out.write_shift(4, 0);
		return out;
	}

	function parse_RANGE(blob, length, opts) {
		var o = {s:{c:0,r:0},e:{c:0,r:0}};
		if(length == 8 && opts.qpro) {
			o.s.c = blob.read_shift(1);
			blob.l++;
			o.s.r = blob.read_shift(2);
			o.e.c = blob.read_shift(1);
			blob.l++;
			o.e.r = blob.read_shift(2);
			return o;
		}
		o.s.c = blob.read_shift(2);
		o.s.r = blob.read_shift(2);
		if(length == 12 && opts.qpro) blob.l += 2;
		o.e.c = blob.read_shift(2);
		o.e.r = blob.read_shift(2);
		if(length == 12 && opts.qpro) blob.l += 2;
		if(o.s.c == 0xFFFF) o.s.c = o.e.c = o.s.r = o.e.r = 0;
		return o;
	}
	function write_RANGE(range) {
		var out = new_buf(8);
		out.write_shift(2, range.s.c);
		out.write_shift(2, range.s.r);
		out.write_shift(2, range.e.c);
		out.write_shift(2, range.e.r);
		return out;
	}

	function parse_cell(blob, length, opts) {
		var o = [{c:0,r:0}, {t:'n',v:0}, 0, 0];
		if(opts.qpro && opts.vers != 0x5120) {
			o[0].c = blob.read_shift(1);
			o[3] = blob.read_shift(1);
			o[0].r = blob.read_shift(2);
			blob.l+=2;
		} else {
			o[2] = blob.read_shift(1);
			o[0].c = blob.read_shift(2); o[0].r = blob.read_shift(2);
		}
		return o;
	}

	function parse_LABEL(blob, length, opts) {
		var tgt = blob.l + length;
		var o = parse_cell(blob, length, opts);
		o[1].t = 's';
		if(opts.vers == 0x5120) {
			blob.l++;
			var len = blob.read_shift(1);
			o[1].v = blob.read_shift(len, 'utf8');
			return o;
		}
		if(opts.qpro) blob.l++;
		o[1].v = blob.read_shift(tgt - blob.l, 'cstr');
		return o;
	}
	function write_LABEL(R, C, s) {
		/* TODO: encoding */
		var o = new_buf(7 + s.length);
		o.write_shift(1, 0xFF);
		o.write_shift(2, C);
		o.write_shift(2, R);
		o.write_shift(1, 0x27); // ??
		for(var i = 0; i < o.length; ++i) {
			var cc = s.charCodeAt(i);
			o.write_shift(1, cc >= 0x80 ? 0x5F : cc);
		}
		o.write_shift(1, 0);
		return o;
	}

	function parse_INTEGER(blob, length, opts) {
		var o = parse_cell(blob, length, opts);
		o[1].v = blob.read_shift(2, 'i');
		return o;
	}
	function write_INTEGER(R, C, v) {
		var o = new_buf(7);
		o.write_shift(1, 0xFF);
		o.write_shift(2, C);
		o.write_shift(2, R);
		o.write_shift(2, v, 'i');
		return o;
	}

	function parse_NUMBER(blob, length, opts) {
		var o = parse_cell(blob, length, opts);
		o[1].v = blob.read_shift(8, 'f');
		return o;
	}
	function write_NUMBER(R, C, v) {
		var o = new_buf(13);
		o.write_shift(1, 0xFF);
		o.write_shift(2, C);
		o.write_shift(2, R);
		o.write_shift(8, v, 'f');
		return o;
	}

	function parse_FORMULA(blob, length, opts) {
		var tgt = blob.l + length;
		var o = parse_cell(blob, length, opts);
		/* TODO: formula */
		o[1].v = blob.read_shift(8, 'f');
		if(opts.qpro) blob.l = tgt;
		else {
			var flen = blob.read_shift(2);
			wk1_fmla_to_csf(blob.slice(blob.l, blob.l + flen), o);
			blob.l += flen;
		}
		return o;
	}

	function wk1_parse_rc(B, V, col) {
		var rel = V & 0x8000;
		V &= ~0x8000;
		V = (rel ? B : 0) + ((V >= 0x2000) ? V - 0x4000 : V);
		return (rel ? "" : "$") + (col ? encode_col(V) : encode_row(V));
	}
	/* var oprec = [
		8, 8, 8, 8, 8, 8, 8, 8, 6, 4, 4, 5, 5, 7, 3, 3,
		3, 3, 3, 3, 1, 1, 2, 6, 8, 8, 8, 8, 8, 8, 8, 8
	]; */
	/* TODO: flesh out */
	var FuncTab = {
		0x33: ["FALSE", 0],
		0x34: ["TRUE", 0],
		0x46: ["LEN", 1],
		0x50: ["SUM", 69],
		0x51: ["AVERAGEA", 69],
		0x52: ["COUNTA", 69],
		0x53: ["MINA", 69],
		0x54: ["MAXA", 69],
		0x6F: ["T", 1]
	};
	var BinOpTab = [
		  "",   "",   "",   "",   "",   "",   "",   "", // eslint-disable-line no-mixed-spaces-and-tabs
		  "",  "+",  "-",  "*",  "/",  "^",  "=", "<>", // eslint-disable-line no-mixed-spaces-and-tabs
		"<=", ">=",  "<",  ">",   "",   "",   "",   "", // eslint-disable-line no-mixed-spaces-and-tabs
		 "&",   "",   "",   "",   "",   "",   "",   ""  // eslint-disable-line no-mixed-spaces-and-tabs
	];

	function wk1_fmla_to_csf(blob, o) {
		prep_blob(blob, 0);
		var out = [], argc = 0, R = "", C = "", argL = "", argR = "";
		while(blob.l < blob.length) {
			var cc = blob[blob.l++];
			switch(cc) {
				case 0x00: out.push(blob.read_shift(8, 'f')); break;
				case 0x01: {
					C = wk1_parse_rc(o[0].c, blob.read_shift(2), true);
					R = wk1_parse_rc(o[0].r, blob.read_shift(2), false);
					out.push(C + R);
				} break;
				case 0x02: {
					var c = wk1_parse_rc(o[0].c, blob.read_shift(2), true);
					var r = wk1_parse_rc(o[0].r, blob.read_shift(2), false);
					C = wk1_parse_rc(o[0].c, blob.read_shift(2), true);
					R = wk1_parse_rc(o[0].r, blob.read_shift(2), false);
					out.push(c + r + ":" + C + R);
				} break;
				case 0x03:
					if(blob.l < blob.length) { console.error("WK1 premature formula end"); return; }
					break;
				case 0x04: out.push("(" + out.pop() + ")"); break;
				case 0x05: out.push(blob.read_shift(2)); break;
				case 0x06: {
					/* TODO: text encoding */
					var Z = ""; while((cc = blob[blob.l++])) Z += String.fromCharCode(cc);
					out.push('"' + Z.replace(/"/g, '""') + '"');
				} break;

				case 0x08: out.push("-" + out.pop()); break;
				case 0x17: out.push("+" + out.pop()); break;
				case 0x16: out.push("NOT(" + out.pop() + ")"); break;

				case 0x14: case 0x15: {
					argR = out.pop(); argL = out.pop();
					out.push(["AND", "OR"][cc - 0x14] + "(" + argL + "," + argR + ")");
				} break;

				default:
					if(cc < 0x20 && BinOpTab[cc]) {
						argR = out.pop(); argL = out.pop();
						out.push(argL + BinOpTab[cc] + argR);
					} else if(FuncTab[cc]) {
						argc = FuncTab[cc][1];
						if(argc == 69) argc = blob[blob.l++];
						if(argc > out.length) { console.error("WK1 bad formula parse 0x" + cc.toString(16) + ":|" + out.join("|") + "|"); return; }
						var args = out.slice(-argc);
						out.length -= argc;
						out.push(FuncTab[cc][0] + "(" + args.join(",") + ")");
					}
					else if(cc <= 0x07) return console.error("WK1 invalid opcode " + cc.toString(16));
					else if(cc <= 0x18) return console.error("WK1 unsupported op " + cc.toString(16));
					else if(cc <= 0x1E) return console.error("WK1 invalid opcode " + cc.toString(16));
					else if(cc <= 0x73) return console.error("WK1 unsupported function opcode " + cc.toString(16));
					// possible future functions ??
					else return console.error("WK1 unrecognized opcode " + cc.toString(16));
			}
		}
		if(out.length == 1) o[1].f = "" + out[0];
		else console.error("WK1 bad formula parse |" + out.join("|") + "|");
	}


	function parse_cell_3(blob/*::, length*/) {
		var o = [{c:0,r:0}, {t:'n',v:0}, 0];
		o[0].r = blob.read_shift(2); o[3] = blob[blob.l++]; o[0].c = blob[blob.l++];
		return o;
	}

	function parse_LABEL_16(blob, length) {
		var o = parse_cell_3(blob, length);
		o[1].t = 's';
		o[1].v = blob.read_shift(length - 4, 'cstr');
		return o;
	}
	function write_LABEL_16(R, C, wsidx, s) {
		/* TODO: encoding */
		var o = new_buf(6 + s.length);
		o.write_shift(2, R);
		o.write_shift(1, wsidx);
		o.write_shift(1, C);
		o.write_shift(1, 0x27);
		for(var i = 0; i < s.length; ++i) {
			var cc = s.charCodeAt(i);
			o.write_shift(1, cc >= 0x80 ? 0x5F : cc);
		}
		o.write_shift(1, 0);
		return o;
	}

	function parse_NUMBER_18(blob, length) {
		var o = parse_cell_3(blob, length);
		o[1].v = blob.read_shift(2);
		var v = o[1].v >> 1;
		if(o[1].v & 0x1) {
			switch(v & 0x07) {
				case 0: v = (v >> 3) * 5000; break;
				case 1: v = (v >> 3) * 500; break;
				case 2: v = (v >> 3) / 20; break;
				case 3: v = (v >> 3) / 200; break;
				case 4: v = (v >> 3) / 2000; break;
				case 5: v = (v >> 3) / 20000; break;
				case 6: v = (v >> 3) / 16; break;
				case 7: v = (v >> 3) / 64; break;
			}
		}
		o[1].v = v;
		return o;
	}

	function parse_NUMBER_17(blob, length) {
		var o = parse_cell_3(blob, length);
		var v1 = blob.read_shift(4);
		var v2 = blob.read_shift(4);
		var e = blob.read_shift(2);
		if(e == 0xFFFF) {
			if(v1 === 0 && v2 === 0xC0000000) { o[1].t = "e"; o[1].v = 0x0F; } // ERR -> #VALUE!
			else if(v1 === 0 && v2 === 0xD0000000) { o[1].t = "e"; o[1].v = 0x2A; } // NA -> #N/A
			else o[1].v = 0;
			return o;
		}
		var s = e & 0x8000; e = (e&0x7FFF) - 16446;
		o[1].v = (1 - s*2) * (v2 * Math.pow(2, e+32) + v1 * Math.pow(2, e));
		return o;
	}
	function write_NUMBER_17(R, C, wsidx, v) {
		var o = new_buf(14);
		o.write_shift(2, R);
		o.write_shift(1, wsidx);
		o.write_shift(1, C);
		if(v == 0) {
			o.write_shift(4, 0);
			o.write_shift(4, 0);
			o.write_shift(2, 0xFFFF);
			return o;
		}
		var s = 0, e = 0, v1 = 0, v2 = 0;
		if(v < 0) { s = 1; v = -v; }
		e = Math.log2(v) | 0;
		v /= Math.pow(2, e-31);
		v2 = (v)>>>0;
		if((v2&0x80000000) == 0) { v/=2; ++e; v2 = v >>> 0; }
		v -= v2;
		v2 |= 0x80000000;
		v2 >>>= 0;
		v *= Math.pow(2, 32);
		v1 = v>>>0;
		o.write_shift(4, v1);
		o.write_shift(4, v2);
		e += 0x3FFF + (s ? 0x8000 : 0);
		o.write_shift(2, e);
		return o;
	}

	function parse_FORMULA_19(blob, length) {
		var o = parse_NUMBER_17(blob, 14);
		blob.l += length - 14; /* TODO: WK3 formula */
		return o;
	}

	function parse_NUMBER_25(blob, length) {
		var o = parse_cell_3(blob, length);
		var v1 = blob.read_shift(4);
		o[1].v = v1 >> 6;
		return o;
	}

	function parse_NUMBER_27(blob, length) {
		var o = parse_cell_3(blob, length);
		var v1 = blob.read_shift(8,'f');
		o[1].v = v1;
		return o;
	}

	function parse_FORMULA_28(blob, length) {
		var o = parse_NUMBER_27(blob, 14);
		blob.l += length - 10; /* TODO: formula */
		return o;
	}

	function parse_SHEETNAMECS(blob, length) {
		return blob[blob.l + length - 1] == 0 ? blob.read_shift(length, 'cstr') : "";
	}

	function parse_SHEETNAMELP(blob, length) {
		var len = blob[blob.l++];
		if(len > length - 1) len = length - 1;
		var o = ""; while(o.length < len) o += String.fromCharCode(blob[blob.l++]);
		return o;
	}

	function parse_SHEETINFOQP(blob, length, opts) {
		if(!opts.qpro || length < 21) return;
		var id = blob.read_shift(1);
		blob.l += 17;
		blob.l += 1; //var len = blob.read_shift(1);
		blob.l += 2;
		var nm = blob.read_shift(length - 21, 'cstr');
		return [id, nm];
	}

	function parse_XFORMAT(blob, length) {
		var o = {}, tgt = blob.l + length;
		while(blob.l < tgt) {
			var dt = blob.read_shift(2);
			if(dt == 0x36b0) {
				o[dt] = [0, ""];
				o[dt][0] = blob.read_shift(2);
				while(blob[blob.l]) { o[dt][1] += String.fromCharCode(blob[blob.l]); blob.l++; } blob.l++;
			}
			// TODO: 0x3a99 ??
		}
		return o;
	}
	function write_XFORMAT_SHEETNAME(name, wsidx) {
		var out = new_buf(5 + name.length);
		out.write_shift(2, 0x36b0);
		out.write_shift(2, wsidx);
		for(var i = 0; i < name.length; ++i) {
			var cc = name.charCodeAt(i);
			out[out.l++] = cc > 0x7F ? 0x5F : cc;
		}
		out[out.l++] = 0;
		return out;
	}

	var WK1Enum = {
		/*::[*/0x0000/*::]*/: { n:"BOF", f:parseuint16 },
		/*::[*/0x0001/*::]*/: { n:"EOF" },
		/*::[*/0x0002/*::]*/: { n:"CALCMODE" },
		/*::[*/0x0003/*::]*/: { n:"CALCORDER" },
		/*::[*/0x0004/*::]*/: { n:"SPLIT" },
		/*::[*/0x0005/*::]*/: { n:"SYNC" },
		/*::[*/0x0006/*::]*/: { n:"RANGE", f:parse_RANGE },
		/*::[*/0x0007/*::]*/: { n:"WINDOW1" },
		/*::[*/0x0008/*::]*/: { n:"COLW1" },
		/*::[*/0x0009/*::]*/: { n:"WINTWO" },
		/*::[*/0x000A/*::]*/: { n:"COLW2" },
		/*::[*/0x000B/*::]*/: { n:"NAME" },
		/*::[*/0x000C/*::]*/: { n:"BLANK" },
		/*::[*/0x000D/*::]*/: { n:"INTEGER", f:parse_INTEGER },
		/*::[*/0x000E/*::]*/: { n:"NUMBER", f:parse_NUMBER },
		/*::[*/0x000F/*::]*/: { n:"LABEL", f:parse_LABEL },
		/*::[*/0x0010/*::]*/: { n:"FORMULA", f:parse_FORMULA },
		/*::[*/0x0018/*::]*/: { n:"TABLE" },
		/*::[*/0x0019/*::]*/: { n:"ORANGE" },
		/*::[*/0x001A/*::]*/: { n:"PRANGE" },
		/*::[*/0x001B/*::]*/: { n:"SRANGE" },
		/*::[*/0x001C/*::]*/: { n:"FRANGE" },
		/*::[*/0x001D/*::]*/: { n:"KRANGE1" },
		/*::[*/0x0020/*::]*/: { n:"HRANGE" },
		/*::[*/0x0023/*::]*/: { n:"KRANGE2" },
		/*::[*/0x0024/*::]*/: { n:"PROTEC" },
		/*::[*/0x0025/*::]*/: { n:"FOOTER" },
		/*::[*/0x0026/*::]*/: { n:"HEADER" },
		/*::[*/0x0027/*::]*/: { n:"SETUP" },
		/*::[*/0x0028/*::]*/: { n:"MARGINS" },
		/*::[*/0x0029/*::]*/: { n:"LABELFMT" },
		/*::[*/0x002A/*::]*/: { n:"TITLES" },
		/*::[*/0x002B/*::]*/: { n:"SHEETJS" },
		/*::[*/0x002D/*::]*/: { n:"GRAPH" },
		/*::[*/0x002E/*::]*/: { n:"NGRAPH" },
		/*::[*/0x002F/*::]*/: { n:"CALCCOUNT" },
		/*::[*/0x0030/*::]*/: { n:"UNFORMATTED" },
		/*::[*/0x0031/*::]*/: { n:"CURSORW12" },
		/*::[*/0x0032/*::]*/: { n:"WINDOW" },
		/*::[*/0x0033/*::]*/: { n:"STRING", f:parse_LABEL },
		/*::[*/0x0037/*::]*/: { n:"PASSWORD" },
		/*::[*/0x0038/*::]*/: { n:"LOCKED" },
		/*::[*/0x003C/*::]*/: { n:"QUERY" },
		/*::[*/0x003D/*::]*/: { n:"QUERYNAME" },
		/*::[*/0x003E/*::]*/: { n:"PRINT" },
		/*::[*/0x003F/*::]*/: { n:"PRINTNAME" },
		/*::[*/0x0040/*::]*/: { n:"GRAPH2" },
		/*::[*/0x0041/*::]*/: { n:"GRAPHNAME" },
		/*::[*/0x0042/*::]*/: { n:"ZOOM" },
		/*::[*/0x0043/*::]*/: { n:"SYMSPLIT" },
		/*::[*/0x0044/*::]*/: { n:"NSROWS" },
		/*::[*/0x0045/*::]*/: { n:"NSCOLS" },
		/*::[*/0x0046/*::]*/: { n:"RULER" },
		/*::[*/0x0047/*::]*/: { n:"NNAME" },
		/*::[*/0x0048/*::]*/: { n:"ACOMM" },
		/*::[*/0x0049/*::]*/: { n:"AMACRO" },
		/*::[*/0x004A/*::]*/: { n:"PARSE" },
		/*::[*/0x0066/*::]*/: { n:"PRANGES??" },
		/*::[*/0x0067/*::]*/: { n:"RRANGES??" },
		/*::[*/0x0068/*::]*/: { n:"FNAME??" },
		/*::[*/0x0069/*::]*/: { n:"MRANGES??" },
		/*::[*/0x00CC/*::]*/: { n:"SHEETNAMECS", f:parse_SHEETNAMECS },
		/*::[*/0x00DE/*::]*/: { n:"SHEETNAMELP", f:parse_SHEETNAMELP },
		/*::[*/0xFFFF/*::]*/: { n:"" }
	};

	var WK3Enum = {
		/*::[*/0x0000/*::]*/: { n:"BOF" },
		/*::[*/0x0001/*::]*/: { n:"EOF" },
		/*::[*/0x0002/*::]*/: { n:"PASSWORD" },
		/*::[*/0x0003/*::]*/: { n:"CALCSET" },
		/*::[*/0x0004/*::]*/: { n:"WINDOWSET" },
		/*::[*/0x0005/*::]*/: { n:"SHEETCELLPTR" },
		/*::[*/0x0006/*::]*/: { n:"SHEETLAYOUT" },
		/*::[*/0x0007/*::]*/: { n:"COLUMNWIDTH" },
		/*::[*/0x0008/*::]*/: { n:"HIDDENCOLUMN" },
		/*::[*/0x0009/*::]*/: { n:"USERRANGE" },
		/*::[*/0x000A/*::]*/: { n:"SYSTEMRANGE" },
		/*::[*/0x000B/*::]*/: { n:"ZEROFORCE" },
		/*::[*/0x000C/*::]*/: { n:"SORTKEYDIR" },
		/*::[*/0x000D/*::]*/: { n:"FILESEAL" },
		/*::[*/0x000E/*::]*/: { n:"DATAFILLNUMS" },
		/*::[*/0x000F/*::]*/: { n:"PRINTMAIN" },
		/*::[*/0x0010/*::]*/: { n:"PRINTSTRING" },
		/*::[*/0x0011/*::]*/: { n:"GRAPHMAIN" },
		/*::[*/0x0012/*::]*/: { n:"GRAPHSTRING" },
		/*::[*/0x0013/*::]*/: { n:"??" },
		/*::[*/0x0014/*::]*/: { n:"ERRCELL" },
		/*::[*/0x0015/*::]*/: { n:"NACELL" },
		/*::[*/0x0016/*::]*/: { n:"LABEL16", f:parse_LABEL_16},
		/*::[*/0x0017/*::]*/: { n:"NUMBER17", f:parse_NUMBER_17 },
		/*::[*/0x0018/*::]*/: { n:"NUMBER18", f:parse_NUMBER_18 },
		/*::[*/0x0019/*::]*/: { n:"FORMULA19", f:parse_FORMULA_19},
		/*::[*/0x001A/*::]*/: { n:"FORMULA1A" },
		/*::[*/0x001B/*::]*/: { n:"XFORMAT", f:parse_XFORMAT },
		/*::[*/0x001C/*::]*/: { n:"DTLABELMISC" },
		/*::[*/0x001D/*::]*/: { n:"DTLABELCELL" },
		/*::[*/0x001E/*::]*/: { n:"GRAPHWINDOW" },
		/*::[*/0x001F/*::]*/: { n:"CPA" },
		/*::[*/0x0020/*::]*/: { n:"LPLAUTO" },
		/*::[*/0x0021/*::]*/: { n:"QUERY" },
		/*::[*/0x0022/*::]*/: { n:"HIDDENSHEET" },
		/*::[*/0x0023/*::]*/: { n:"??" },
		/*::[*/0x0025/*::]*/: { n:"NUMBER25", f:parse_NUMBER_25 },
		/*::[*/0x0026/*::]*/: { n:"??" },
		/*::[*/0x0027/*::]*/: { n:"NUMBER27", f:parse_NUMBER_27 },
		/*::[*/0x0028/*::]*/: { n:"FORMULA28", f:parse_FORMULA_28 },
		/*::[*/0x008E/*::]*/: { n:"??" },
		/*::[*/0x0093/*::]*/: { n:"??" },
		/*::[*/0x0096/*::]*/: { n:"??" },
		/*::[*/0x0097/*::]*/: { n:"??" },
		/*::[*/0x0098/*::]*/: { n:"??" },
		/*::[*/0x0099/*::]*/: { n:"??" },
		/*::[*/0x009A/*::]*/: { n:"??" },
		/*::[*/0x009B/*::]*/: { n:"??" },
		/*::[*/0x009C/*::]*/: { n:"??" },
		/*::[*/0x00A3/*::]*/: { n:"??" },
		/*::[*/0x00AE/*::]*/: { n:"??" },
		/*::[*/0x00AF/*::]*/: { n:"??" },
		/*::[*/0x00B0/*::]*/: { n:"??" },
		/*::[*/0x00B1/*::]*/: { n:"??" },
		/*::[*/0x00B8/*::]*/: { n:"??" },
		/*::[*/0x00B9/*::]*/: { n:"??" },
		/*::[*/0x00BA/*::]*/: { n:"??" },
		/*::[*/0x00BB/*::]*/: { n:"??" },
		/*::[*/0x00BC/*::]*/: { n:"??" },
		/*::[*/0x00C3/*::]*/: { n:"??" },
		/*::[*/0x00C9/*::]*/: { n:"??" },
		/*::[*/0x00CC/*::]*/: { n:"SHEETNAMECS", f:parse_SHEETNAMECS },
		/*::[*/0x00CD/*::]*/: { n:"??" },
		/*::[*/0x00CE/*::]*/: { n:"??" },
		/*::[*/0x00CF/*::]*/: { n:"??" },
		/*::[*/0x00D0/*::]*/: { n:"??" },
		/*::[*/0x0100/*::]*/: { n:"??" },
		/*::[*/0x0103/*::]*/: { n:"??" },
		/*::[*/0x0104/*::]*/: { n:"??" },
		/*::[*/0x0105/*::]*/: { n:"??" },
		/*::[*/0x0106/*::]*/: { n:"??" },
		/*::[*/0x0107/*::]*/: { n:"??" },
		/*::[*/0x0109/*::]*/: { n:"??" },
		/*::[*/0x010A/*::]*/: { n:"??" },
		/*::[*/0x010B/*::]*/: { n:"??" },
		/*::[*/0x010C/*::]*/: { n:"??" },
		/*::[*/0x010E/*::]*/: { n:"??" },
		/*::[*/0x010F/*::]*/: { n:"??" },
		/*::[*/0x0180/*::]*/: { n:"??" },
		/*::[*/0x0185/*::]*/: { n:"??" },
		/*::[*/0x0186/*::]*/: { n:"??" },
		/*::[*/0x0189/*::]*/: { n:"??" },
		/*::[*/0x018C/*::]*/: { n:"??" },
		/*::[*/0x0200/*::]*/: { n:"??" },
		/*::[*/0x0202/*::]*/: { n:"??" },
		/*::[*/0x0201/*::]*/: { n:"??" },
		/*::[*/0x0204/*::]*/: { n:"??" },
		/*::[*/0x0205/*::]*/: { n:"??" },
		/*::[*/0x0280/*::]*/: { n:"??" },
		/*::[*/0x0281/*::]*/: { n:"??" },
		/*::[*/0x0282/*::]*/: { n:"??" },
		/*::[*/0x0283/*::]*/: { n:"??" },
		/*::[*/0x0284/*::]*/: { n:"??" },
		/*::[*/0x0285/*::]*/: { n:"??" },
		/*::[*/0x0286/*::]*/: { n:"??" },
		/*::[*/0x0287/*::]*/: { n:"??" },
		/*::[*/0x0288/*::]*/: { n:"??" },
		/*::[*/0x0292/*::]*/: { n:"??" },
		/*::[*/0x0293/*::]*/: { n:"??" },
		/*::[*/0x0294/*::]*/: { n:"??" },
		/*::[*/0x0295/*::]*/: { n:"??" },
		/*::[*/0x0296/*::]*/: { n:"??" },
		/*::[*/0x0299/*::]*/: { n:"??" },
		/*::[*/0x029A/*::]*/: { n:"??" },
		/*::[*/0x0300/*::]*/: { n:"??" },
		/*::[*/0x0304/*::]*/: { n:"??" },
		/*::[*/0x0601/*::]*/: { n:"SHEETINFOQP", f:parse_SHEETINFOQP },
		/*::[*/0x0640/*::]*/: { n:"??" },
		/*::[*/0x0642/*::]*/: { n:"??" },
		/*::[*/0x0701/*::]*/: { n:"??" },
		/*::[*/0x0702/*::]*/: { n:"??" },
		/*::[*/0x0703/*::]*/: { n:"??" },
		/*::[*/0x0704/*::]*/: { n:"??" },
		/*::[*/0x0780/*::]*/: { n:"??" },
		/*::[*/0x0800/*::]*/: { n:"??" },
		/*::[*/0x0801/*::]*/: { n:"??" },
		/*::[*/0x0804/*::]*/: { n:"??" },
		/*::[*/0x0A80/*::]*/: { n:"??" },
		/*::[*/0x2AF6/*::]*/: { n:"??" },
		/*::[*/0x3231/*::]*/: { n:"??" },
		/*::[*/0x6E49/*::]*/: { n:"??" },
		/*::[*/0x6F44/*::]*/: { n:"??" },
		/*::[*/0xFFFF/*::]*/: { n:"" }
	};
	return {
		sheet_to_wk1: sheet_to_wk1,
		book_to_wk3: book_to_wk3,
		to_workbook: lotus_to_workbook
	};
})();
/* 18.4.7 rPr CT_RPrElt */
function parse_rpr(rpr) {
	var font = {}, m = rpr.match(tagregex), i = 0;
	var pass = false;
	if(m) for(;i!=m.length; ++i) {
		var y = parsexmltag(m[i]);
		switch(y[0].replace(/\w*:/g,"")) {
			/* 18.8.12 condense CT_BooleanProperty */
			/* ** not required . */
			case '<condense': break;
			/* 18.8.17 extend CT_BooleanProperty */
			/* ** not required . */
			case '<extend': break;
			/* 18.8.36 shadow CT_BooleanProperty */
			/* ** not required . */
			case '<shadow':
				if(!y.val) break;
				/* falls through */
			case '<shadow>':
			case '<shadow/>': font.shadow = 1; break;
			case '</shadow>': break;

			/* 18.4.1 charset CT_IntProperty TODO */
			case '<charset':
				if(y.val == '1') break;
				font.cp = CS2CP[parseInt(y.val, 10)];
				break;

			/* 18.4.2 outline CT_BooleanProperty TODO */
			case '<outline':
				if(!y.val) break;
				/* falls through */
			case '<outline>':
			case '<outline/>': font.outline = 1; break;
			case '</outline>': break;

			/* 18.4.5 rFont CT_FontName */
			case '<rFont': font.name = y.val; break;

			/* 18.4.11 sz CT_FontSize */
			case '<sz': font.sz = y.val; break;

			/* 18.4.10 strike CT_BooleanProperty */
			case '<strike':
				if(!y.val) break;
				/* falls through */
			case '<strike>':
			case '<strike/>': font.strike = 1; break;
			case '</strike>': break;

			/* 18.4.13 u CT_UnderlineProperty */
			case '<u':
				if(!y.val) break;
				switch(y.val) {
					case 'double': font.uval = "double"; break;
					case 'singleAccounting': font.uval = "single-accounting"; break;
					case 'doubleAccounting': font.uval = "double-accounting"; break;
				}
				/* falls through */
			case '<u>':
			case '<u/>': font.u = 1; break;
			case '</u>': break;

			/* 18.8.2 b */
			case '<b':
				if(y.val == '0') break;
				/* falls through */
			case '<b>':
			case '<b/>': font.b = 1; break;
			case '</b>': break;

			/* 18.8.26 i */
			case '<i':
				if(y.val == '0') break;
				/* falls through */
			case '<i>':
			case '<i/>': font.i = 1; break;
			case '</i>': break;

			/* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */
			case '<color':
				if(y.rgb) font.color = y.rgb.slice(2,8);
				break;
			case '<color>': case '<color/>': case '</color>': break;

			/* 18.8.18 family ST_FontFamily */
			case '<family': font.family = y.val; break;
			case '<family>': case '<family/>': case '</family>': break;

			/* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */
			case '<vertAlign': font.valign = y.val; break;
			case '<vertAlign>': case '<vertAlign/>': case '</vertAlign>': break;

			/* 18.8.35 scheme CT_FontScheme TODO */
			case '<scheme': break;
			case '<scheme>': case '<scheme/>': case '</scheme>': break;

			/* 18.2.10 extLst CT_ExtensionList ? */
			case '<extLst': case '<extLst>': case '</extLst>': break;
			case '<ext': pass = true; break;
			case '</ext>': pass = false; break;
			default:
				if(y[0].charCodeAt(1) !== 47 && !pass) throw new Error('Unrecognized rich format ' + y[0]);
		}
	}
	return font;
}

var parse_rs = /*#__PURE__*/(function() {
	var tregex = matchtag("t"), rpregex = matchtag("rPr");
	/* 18.4.4 r CT_RElt */
	function parse_r(r) {
		/* 18.4.12 t ST_Xstring */
		var t = r.match(tregex)/*, cp = 65001*/;
		if(!t) return {t:"s", v:""};

		var o/*:Cell*/ = ({t:'s', v:unescapexml(t[1])}/*:any*/);
		var rpr = r.match(rpregex);
		if(rpr) o.s = parse_rpr(rpr[1]);
		return o;
	}
	var rregex = /<(?:\w+:)?r>/g, rend = /<\/(?:\w+:)?r>/;
	return function parse_rs(rs) {
		return rs.replace(rregex,"").split(rend).map(parse_r).filter(function(r) { return r.v; });
	};
})();


/* Parse a list of <r> tags */
var rs_to_html = /*#__PURE__*/(function parse_rs_factory() {
	var nlregex = /(\r\n|\n)/g;
	function parse_rpr2(font, intro, outro) {
		var style/*:Array<string>*/ = [];

		if(font.u) style.push("text-decoration: underline;");
		if(font.uval) style.push("text-underline-style:" + font.uval + ";");
		if(font.sz) style.push("font-size:" + font.sz + "pt;");
		if(font.outline) style.push("text-effect: outline;");
		if(font.shadow) style.push("text-shadow: auto;");
		intro.push('<span style="' + style.join("") + '">');

		if(font.b) { intro.push("<b>"); outro.push("</b>"); }
		if(font.i) { intro.push("<i>"); outro.push("</i>"); }
		if(font.strike) { intro.push("<s>"); outro.push("</s>"); }

		var align = font.valign || "";
		if(align == "superscript" || align == "super") align = "sup";
		else if(align == "subscript") align = "sub";
		if(align != "") { intro.push("<" + align + ">"); outro.push("</" + align + ">"); }

		outro.push("</span>");
		return font;
	}

	/* 18.4.4 r CT_RElt */
	function r_to_html(r) {
		var terms/*:[Array<string>, string, Array<string>]*/ = [[],r.v,[]];
		if(!r.v) return "";

		if(r.s) parse_rpr2(r.s, terms[0], terms[2]);

		return terms[0].join("") + terms[1].replace(nlregex,'<br/>') + terms[2].join("");
	}

	return function parse_rs(rs) {
		return rs.map(r_to_html).join("");
	};
})();

/* 18.4.8 si CT_Rst */
var sitregex = /<(?:\w+:)?t[^>]*>([^<]*)<\/(?:\w+:)?t>/g, sirregex = /<(?:\w+:)?r>/;
var sirphregex = /<(?:\w+:)?rPh.*?>([\s\S]*?)<\/(?:\w+:)?rPh>/g;
function parse_si(x, opts) {
	var html = opts ? opts.cellHTML : true;
	var z = {};
	if(!x) return { t: "" };
	//var y;
	/* 18.4.12 t ST_Xstring (Plaintext String) */
	// TODO: is whitespace actually valid here?
	if(x.match(/^\s*<(?:\w+:)?t[^>]*>/)) {
		z.t = unescapexml(utf8read(x.slice(x.indexOf(">")+1).split(/<\/(?:\w+:)?t>/)[0]||""));
		z.r = utf8read(x);
		if(html) z.h = escapehtml(z.t);
	}
	/* 18.4.4 r CT_RElt (Rich Text Run) */
	else if((/*y = */x.match(sirregex))) {
		z.r = utf8read(x);
		z.t = unescapexml(utf8read((x.replace(sirphregex, '').match(sitregex)||[]).join("").replace(tagregex,"")));
		if(html) z.h = rs_to_html(parse_rs(z.r));
	}
	/* 18.4.3 phoneticPr CT_PhoneticPr (TODO: needed for Asian support) */
	/* 18.4.6 rPh CT_PhoneticRun (TODO: needed for Asian support) */
	return z;
}

/* 18.4 Shared String Table */
var sstr0 = /<(?:\w+:)?sst([^>]*)>([\s\S]*)<\/(?:\w+:)?sst>/;
var sstr1 = /<(?:\w+:)?(?:si|sstItem)>/g;
var sstr2 = /<\/(?:\w+:)?(?:si|sstItem)>/;
function parse_sst_xml(data/*:string*/, opts)/*:SST*/ {
	var s/*:SST*/ = ([]/*:any*/), ss = "";
	if(!data) return s;
	/* 18.4.9 sst CT_Sst */
	var sst = data.match(sstr0);
	if(sst) {
		ss = sst[2].replace(sstr1,"").split(sstr2);
		for(var i = 0; i != ss.length; ++i) {
			var o = parse_si(ss[i].trim(), opts);
			if(o != null) s[s.length] = o;
		}
		sst = parsexmltag(sst[1]); s.Count = sst.count; s.Unique = sst.uniqueCount;
	}
	return s;
}

var straywsregex = /^\s|\s$|[\t\n\r]/;
function write_sst_xml(sst/*:SST*/, opts)/*:string*/ {
	if(!opts.bookSST) return "";
	var o = [XML_HEADER];
	o[o.length] = (writextag('sst', null, {
		xmlns: XMLNS_main[0],
		count: sst.Count,
		uniqueCount: sst.Unique
	}));
	for(var i = 0; i != sst.length; ++i) { if(sst[i] == null) continue;
		var s/*:XLString*/ = sst[i];
		var sitag = "<si>";
		if(s.r) sitag += s.r;
		else {
			sitag += "<t";
			if(!s.t) s.t = "";
			if(s.t.match(straywsregex)) sitag += ' xml:space="preserve"';
			sitag += ">" + escapexml(s.t) + "</t>";
		}
		sitag += "</si>";
		o[o.length] = (sitag);
	}
	if(o.length>2){ o[o.length] = ('</sst>'); o[1]=o[1].replace("/>",">"); }
	return o.join("");
}
/* [MS-XLSB] 2.4.221 BrtBeginSst */
function parse_BrtBeginSst(data) {
	return [data.read_shift(4), data.read_shift(4)];
}

/* [MS-XLSB] 2.1.7.45 Shared Strings */
function parse_sst_bin(data, opts)/*:SST*/ {
	var s/*:SST*/ = ([]/*:any*/);
	var pass = false;
	recordhopper(data, function hopper_sst(val, R, RT) {
		switch(RT) {
			case 0x009F: /* BrtBeginSst */
				s.Count = val[0]; s.Unique = val[1]; break;
			case 0x0013: /* BrtSSTItem */
				s.push(val); break;
			case 0x00A0: /* BrtEndSst */
				return true;

			case 0x0023: /* BrtFRTBegin */
				pass = true; break;
			case 0x0024: /* BrtFRTEnd */
				pass = false; break;

			default:
				if(R.T){}
				if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
		}
	});
	return s;
}

function write_BrtBeginSst(sst, o) {
	if(!o) o = new_buf(8);
	o.write_shift(4, sst.Count);
	o.write_shift(4, sst.Unique);
	return o;
}

var write_BrtSSTItem = write_RichStr;

function write_sst_bin(sst/*::, opts*/) {
	var ba = buf_array();
	write_record(ba, 0x009F /* BrtBeginSst */, write_BrtBeginSst(sst));
	for(var i = 0; i < sst.length; ++i) write_record(ba, 0x0013 /* BrtSSTItem */, write_BrtSSTItem(sst[i]));
	/* FRTSST */
	write_record(ba, 0x00A0 /* BrtEndSst */);
	return ba.end();
}
function _JS2ANSI(str/*:string*/)/*:Array<number>*/ {
	if(typeof $cptable !== 'undefined') return $cptable.utils.encode(current_ansi, str);
	var o/*:Array<number>*/ = [], oo = str.split("");
	for(var i = 0; i < oo.length; ++i) o[i] = oo[i].charCodeAt(0);
	return o;
}

/* [MS-OFFCRYPTO] 2.1.4 Version */
function parse_CRYPTOVersion(blob, length/*:?number*/) {
	var o/*:any*/ = {};
	o.Major = blob.read_shift(2);
	o.Minor = blob.read_shift(2);
	/*:: if(length == null) return o; */
	if(length >= 4) blob.l += length - 4;
	return o;
}

/* [MS-OFFCRYPTO] 2.1.5 DataSpaceVersionInfo */
function parse_DataSpaceVersionInfo(blob) {
	var o = {};
	o.id = blob.read_shift(0, 'lpp4');
	o.R = parse_CRYPTOVersion(blob, 4);
	o.U = parse_CRYPTOVersion(blob, 4);
	o.W = parse_CRYPTOVersion(blob, 4);
	return o;
}

/* [MS-OFFCRYPTO] 2.1.6.1 DataSpaceMapEntry Structure */
function parse_DataSpaceMapEntry(blob) {
	var len = blob.read_shift(4);
	var end = blob.l + len - 4;
	var o = {};
	var cnt = blob.read_shift(4);
	var comps/*:Array<{t:number, v:string}>*/ = [];
	/* [MS-OFFCRYPTO] 2.1.6.2 DataSpaceReferenceComponent Structure */
	while(cnt-- > 0) comps.push({ t: blob.read_shift(4), v: blob.read_shift(0, 'lpp4') });
	o.name = blob.read_shift(0, 'lpp4');
	o.comps = comps;
	if(blob.l != end) throw new Error("Bad DataSpaceMapEntry: " + blob.l + " != " + end);
	return o;
}

/* [MS-OFFCRYPTO] 2.1.6 DataSpaceMap */
function parse_DataSpaceMap(blob) {
	var o = [];
	blob.l += 4; // must be 0x8
	var cnt = blob.read_shift(4);
	while(cnt-- > 0) o.push(parse_DataSpaceMapEntry(blob));
	return o;
}

/* [MS-OFFCRYPTO] 2.1.7 DataSpaceDefinition */
function parse_DataSpaceDefinition(blob)/*:Array<string>*/ {
	var o/*:Array<string>*/ = [];
	blob.l += 4; // must be 0x8
	var cnt = blob.read_shift(4);
	while(cnt-- > 0) o.push(blob.read_shift(0, 'lpp4'));
	return o;
}

/* [MS-OFFCRYPTO] 2.1.8 DataSpaceDefinition */
function parse_TransformInfoHeader(blob) {
	var o = {};
	/*var len = */blob.read_shift(4);
	blob.l += 4; // must be 0x1
	o.id = blob.read_shift(0, 'lpp4');
	o.name = blob.read_shift(0, 'lpp4');
	o.R = parse_CRYPTOVersion(blob, 4);
	o.U = parse_CRYPTOVersion(blob, 4);
	o.W = parse_CRYPTOVersion(blob, 4);
	return o;
}

function parse_Primary(blob) {
	/* [MS-OFFCRYPTO] 2.2.6 IRMDSTransformInfo */
	var hdr = parse_TransformInfoHeader(blob);
	/* [MS-OFFCRYPTO] 2.1.9 EncryptionTransformInfo */
	hdr.ename = blob.read_shift(0, '8lpp4');
	hdr.blksz = blob.read_shift(4);
	hdr.cmode = blob.read_shift(4);
	if(blob.read_shift(4) != 0x04) throw new Error("Bad !Primary record");
	return hdr;
}

/* [MS-OFFCRYPTO] 2.3.2 Encryption Header */
function parse_EncryptionHeader(blob, length/*:number*/) {
	var tgt = blob.l + length;
	var o = {};
	o.Flags = (blob.read_shift(4) & 0x3F);
	blob.l += 4;
	o.AlgID = blob.read_shift(4);
	var valid = false;
	switch(o.AlgID) {
		case 0x660E: case 0x660F: case 0x6610: valid = (o.Flags == 0x24); break;
		case 0x6801: valid = (o.Flags == 0x04); break;
		case 0: valid = (o.Flags == 0x10 || o.Flags == 0x04 || o.Flags == 0x24); break;
		default: throw 'Unrecognized encryption algorithm: ' + o.AlgID;
	}
	if(!valid) throw new Error("Encryption Flags/AlgID mismatch");
	o.AlgIDHash = blob.read_shift(4);
	o.KeySize = blob.read_shift(4);
	o.ProviderType = blob.read_shift(4);
	blob.l += 8;
	o.CSPName = blob.read_shift((tgt-blob.l)>>1, 'utf16le');
	blob.l = tgt;
	return o;
}

/* [MS-OFFCRYPTO] 2.3.3 Encryption Verifier */
function parse_EncryptionVerifier(blob, length/*:number*/) {
	var o = {}, tgt = blob.l + length;
	blob.l += 4; // SaltSize must be 0x10
	o.Salt = blob.slice(blob.l, blob.l+16); blob.l += 16;
	o.Verifier = blob.slice(blob.l, blob.l+16); blob.l += 16;
	/*var sz = */blob.read_shift(4);
	o.VerifierHash = blob.slice(blob.l, tgt); blob.l = tgt;
	return o;
}

/* [MS-OFFCRYPTO] 2.3.4.* EncryptionInfo Stream */
function parse_EncryptionInfo(blob) {
	var vers = parse_CRYPTOVersion(blob);
	switch(vers.Minor) {
		case 0x02: return [vers.Minor, parse_EncInfoStd(blob, vers)];
		case 0x03: return [vers.Minor, parse_EncInfoExt(blob, vers)];
		case 0x04: return [vers.Minor, parse_EncInfoAgl(blob, vers)];
	}
	throw new Error("ECMA-376 Encrypted file unrecognized Version: " + vers.Minor);
}

/* [MS-OFFCRYPTO] 2.3.4.5  EncryptionInfo Stream (Standard Encryption) */
function parse_EncInfoStd(blob/*::, vers*/) {
	var flags = blob.read_shift(4);
	if((flags & 0x3F) != 0x24) throw new Error("EncryptionInfo mismatch");
	var sz = blob.read_shift(4);
	//var tgt = blob.l + sz;
	var hdr = parse_EncryptionHeader(blob, sz);
	var verifier = parse_EncryptionVerifier(blob, blob.length - blob.l);
	return { t:"Std", h:hdr, v:verifier };
}
/* [MS-OFFCRYPTO] 2.3.4.6  EncryptionInfo Stream (Extensible Encryption) */
function parse_EncInfoExt(/*::blob, vers*/) { throw new Error("File is password-protected: ECMA-376 Extensible"); }
/* [MS-OFFCRYPTO] 2.3.4.10 EncryptionInfo Stream (Agile Encryption) */
function parse_EncInfoAgl(blob/*::, vers*/) {
	var KeyData = ["saltSize","blockSize","keyBits","hashSize","cipherAlgorithm","cipherChaining","hashAlgorithm","saltValue"];
	blob.l+=4;
	var xml = blob.read_shift(blob.length - blob.l, 'utf8');
	var o = {};
	xml.replace(tagregex, function xml_agile(x) {
		var y/*:any*/ = parsexmltag(x);
		switch(strip_ns(y[0])) {
			case '<?xml': break;
			case '<encryption': case '</encryption>': break;
			case '<keyData': KeyData.forEach(function(k) { o[k] = y[k]; }); break;
			case '<dataIntegrity': o.encryptedHmacKey = y.encryptedHmacKey; o.encryptedHmacValue = y.encryptedHmacValue; break;
			case '<keyEncryptors>': case '<keyEncryptors': o.encs = []; break;
			case '</keyEncryptors>': break;

			case '<keyEncryptor': o.uri = y.uri; break;
			case '</keyEncryptor>': break;
			case '<encryptedKey': o.encs.push(y); break;
			default: throw y[0];
		}
	});
	return o;
}

/* [MS-OFFCRYPTO] 2.3.5.1 RC4 CryptoAPI Encryption Header */
function parse_RC4CryptoHeader(blob, length/*:number*/) {
	var o = {};
	var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4); length -= 4;
	if(vers.Minor != 2) throw new Error('unrecognized minor version code: ' + vers.Minor);
	if(vers.Major > 4 || vers.Major < 2) throw new Error('unrecognized major version code: ' + vers.Major);
	o.Flags = blob.read_shift(4); length -= 4;
	var sz = blob.read_shift(4); length -= 4;
	o.EncryptionHeader = parse_EncryptionHeader(blob, sz); length -= sz;
	o.EncryptionVerifier = parse_EncryptionVerifier(blob, length);
	return o;
}
/* [MS-OFFCRYPTO] 2.3.6.1 RC4 Encryption Header */
function parse_RC4Header(blob/*::, length*/) {
	var o = {};
	var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4);
	if(vers.Major != 1 || vers.Minor != 1) throw 'unrecognized version code ' + vers.Major + ' : ' + vers.Minor;
	o.Salt = blob.read_shift(16);
	o.EncryptedVerifier = blob.read_shift(16);
	o.EncryptedVerifierHash = blob.read_shift(16);
	return o;
}

/* [MS-OFFCRYPTO] 2.3.7.1 Binary Document Password Verifier Derivation */
function crypto_CreatePasswordVerifier_Method1(Password/*:string*/) {
	var Verifier = 0x0000, PasswordArray;
	var PasswordDecoded = _JS2ANSI(Password);
	var len = PasswordDecoded.length + 1, i, PasswordByte;
	var Intermediate1, Intermediate2, Intermediate3;
	PasswordArray = new_raw_buf(len);
	PasswordArray[0] = PasswordDecoded.length;
	for(i = 1; i != len; ++i) PasswordArray[i] = PasswordDecoded[i-1];
	for(i = len-1; i >= 0; --i) {
		PasswordByte = PasswordArray[i];
		Intermediate1 = ((Verifier & 0x4000) === 0x0000) ? 0 : 1;
		Intermediate2 = (Verifier << 1) & 0x7FFF;
		Intermediate3 = Intermediate1 | Intermediate2;
		Verifier = Intermediate3 ^ PasswordByte;
	}
	return Verifier ^ 0xCE4B;
}

/* [MS-OFFCRYPTO] 2.3.7.2 Binary Document XOR Array Initialization */
var crypto_CreateXorArray_Method1 = /*#__PURE__*/(function() {
	var PadArray = [0xBB, 0xFF, 0xFF, 0xBA, 0xFF, 0xFF, 0xB9, 0x80, 0x00, 0xBE, 0x0F, 0x00, 0xBF, 0x0F, 0x00];
	var InitialCode = [0xE1F0, 0x1D0F, 0xCC9C, 0x84C0, 0x110C, 0x0E10, 0xF1CE, 0x313E, 0x1872, 0xE139, 0xD40F, 0x84F9, 0x280C, 0xA96A, 0x4EC3];
	var XorMatrix = [0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09, 0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF, 0x4563, 0x8AC6, 0x05AD, 0x0B5A, 0x16B4, 0x2D68, 0x5AD0, 0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40, 0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5, 0x6F45, 0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A, 0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9, 0x47D3, 0x8FA6, 0x0F6D, 0x1EDA, 0x3DB4, 0x7B68, 0xF6D0, 0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC, 0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10, 0xAA51, 0x4483, 0x8906, 0x022D, 0x045A, 0x08B4, 0x1168, 0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C, 0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6, 0x1DAD, 0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC, 0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4];
	var Ror = function(Byte) { return ((Byte/2) | (Byte*128)) & 0xFF; };
	var XorRor = function(byte1, byte2) { return Ror(byte1 ^ byte2); };
	var CreateXorKey_Method1 = function(Password) {
		var XorKey = InitialCode[Password.length - 1];
		var CurrentElement = 0x68;
		for(var i = Password.length-1; i >= 0; --i) {
			var Char = Password[i];
			for(var j = 0; j != 7; ++j) {
				if(Char & 0x40) XorKey ^= XorMatrix[CurrentElement];
				Char *= 2; --CurrentElement;
			}
		}
		return XorKey;
	};
	return function(password/*:string*/) {
		var Password = _JS2ANSI(password);
		var XorKey = CreateXorKey_Method1(Password);
		var Index = Password.length;
		var ObfuscationArray = new_raw_buf(16);
		for(var i = 0; i != 16; ++i) ObfuscationArray[i] = 0x00;
		var Temp, PasswordLastChar, PadIndex;
		if((Index & 1) === 1) {
			Temp = XorKey >> 8;
			ObfuscationArray[Index] = XorRor(PadArray[0], Temp);
			--Index;
			Temp = XorKey & 0xFF;
			PasswordLastChar = Password[Password.length - 1];
			ObfuscationArray[Index] = XorRor(PasswordLastChar, Temp);
		}
		while(Index > 0) {
			--Index;
			Temp = XorKey >> 8;
			ObfuscationArray[Index] = XorRor(Password[Index], Temp);
			--Index;
			Temp = XorKey & 0xFF;
			ObfuscationArray[Index] = XorRor(Password[Index], Temp);
		}
		Index = 15;
		PadIndex = 15 - Password.length;
		while(PadIndex > 0) {
			Temp = XorKey >> 8;
			ObfuscationArray[Index] = XorRor(PadArray[PadIndex], Temp);
			--Index;
			--PadIndex;
			Temp = XorKey & 0xFF;
			ObfuscationArray[Index] = XorRor(Password[Index], Temp);
			--Index;
			--PadIndex;
		}
		return ObfuscationArray;
	};
})();

/* [MS-OFFCRYPTO] 2.3.7.3 Binary Document XOR Data Transformation Method 1 */
var crypto_DecryptData_Method1 = function(password/*:string*/, Data, XorArrayIndex, XorArray, O) {
	/* If XorArray is set, use it; if O is not set, make changes in-place */
	if(!O) O = Data;
	if(!XorArray) XorArray = crypto_CreateXorArray_Method1(password);
	var Index, Value;
	for(Index = 0; Index != Data.length; ++Index) {
		Value = Data[Index];
		Value ^= XorArray[XorArrayIndex];
		Value = ((Value>>5) | (Value<<3)) & 0xFF;
		O[Index] = Value;
		++XorArrayIndex;
	}
	return [O, XorArrayIndex, XorArray];
};

var crypto_MakeXorDecryptor = function(password/*:string*/) {
	var XorArrayIndex = 0, XorArray = crypto_CreateXorArray_Method1(password);
	return function(Data) {
		var O = crypto_DecryptData_Method1("", Data, XorArrayIndex, XorArray);
		XorArrayIndex = O[1];
		return O[0];
	};
};

/* 2.5.343 */
function parse_XORObfuscation(blob, length, opts, out) {
	var o = ({ key: parseuint16(blob), verificationBytes: parseuint16(blob) }/*:any*/);
	if(opts.password) o.verifier = crypto_CreatePasswordVerifier_Method1(opts.password);
	out.valid = o.verificationBytes === o.verifier;
	if(out.valid) out.insitu = crypto_MakeXorDecryptor(opts.password);
	return o;
}

/* 2.4.117 */
function parse_FilePassHeader(blob, length/*:number*/, oo) {
	var o = oo || {}; o.Info = blob.read_shift(2); blob.l -= 2;
	if(o.Info === 1) o.Data = parse_RC4Header(blob, length);
	else o.Data = parse_RC4CryptoHeader(blob, length);
	return o;
}
function parse_FilePass(blob, length/*:number*/, opts) {
	var o = ({ Type: opts.biff >= 8 ? blob.read_shift(2) : 0 }/*:any*/); /* wEncryptionType */
	if(o.Type) parse_FilePassHeader(blob, length-2, o);
	else parse_XORObfuscation(blob, opts.biff >= 8 ? length : length - 2, opts, o);
	return o;
}


var RTF = /*#__PURE__*/(function() {
	function rtf_to_sheet(d/*:RawData*/, opts)/*:Worksheet*/ {
		switch(opts.type) {
			case 'base64': return rtf_to_sheet_str(Base64_decode(d), opts);
			case 'binary': return rtf_to_sheet_str(d, opts);
			case 'buffer': return rtf_to_sheet_str(has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d), opts);
			case 'array':  return rtf_to_sheet_str(cc2str(d), opts);
		}
		throw new Error("Unrecognized type " + opts.type);
	}

	/* TODO: this is a stub */
	function rtf_to_sheet_str(str/*:string*/, opts)/*:Worksheet*/ {
		var o = opts || {};
		var ws/*:Worksheet*/ = o.dense ? ([]/*:any*/) : ({}/*:any*/);

		var rows = str.match(/\\trowd.*?\\row\b/g);
		if(!rows.length) throw new Error("RTF missing table");
		var range/*:Range*/ = ({s: {c:0, r:0}, e: {c:0, r:rows.length - 1}}/*:any*/);
		rows.forEach(function(rowtf, R) {
			if(Array.isArray(ws)) ws[R] = [];
			var rtfre = /\\\w+\b/g;
			var last_index = 0;
			var res;
			var C = -1;
			while((res = rtfre.exec(rowtf))) {
				switch(res[0]) {
					case "\\cell":
						var data = rowtf.slice(last_index, rtfre.lastIndex - res[0].length);
						if(data[0] == " ") data = data.slice(1);
						++C;
						if(data.length) {
							// TODO: value parsing, including codepage adjustments
							var cell = {v: data, t:"s"};
							if(Array.isArray(ws)) ws[R][C] = cell;
							else ws[encode_cell({r:R, c:C})] = cell;
						}
						break;
				}
				last_index = rtfre.lastIndex;
			}
			if(C > range.e.c) range.e.c = C;
		});
		ws['!ref'] = encode_range(range);
		return ws;
	}

	function rtf_to_workbook(d/*:RawData*/, opts)/*:Workbook*/ { return sheet_to_workbook(rtf_to_sheet(d, opts), opts); }

	/* TODO: this is a stub */
	function sheet_to_rtf(ws/*:Worksheet*//*::, opts*/)/*:string*/ {
		var o = ["{\\rtf1\\ansi"];
		var r = safe_decode_range(ws['!ref']), cell/*:Cell*/;
		var dense = Array.isArray(ws);
		for(var R = r.s.r; R <= r.e.r; ++R) {
			o.push("\\trowd\\trautofit1");
			for(var C = r.s.c; C <= r.e.c; ++C) o.push("\\cellx" + (C+1));
			o.push("\\pard\\intbl");
			for(C = r.s.c; C <= r.e.c; ++C) {
				var coord = encode_cell({r:R,c:C});
				cell = dense ? (ws[R]||[])[C]: ws[coord];
				if(!cell || cell.v == null && (!cell.f || cell.F)) continue;
				o.push(" " + (cell.w || (format_cell(cell), cell.w)));
				o.push("\\cell");
			}
			o.push("\\pard\\intbl\\row");
		}
		return o.join("") + "}";
	}

	return {
		to_workbook: rtf_to_workbook,
		to_sheet: rtf_to_sheet,
		from_sheet: sheet_to_rtf
	};
})();
function hex2RGB(h) {
	var o = h.slice(h[0]==="#"?1:0).slice(0,6);
	return [parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)];
}
function rgb2Hex(rgb) {
	for(var i=0,o=1; i!=3; ++i) o = o*256 + (rgb[i]>255?255:rgb[i]<0?0:rgb[i]);
	return o.toString(16).toUpperCase().slice(1);
}

function rgb2HSL(rgb) {
	var R = rgb[0]/255, G = rgb[1]/255, B=rgb[2]/255;
	var M = Math.max(R, G, B), m = Math.min(R, G, B), C = M - m;
	if(C === 0) return [0, 0, R];

	var H6 = 0, S = 0, L2 = (M + m);
	S = C / (L2 > 1 ? 2 - L2 : L2);
	switch(M){
		case R: H6 = ((G - B) / C + 6)%6; break;
		case G: H6 = ((B - R) / C + 2); break;
		case B: H6 = ((R - G) / C + 4); break;
	}
	return [H6 / 6, S, L2 / 2];
}

function hsl2RGB(hsl){
	var H = hsl[0], S = hsl[1], L = hsl[2];
	var C = S * 2 * (L < 0.5 ? L : 1 - L), m = L - C/2;
	var rgb = [m,m,m], h6 = 6*H;

	var X;
	if(S !== 0) switch(h6|0) {
		case 0: case 6: X = C * h6; rgb[0] += C; rgb[1] += X; break;
		case 1: X = C * (2 - h6);   rgb[0] += X; rgb[1] += C; break;
		case 2: X = C * (h6 - 2);   rgb[1] += C; rgb[2] += X; break;
		case 3: X = C * (4 - h6);   rgb[1] += X; rgb[2] += C; break;
		case 4: X = C * (h6 - 4);   rgb[2] += C; rgb[0] += X; break;
		case 5: X = C * (6 - h6);   rgb[2] += X; rgb[0] += C; break;
	}
	for(var i = 0; i != 3; ++i) rgb[i] = Math.round(rgb[i]*255);
	return rgb;
}

/* 18.8.3 bgColor tint algorithm */
function rgb_tint(hex, tint) {
	if(tint === 0) return hex;
	var hsl = rgb2HSL(hex2RGB(hex));
	if (tint < 0) hsl[2] = hsl[2] * (1 + tint);
	else hsl[2] = 1 - (1 - hsl[2]) * (1 - tint);
	return rgb2Hex(hsl2RGB(hsl));
}

/* 18.3.1.13 width calculations */
/* [MS-OI29500] 2.1.595 Column Width & Formatting */
var DEF_MDW = 6, MAX_MDW = 15, MIN_MDW = 1, MDW = DEF_MDW;
function width2px(width) { return Math.floor(( width + (Math.round(128/MDW))/256 )* MDW ); }
function px2char(px) { return (Math.floor((px - 5)/MDW * 100 + 0.5))/100; }
function char2width(chr) { return (Math.round((chr * MDW + 5)/MDW*256))/256; }
//function px2char_(px) { return (((px - 5)/MDW * 100 + 0.5))/100; }
//function char2width_(chr) { return (((chr * MDW + 5)/MDW*256))/256; }
function cycle_width(collw) { return char2width(px2char(width2px(collw))); }
/* XLSX/XLSB/XLS specify width in units of MDW */
function find_mdw_colw(collw) {
	var delta = Math.abs(collw - cycle_width(collw)), _MDW = MDW;
	if(delta > 0.005) for(MDW=MIN_MDW; MDW<MAX_MDW; ++MDW) if(Math.abs(collw - cycle_width(collw)) <= delta) { delta = Math.abs(collw - cycle_width(collw)); _MDW = MDW; }
	MDW = _MDW;
}
/* XLML specifies width in terms of pixels */
/*function find_mdw_wpx(wpx) {
	var delta = Infinity, guess = 0, _MDW = MIN_MDW;
	for(MDW=MIN_MDW; MDW<MAX_MDW; ++MDW) {
		guess = char2width_(px2char_(wpx))*256;
		guess = (guess) % 1;
		if(guess > 0.5) guess--;
		if(Math.abs(guess) < delta) { delta = Math.abs(guess); _MDW = MDW; }
	}
	MDW = _MDW;
}*/

function process_col(coll/*:ColInfo*/) {
	if(coll.width) {
		coll.wpx = width2px(coll.width);
		coll.wch = px2char(coll.wpx);
		coll.MDW = MDW;
	} else if(coll.wpx) {
		coll.wch = px2char(coll.wpx);
		coll.width = char2width(coll.wch);
		coll.MDW = MDW;
	} else if(typeof coll.wch == 'number') {
		coll.width = char2width(coll.wch);
		coll.wpx = width2px(coll.width);
		coll.MDW = MDW;
	}
	if(coll.customWidth) delete coll.customWidth;
}

var DEF_PPI = 96, PPI = DEF_PPI;
function px2pt(px) { return px * 96 / PPI; }
function pt2px(pt) { return pt * PPI / 96; }

/* [MS-EXSPXML3] 2.4.54 ST_enmPattern */
var XLMLPatternTypeMap = {
	"None": "none",
	"Solid": "solid",
	"Gray50": "mediumGray",
	"Gray75": "darkGray",
	"Gray25": "lightGray",
	"HorzStripe": "darkHorizontal",
	"VertStripe": "darkVertical",
	"ReverseDiagStripe": "darkDown",
	"DiagStripe": "darkUp",
	"DiagCross": "darkGrid",
	"ThickDiagCross": "darkTrellis",
	"ThinHorzStripe": "lightHorizontal",
	"ThinVertStripe": "lightVertical",
	"ThinReverseDiagStripe": "lightDown",
	"ThinHorzCross": "lightGrid"
};

/* 18.8.5 borders CT_Borders */
function parse_borders(t, styles, themes, opts) {
	styles.Borders = [];
	var border = {};
	var pass = false;
	(t[0].match(tagregex)||[]).forEach(function(x) {
		var y = parsexmltag(x);
		switch(strip_ns(y[0])) {
			case '<borders': case '<borders>': case '</borders>': break;

			/* 18.8.4 border CT_Border */
			case '<border': case '<border>': case '<border/>':
				border = /*::(*/{}/*:: :any)*/;
				if(y.diagonalUp) border.diagonalUp = parsexmlbool(y.diagonalUp);
				if(y.diagonalDown) border.diagonalDown = parsexmlbool(y.diagonalDown);
				styles.Borders.push(border);
				break;
			case '</border>': break;

			/* note: not in spec, appears to be CT_BorderPr */
			case '<left/>': break;
			case '<left': case '<left>': break;
			case '</left>': break;

			/* note: not in spec, appears to be CT_BorderPr */
			case '<right/>': break;
			case '<right': case '<right>': break;
			case '</right>': break;

			/* 18.8.43 top CT_BorderPr */
			case '<top/>': break;
			case '<top': case '<top>': break;
			case '</top>': break;

			/* 18.8.6 bottom CT_BorderPr */
			case '<bottom/>': break;
			case '<bottom': case '<bottom>': break;
			case '</bottom>': break;

			/* 18.8.13 diagonal CT_BorderPr */
			case '<diagonal': case '<diagonal>': case '<diagonal/>': break;
			case '</diagonal>': break;

			/* 18.8.25 horizontal CT_BorderPr */
			case '<horizontal': case '<horizontal>': case '<horizontal/>': break;
			case '</horizontal>': break;

			/* 18.8.44 vertical CT_BorderPr */
			case '<vertical': case '<vertical>': case '<vertical/>': break;
			case '</vertical>': break;

			/* 18.8.37 start CT_BorderPr */
			case '<start': case '<start>': case '<start/>': break;
			case '</start>': break;

			/* 18.8.16 end CT_BorderPr */
			case '<end': case '<end>': case '<end/>': break;
			case '</end>': break;

			/* 18.8.? color CT_Color */
			case '<color': case '<color>':
				break;
			case '<color/>': case '</color>': break;

			/* 18.2.10 extLst CT_ExtensionList ? */
			case '<extLst': case '<extLst>': case '</extLst>': break;
			case '<ext': pass = true; break;
			case '</ext>': pass = false; break;
			default: if(opts && opts.WTF) {
				if(!pass) throw new Error('unrecognized ' + y[0] + ' in borders');
			}
		}
	});
}

/* 18.8.21 fills CT_Fills */
function parse_fills(t, styles, themes, opts) {
	styles.Fills = [];
	var fill = {};
	var pass = false;
	(t[0].match(tagregex)||[]).forEach(function(x) {
		var y = parsexmltag(x);
		switch(strip_ns(y[0])) {
			case '<fills': case '<fills>': case '</fills>': break;

			/* 18.8.20 fill CT_Fill */
			case '<fill>': case '<fill': case '<fill/>':
				fill = {}; styles.Fills.push(fill); break;
			case '</fill>': break;

			/* 18.8.24 gradientFill CT_GradientFill */
			case '<gradientFill>': break;
			case '<gradientFill':
			case '</gradientFill>': styles.Fills.push(fill); fill = {}; break;

			/* 18.8.32 patternFill CT_PatternFill */
			case '<patternFill': case '<patternFill>':
				if(y.patternType) fill.patternType = y.patternType;
				break;
			case '<patternFill/>': case '</patternFill>': break;

			/* 18.8.3 bgColor CT_Color */
			case '<bgColor':
				if(!fill.bgColor) fill.bgColor = {};
				if(y.indexed) fill.bgColor.indexed = parseInt(y.indexed, 10);
				if(y.theme) fill.bgColor.theme = parseInt(y.theme, 10);
				if(y.tint) fill.bgColor.tint = parseFloat(y.tint);
				/* Excel uses ARGB strings */
				if(y.rgb) fill.bgColor.rgb = y.rgb.slice(-6);
				break;
			case '<bgColor/>': case '</bgColor>': break;

			/* 18.8.19 fgColor CT_Color */
			case '<fgColor':
				if(!fill.fgColor) fill.fgColor = {};
				if(y.theme) fill.fgColor.theme = parseInt(y.theme, 10);
				if(y.tint) fill.fgColor.tint = parseFloat(y.tint);
				/* Excel uses ARGB strings */
				if(y.rgb != null) fill.fgColor.rgb = y.rgb.slice(-6);
				break;
			case '<fgColor/>': case '</fgColor>': break;

			/* 18.8.38 stop CT_GradientStop */
			case '<stop': case '<stop/>': break;
			case '</stop>': break;

			/* 18.8.? color CT_Color */
			case '<color': case '<color/>': break;
			case '</color>': break;

			/* 18.2.10 extLst CT_ExtensionList ? */
			case '<extLst': case '<extLst>': case '</extLst>': break;
			case '<ext': pass = true; break;
			case '</ext>': pass = false; break;
			default: if(opts && opts.WTF) {
				if(!pass) throw new Error('unrecognized ' + y[0] + ' in fills');
			}
		}
	});
}

/* 18.8.23 fonts CT_Fonts */
function parse_fonts(t, styles, themes, opts) {
	styles.Fonts = [];
	var font = {};
	var pass = false;
	(t[0].match(tagregex)||[]).forEach(function(x) {
		var y = parsexmltag(x);
		switch(strip_ns(y[0])) {
			case '<fonts': case '<fonts>': case '</fonts>': break;

			/* 18.8.22 font CT_Font */
			case '<font': case '<font>': break;
			case '</font>': case '<font/>':
				styles.Fonts.push(font);
				font = {};
				break;

			/* 18.8.29 name CT_FontName */
			case '<name': if(y.val) font.name = utf8read(y.val); break;
			case '<name/>': case '</name>': break;

			/* 18.8.2  b CT_BooleanProperty */
			case '<b': font.bold = y.val ? parsexmlbool(y.val) : 1; break;
			case '<b/>': font.bold = 1; break;

			/* 18.8.26 i CT_BooleanProperty */
			case '<i': font.italic = y.val ? parsexmlbool(y.val) : 1; break;
			case '<i/>': font.italic = 1; break;

			/* 18.4.13 u CT_UnderlineProperty */
			case '<u':
				switch(y.val) {
					case "none": font.underline = 0x00; break;
					case "single": font.underline = 0x01; break;
					case "double": font.underline = 0x02; break;
					case "singleAccounting": font.underline = 0x21; break;
					case "doubleAccounting": font.underline = 0x22; break;
				} break;
			case '<u/>': font.underline = 1; break;

			/* 18.4.10 strike CT_BooleanProperty */
			case '<strike': font.strike = y.val ? parsexmlbool(y.val) : 1; break;
			case '<strike/>': font.strike = 1; break;

			/* 18.4.2  outline CT_BooleanProperty */
			case '<outline': font.outline = y.val ? parsexmlbool(y.val) : 1; break;
			case '<outline/>': font.outline = 1; break;

			/* 18.8.36 shadow CT_BooleanProperty */
			case '<shadow': font.shadow = y.val ? parsexmlbool(y.val) : 1; break;
			case '<shadow/>': font.shadow = 1; break;

			/* 18.8.12 condense CT_BooleanProperty */
			case '<condense': font.condense = y.val ? parsexmlbool(y.val) : 1; break;
			case '<condense/>': font.condense = 1; break;

			/* 18.8.17 extend CT_BooleanProperty */
			case '<extend': font.extend = y.val ? parsexmlbool(y.val) : 1; break;
			case '<extend/>': font.extend = 1; break;

			/* 18.4.11 sz CT_FontSize */
			case '<sz': if(y.val) font.sz = +y.val; break;
			case '<sz/>': case '</sz>': break;

			/* 18.4.14 vertAlign CT_VerticalAlignFontProperty */
			case '<vertAlign': if(y.val) font.vertAlign = y.val; break;
			case '<vertAlign/>': case '</vertAlign>': break;

			/* 18.8.18 family CT_FontFamily */
			case '<family': if(y.val) font.family = parseInt(y.val,10); break;
			case '<family/>': case '</family>': break;

			/* 18.8.35 scheme CT_FontScheme */
			case '<scheme': if(y.val) font.scheme = y.val; break;
			case '<scheme/>': case '</scheme>': break;

			/* 18.4.1 charset CT_IntProperty */
			case '<charset':
				if(y.val == '1') break;
				y.codepage = CS2CP[parseInt(y.val, 10)];
				break;

			/* 18.?.? color CT_Color */
			case '<color':
				if(!font.color) font.color = {};
				if(y.auto) font.color.auto = parsexmlbool(y.auto);

				if(y.rgb) font.color.rgb = y.rgb.slice(-6);
				else if(y.indexed) {
					font.color.index = parseInt(y.indexed, 10);
					var icv = XLSIcv[font.color.index];
					if(font.color.index == 81) icv = XLSIcv[1];
					if(!icv) icv = XLSIcv[1]; //throw new Error(x); // note: 206 is valid
					font.color.rgb = icv[0].toString(16) + icv[1].toString(16) + icv[2].toString(16);
				} else if(y.theme) {
					font.color.theme = parseInt(y.theme, 10);
					if(y.tint) font.color.tint = parseFloat(y.tint);
					if(y.theme && themes.themeElements && themes.themeElements.clrScheme) {
						font.color.rgb = rgb_tint(themes.themeElements.clrScheme[font.color.theme].rgb, font.color.tint || 0);
					}
				}

				break;
			case '<color/>': case '</color>': break;

			/* note: sometimes mc:AlternateContent appears bare */
			case '<AlternateContent': pass = true; break;
			case '</AlternateContent>': pass = false; break;

			/* 18.2.10 extLst CT_ExtensionList ? */
			case '<extLst': case '<extLst>': case '</extLst>': break;
			case '<ext': pass = true; break;
			case '</ext>': pass = false; break;
			default: if(opts && opts.WTF) {
				if(!pass) throw new Error('unrecognized ' + y[0] + ' in fonts');
			}
		}
	});
}

/* 18.8.31 numFmts CT_NumFmts */
function parse_numFmts(t, styles, opts) {
	styles.NumberFmt = [];
	var k/*Array<number>*/ = (keys(table_fmt)/*:any*/);
	for(var i=0; i < k.length; ++i) styles.NumberFmt[k[i]] = table_fmt[k[i]];
	var m = t[0].match(tagregex);
	if(!m) return;
	for(i=0; i < m.length; ++i) {
		var y = parsexmltag(m[i]);
		switch(strip_ns(y[0])) {
			case '<numFmts': case '</numFmts>': case '<numFmts/>': case '<numFmts>': break;
			case '<numFmt': {
				var f=unescapexml(utf8read(y.formatCode)), j=parseInt(y.numFmtId,10);
				styles.NumberFmt[j] = f;
				if(j>0) {
					if(j > 0x188) {
						for(j = 0x188; j > 0x3c; --j) if(styles.NumberFmt[j] == null) break;
						styles.NumberFmt[j] = f;
					}
					SSF_load(f,j);
				}
			} break;
			case '</numFmt>': break;
			default: if(opts.WTF) throw new Error('unrecognized ' + y[0] + ' in numFmts');
		}
	}
}

function write_numFmts(NF/*:{[n:number|string]:string}*//*::, opts*/) {
	var o = ["<numFmts>"];
	[[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
		for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) o[o.length] = (writextag('numFmt',null,{numFmtId:i,formatCode:escapexml(NF[i])}));
	});
	if(o.length === 1) return "";
	o[o.length] = ("</numFmts>");
	o[0] = writextag('numFmts', null, { count:o.length-2 }).replace("/>", ">");
	return o.join("");
}

/* 18.8.10 cellXfs CT_CellXfs */
var cellXF_uint = [ "numFmtId", "fillId", "fontId", "borderId", "xfId" ];
var cellXF_bool = [ "applyAlignment", "applyBorder", "applyFill", "applyFont", "applyNumberFormat", "applyProtection", "pivotButton", "quotePrefix" ];
function parse_cellXfs(t, styles, opts) {
	styles.CellXf = [];
	var xf;
	var pass = false;
	(t[0].match(tagregex)||[]).forEach(function(x) {
		var y = parsexmltag(x), i = 0;
		switch(strip_ns(y[0])) {
			case '<cellXfs': case '<cellXfs>': case '<cellXfs/>': case '</cellXfs>': break;

			/* 18.8.45 xf CT_Xf */
			case '<xf': case '<xf/>':
				xf = y;
				delete xf[0];
				for(i = 0; i < cellXF_uint.length; ++i) if(xf[cellXF_uint[i]])
					xf[cellXF_uint[i]] = parseInt(xf[cellXF_uint[i]], 10);
				for(i = 0; i < cellXF_bool.length; ++i) if(xf[cellXF_bool[i]])
					xf[cellXF_bool[i]] = parsexmlbool(xf[cellXF_bool[i]]);
				if(styles.NumberFmt && xf.numFmtId > 0x188) {
					for(i = 0x188; i > 0x3c; --i) if(styles.NumberFmt[xf.numFmtId] == styles.NumberFmt[i]) { xf.numFmtId = i; break; }
				}
				styles.CellXf.push(xf); break;
			case '</xf>': break;

			/* 18.8.1 alignment CT_CellAlignment */
			case '<alignment': case '<alignment/>':
				var alignment = {};
				if(y.vertical) alignment.vertical = y.vertical;
				if(y.horizontal) alignment.horizontal = y.horizontal;
				if(y.textRotation != null) alignment.textRotation = y.textRotation;
				if(y.indent) alignment.indent = y.indent;
				if(y.wrapText) alignment.wrapText = parsexmlbool(y.wrapText);
				xf.alignment = alignment;
				break;
			case '</alignment>': break;

			/* 18.8.33 protection CT_CellProtection */
			case '<protection':
				break;
			case '</protection>': case '<protection/>': break;

			/* note: sometimes mc:AlternateContent appears bare */
			case '<AlternateContent': pass = true; break;
			case '</AlternateContent>': pass = false; break;

			/* 18.2.10 extLst CT_ExtensionList ? */
			case '<extLst': case '<extLst>': case '</extLst>': break;
			case '<ext': pass = true; break;
			case '</ext>': pass = false; break;
			default: if(opts && opts.WTF) {
				if(!pass) throw new Error('unrecognized ' + y[0] + ' in cellXfs');
			}
		}
	});
}

function write_cellXfs(cellXfs)/*:string*/ {
	var o/*:Array<string>*/ = [];
	o[o.length] = (writextag('cellXfs',null));
	cellXfs.forEach(function(c) {
		o[o.length] = (writextag('xf', null, c));
	});
	o[o.length] = ("</cellXfs>");
	if(o.length === 2) return "";
	o[0] = writextag('cellXfs',null, {count:o.length-2}).replace("/>",">");
	return o.join("");
}

/* 18.8 Styles CT_Stylesheet*/
var parse_sty_xml= /*#__PURE__*/(function make_pstyx() {
var numFmtRegex = /<(?:\w+:)?numFmts([^>]*)>[\S\s]*?<\/(?:\w+:)?numFmts>/;
var cellXfRegex = /<(?:\w+:)?cellXfs([^>]*)>[\S\s]*?<\/(?:\w+:)?cellXfs>/;
var fillsRegex = /<(?:\w+:)?fills([^>]*)>[\S\s]*?<\/(?:\w+:)?fills>/;
var fontsRegex = /<(?:\w+:)?fonts([^>]*)>[\S\s]*?<\/(?:\w+:)?fonts>/;
var bordersRegex = /<(?:\w+:)?borders([^>]*)>[\S\s]*?<\/(?:\w+:)?borders>/;

return function parse_sty_xml(data, themes, opts) {
	var styles = {};
	if(!data) return styles;
	data = data.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
	/* 18.8.39 styleSheet CT_Stylesheet */
	var t;

	/* 18.8.31 numFmts CT_NumFmts ? */
	if((t=data.match(numFmtRegex))) parse_numFmts(t, styles, opts);

	/* 18.8.23 fonts CT_Fonts ? */
	if((t=data.match(fontsRegex))) parse_fonts(t, styles, themes, opts);

	/* 18.8.21 fills CT_Fills ? */
	if((t=data.match(fillsRegex))) parse_fills(t, styles, themes, opts);

	/* 18.8.5  borders CT_Borders ? */
	if((t=data.match(bordersRegex))) parse_borders(t, styles, themes, opts);

	/* 18.8.9  cellStyleXfs CT_CellStyleXfs ? */
	/* 18.8.8  cellStyles CT_CellStyles ? */

	/* 18.8.10 cellXfs CT_CellXfs ? */
	if((t=data.match(cellXfRegex))) parse_cellXfs(t, styles, opts);

	/* 18.8.15 dxfs CT_Dxfs ? */
	/* 18.8.42 tableStyles CT_TableStyles ? */
	/* 18.8.11 colors CT_Colors ? */
	/* 18.2.10 extLst CT_ExtensionList ? */

	return styles;
};
})();

function write_sty_xml(wb/*:Workbook*/, opts)/*:string*/ {
	var o = [XML_HEADER, writextag('styleSheet', null, {
		'xmlns': XMLNS_main[0],
		'xmlns:vt': XMLNS.vt
	})], w;
	if(wb.SSF && (w = write_numFmts(wb.SSF)) != null) o[o.length] = w;
	o[o.length] = ('<fonts count="1"><font><sz val="12"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font></fonts>');
	o[o.length] = ('<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>');
	o[o.length] = ('<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>');
	o[o.length] = ('<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>');
	if((w = write_cellXfs(opts.cellXfs))) o[o.length] = (w);
	o[o.length] = ('<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>');
	o[o.length] = ('<dxfs count="0"/>');
	o[o.length] = ('<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4"/>');

	if(o.length>2){ o[o.length] = ('</styleSheet>'); o[1]=o[1].replace("/>",">"); }
	return o.join("");
}
/* [MS-XLSB] 2.4.657 BrtFmt */
function parse_BrtFmt(data, length/*:number*/) {
	var numFmtId = data.read_shift(2);
	var stFmtCode = parse_XLWideString(data,length-2);
	return [numFmtId, stFmtCode];
}
function write_BrtFmt(i/*:number*/, f/*:string*/, o) {
	if(!o) o = new_buf(6 + 4 * f.length);
	o.write_shift(2, i);
	write_XLWideString(f, o);
	var out = (o.length > o.l) ? o.slice(0, o.l) : o;
	if(o.l == null) o.l = o.length;
	return out;
}

/* [MS-XLSB] 2.4.659 BrtFont TODO */
function parse_BrtFont(data, length/*:number*/, opts) {
	var out = ({}/*:any*/);

	out.sz = data.read_shift(2) / 20;

	var grbit = parse_FontFlags(data, 2, opts);
	if(grbit.fItalic) out.italic = 1;
	if(grbit.fCondense) out.condense = 1;
	if(grbit.fExtend) out.extend = 1;
	if(grbit.fShadow) out.shadow = 1;
	if(grbit.fOutline) out.outline = 1;
	if(grbit.fStrikeout) out.strike = 1;

	var bls = data.read_shift(2);
	if(bls === 0x02BC) out.bold = 1;

	switch(data.read_shift(2)) {
		/* case 0: out.vertAlign = "baseline"; break; */
		case 1: out.vertAlign = "superscript"; break;
		case 2: out.vertAlign = "subscript"; break;
	}

	var underline = data.read_shift(1);
	if(underline != 0) out.underline = underline;

	var family = data.read_shift(1);
	if(family > 0) out.family = family;

	var bCharSet = data.read_shift(1);
	if(bCharSet > 0) out.charset = bCharSet;

	data.l++;
	out.color = parse_BrtColor(data, 8);

	switch(data.read_shift(1)) {
		/* case 0: out.scheme = "none": break; */
		case 1: out.scheme = "major"; break;
		case 2: out.scheme = "minor"; break;
	}

	out.name = parse_XLWideString(data, length - 21);

	return out;
}
function write_BrtFont(font/*:any*/, o) {
	if(!o) o = new_buf(25+4*32);
	o.write_shift(2, font.sz * 20);
	write_FontFlags(font, o);
	o.write_shift(2, font.bold ? 0x02BC : 0x0190);
	var sss = 0;
	if(font.vertAlign == "superscript") sss = 1;
	else if(font.vertAlign == "subscript") sss = 2;
	o.write_shift(2, sss);
	o.write_shift(1, font.underline || 0);
	o.write_shift(1, font.family || 0);
	o.write_shift(1, font.charset || 0);
	o.write_shift(1, 0);
	write_BrtColor(font.color, o);
	var scheme = 0;
	if(font.scheme == "major") scheme = 1;
	if(font.scheme == "minor") scheme = 2;
	o.write_shift(1, scheme);
	write_XLWideString(font.name, o);
	return o.length > o.l ? o.slice(0, o.l) : o;
}

/* [MS-XLSB] 2.4.650 BrtFill */
var XLSBFillPTNames = [
	"none",
	"solid",
	"mediumGray",
	"darkGray",
	"lightGray",
	"darkHorizontal",
	"darkVertical",
	"darkDown",
	"darkUp",
	"darkGrid",
	"darkTrellis",
	"lightHorizontal",
	"lightVertical",
	"lightDown",
	"lightUp",
	"lightGrid",
	"lightTrellis",
	"gray125",
	"gray0625"
];
var rev_XLSBFillPTNames/*:EvertNumType*/;
/* TODO: gradient fill representation */
var parse_BrtFill = parsenoop;
function write_BrtFill(fill, o) {
	if(!o) o = new_buf(4*3 + 8*7 + 16*1);
	if(!rev_XLSBFillPTNames) rev_XLSBFillPTNames = (evert(XLSBFillPTNames)/*:any*/);
	var fls/*:number*/ = rev_XLSBFillPTNames[fill.patternType];
	if(fls == null) fls = 0x28;
	o.write_shift(4, fls);
	var j = 0;
	if(fls != 0x28) {
		/* TODO: custom FG Color */
		write_BrtColor({auto:1}, o);
		/* TODO: custom BG Color */
		write_BrtColor({auto:1}, o);

		for(; j < 12; ++j) o.write_shift(4, 0);
	} else {
		for(; j < 4; ++j) o.write_shift(4, 0);

		for(; j < 12; ++j) o.write_shift(4, 0); /* TODO */
		/* iGradientType */
		/* xnumDegree */
		/* xnumFillToLeft */
		/* xnumFillToRight */
		/* xnumFillToTop */
		/* xnumFillToBottom */
		/* cNumStop */
		/* xfillGradientStop */
	}
	return o.length > o.l ? o.slice(0, o.l) : o;
}

/* [MS-XLSB] 2.4.824 BrtXF */
function parse_BrtXF(data, length/*:number*/) {
	var tgt = data.l + length;
	var ixfeParent = data.read_shift(2);
	var ifmt = data.read_shift(2);
	data.l = tgt;
	return {ixfe:ixfeParent, numFmtId:ifmt };
}
function write_BrtXF(data, ixfeP, o) {
	if(!o) o = new_buf(16);
	o.write_shift(2, ixfeP||0);
	o.write_shift(2, data.numFmtId||0);
	o.write_shift(2, 0); /* iFont */
	o.write_shift(2, 0); /* iFill */
	o.write_shift(2, 0); /* ixBorder */
	o.write_shift(1, 0); /* trot */
	o.write_shift(1, 0); /* indent */
	var flow = 0;
	o.write_shift(1, flow); /* flags */
	o.write_shift(1, 0); /* flags */
	o.write_shift(1, 0); /* xfGrbitAtr */
	o.write_shift(1, 0);
	return o;
}

/* [MS-XLSB] 2.5.4 Blxf TODO */
function write_Blxf(data, o) {
	if(!o) o = new_buf(10);
	o.write_shift(1, 0); /* dg */
	o.write_shift(1, 0);
	o.write_shift(4, 0); /* color */
	o.write_shift(4, 0); /* color */
	return o;
}
/* [MS-XLSB] 2.4.302 BrtBorder TODO */
var parse_BrtBorder = parsenoop;
function write_BrtBorder(border, o) {
	if(!o) o = new_buf(51);
	o.write_shift(1, 0); /* diagonal */
	write_Blxf(null, o); /* top */
	write_Blxf(null, o); /* bottom */
	write_Blxf(null, o); /* left */
	write_Blxf(null, o); /* right */
	write_Blxf(null, o); /* diag */
	return o.length > o.l ? o.slice(0, o.l) : o;
}

/* [MS-XLSB] 2.4.763 BrtStyle TODO */
function write_BrtStyle(style, o) {
	if(!o) o = new_buf(12+4*10);
	o.write_shift(4, style.xfId);
	o.write_shift(2, 1);
	o.write_shift(1, +style.builtinId);
	o.write_shift(1, 0); /* iLevel */
	write_XLNullableWideString(style.name || "", o);
	return o.length > o.l ? o.slice(0, o.l) : o;
}

/* [MS-XLSB] 2.4.272 BrtBeginTableStyles */
function write_BrtBeginTableStyles(cnt, defTableStyle, defPivotStyle) {
	var o = new_buf(4+256*2*4);
	o.write_shift(4, cnt);
	write_XLNullableWideString(defTableStyle, o);
	write_XLNullableWideString(defPivotStyle, o);
	return o.length > o.l ? o.slice(0, o.l) : o;
}

/* [MS-XLSB] 2.1.7.50 Styles */
function parse_sty_bin(data, themes, opts) {
	var styles = {};
	styles.NumberFmt = ([]/*:any*/);
	for(var y in table_fmt) styles.NumberFmt[y] = table_fmt[y];

	styles.CellXf = [];
	styles.Fonts = [];
	var state/*:Array<string>*/ = [];
	var pass = false;
	recordhopper(data, function hopper_sty(val, R, RT) {
		switch(RT) {
			case 0x002C: /* BrtFmt */
				styles.NumberFmt[val[0]] = val[1]; SSF_load(val[1], val[0]);
				break;
			case 0x002B: /* BrtFont */
				styles.Fonts.push(val);
				if(val.color.theme != null && themes && themes.themeElements && themes.themeElements.clrScheme) {
					val.color.rgb = rgb_tint(themes.themeElements.clrScheme[val.color.theme].rgb, val.color.tint || 0);
				}
				break;
			case 0x0401: /* BrtKnownFonts */ break;
			case 0x002D: /* BrtFill */
				break;
			case 0x002E: /* BrtBorder */
				break;
			case 0x002F: /* BrtXF */
				if(state[state.length - 1] == 0x0269 /* BrtBeginCellXFs */) {
					styles.CellXf.push(val);
				}
				break;
			case 0x0030: /* BrtStyle */
			case 0x01FB: /* BrtDXF */
			case 0x023C: /* BrtMRUColor */
			case 0x01DB: /* BrtIndexedColor */
				break;

			case 0x0493: /* BrtDXF14 */
			case 0x0836: /* BrtDXF15 */
			case 0x046A: /* BrtSlicerStyleElement */
			case 0x0200: /* BrtTableStyleElement */
			case 0x082F: /* BrtTimelineStyleElement */
			case 0x0C00: /* BrtUid */
				break;

			case 0x0023: /* BrtFRTBegin */
				pass = true; break;
			case 0x0024: /* BrtFRTEnd */
				pass = false; break;
			case 0x0025: /* BrtACBegin */
				state.push(RT); pass = true; break;
			case 0x0026: /* BrtACEnd */
				state.pop(); pass = false; break;

			default:
				if(R.T > 0) state.push(RT);
				else if(R.T < 0) state.pop();
				else if(!pass || (opts.WTF && state[state.length-1] != 0x0025 /* BrtACBegin */)) throw new Error("Unexpected record 0x" + RT.toString(16));
		}
	});
	return styles;
}

function write_FMTS_bin(ba, NF/*:?SSFTable*/) {
	if(!NF) return;
	var cnt = 0;
	[[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
		/*:: if(!NF) return; */
		for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) ++cnt;
	});

	if(cnt == 0) return;
	write_record(ba, 0x0267 /* BrtBeginFmts */, write_UInt32LE(cnt));
	[[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
		/*:: if(!NF) return; */
		for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) write_record(ba, 0x002C /* BrtFmt */, write_BrtFmt(i, NF[i]));
	});
	write_record(ba, 0x0268 /* BrtEndFmts */);
}

function write_FONTS_bin(ba/*::, data*/) {
	var cnt = 1;

	if(cnt == 0) return;
	write_record(ba, 0x0263 /* BrtBeginFonts */, write_UInt32LE(cnt));
	write_record(ba, 0x002B /* BrtFont */, write_BrtFont({
		sz:12,
		color: {theme:1},
		name: "Calibri",
		family: 2,
		scheme: "minor"
	}));
	/* 1*65491BrtFont [ACFONTS] */
	write_record(ba, 0x0264 /* BrtEndFonts */);
}

function write_FILLS_bin(ba/*::, data*/) {
	var cnt = 2;

	if(cnt == 0) return;
	write_record(ba, 0x025B /* BrtBeginFills */, write_UInt32LE(cnt));
	write_record(ba, 0x002D /* BrtFill */, write_BrtFill({patternType:"none"}));
	write_record(ba, 0x002D /* BrtFill */, write_BrtFill({patternType:"gray125"}));
	/* 1*65431BrtFill */
	write_record(ba, 0x025C /* BrtEndFills */);
}

function write_BORDERS_bin(ba/*::, data*/) {
	var cnt = 1;

	if(cnt == 0) return;
	write_record(ba, 0x0265 /* BrtBeginBorders */, write_UInt32LE(cnt));
	write_record(ba, 0x002E /* BrtBorder */, write_BrtBorder({}));
	/* 1*65430BrtBorder */
	write_record(ba, 0x0266 /* BrtEndBorders */);
}

function write_CELLSTYLEXFS_bin(ba/*::, data*/) {
	var cnt = 1;
	write_record(ba, 0x0272 /* BrtBeginCellStyleXFs */, write_UInt32LE(cnt));
	write_record(ba, 0x002F /* BrtXF */, write_BrtXF({
		numFmtId: 0,
		fontId:   0,
		fillId:   0,
		borderId: 0
	}, 0xFFFF));
	/* 1*65430(BrtXF *FRT) */
	write_record(ba, 0x0273 /* BrtEndCellStyleXFs */);
}

function write_CELLXFS_bin(ba, data) {
	write_record(ba, 0x0269 /* BrtBeginCellXFs */, write_UInt32LE(data.length));
	data.forEach(function(c) { write_record(ba, 0x002F /* BrtXF */, write_BrtXF(c,0)); });
	/* 1*65430(BrtXF *FRT) */
	write_record(ba, 0x026A /* BrtEndCellXFs */);
}

function write_STYLES_bin(ba/*::, data*/) {
	var cnt = 1;

	write_record(ba, 0x026B /* BrtBeginStyles */, write_UInt32LE(cnt));
	write_record(ba, 0x0030 /* BrtStyle */, write_BrtStyle({
		xfId:0,
		builtinId:0,
		name:"Normal"
	}));
	/* 1*65430(BrtStyle *FRT) */
	write_record(ba, 0x026C /* BrtEndStyles */);
}

function write_DXFS_bin(ba/*::, data*/) {
	var cnt = 0;

	write_record(ba, 0x01F9 /* BrtBeginDXFs */, write_UInt32LE(cnt));
	/* *2147483647(BrtDXF *FRT) */
	write_record(ba, 0x01FA /* BrtEndDXFs */);
}

function write_TABLESTYLES_bin(ba/*::, data*/) {
	var cnt = 0;

	write_record(ba, 0x01FC /* BrtBeginTableStyles */, write_BrtBeginTableStyles(cnt, "TableStyleMedium9", "PivotStyleMedium4"));
	/* *TABLESTYLE */
	write_record(ba, 0x01FD /* BrtEndTableStyles */);
}

function write_COLORPALETTE_bin(/*::ba, data*/) {
	return;
	/* BrtBeginColorPalette [INDEXEDCOLORS] [MRUCOLORS] BrtEndColorPalette */
}

/* [MS-XLSB] 2.1.7.50 Styles */
function write_sty_bin(wb, opts) {
	var ba = buf_array();
	write_record(ba, 0x0116 /* BrtBeginStyleSheet */);
	write_FMTS_bin(ba, wb.SSF);
	write_FONTS_bin(ba, wb);
	write_FILLS_bin(ba, wb);
	write_BORDERS_bin(ba, wb);
	write_CELLSTYLEXFS_bin(ba, wb);
	write_CELLXFS_bin(ba, opts.cellXfs);
	write_STYLES_bin(ba, wb);
	write_DXFS_bin(ba, wb);
	write_TABLESTYLES_bin(ba, wb);
	write_COLORPALETTE_bin(ba, wb);
	/* FRTSTYLESHEET*/
	write_record(ba, 0x0117 /* BrtEndStyleSheet */);
	return ba.end();
}
/* Even though theme layout is dk1 lt1 dk2 lt2, true order is lt1 dk1 lt2 dk2 */
var XLSXThemeClrScheme = [
	'</a:lt1>', '</a:dk1>', '</a:lt2>', '</a:dk2>',
	'</a:accent1>', '</a:accent2>', '</a:accent3>',
	'</a:accent4>', '</a:accent5>', '</a:accent6>',
	'</a:hlink>', '</a:folHlink>'
];
/* 20.1.6.2 clrScheme CT_ColorScheme */
function parse_clrScheme(t, themes, opts) {
	themes.themeElements.clrScheme = [];
	var color = {};
	(t[0].match(tagregex)||[]).forEach(function(x) {
		var y = parsexmltag(x);
		switch(y[0]) {
			/* 20.1.6.2 clrScheme (Color Scheme) CT_ColorScheme */
			case '<a:clrScheme': case '</a:clrScheme>': break;

			/* 20.1.2.3.32 srgbClr CT_SRgbColor */
			case '<a:srgbClr':
				color.rgb = y.val; break;

			/* 20.1.2.3.33 sysClr CT_SystemColor */
			case '<a:sysClr':
				color.rgb = y.lastClr; break;

			/* 20.1.4.1.1 accent1 (Accent 1) */
			/* 20.1.4.1.2 accent2 (Accent 2) */
			/* 20.1.4.1.3 accent3 (Accent 3) */
			/* 20.1.4.1.4 accent4 (Accent 4) */
			/* 20.1.4.1.5 accent5 (Accent 5) */
			/* 20.1.4.1.6 accent6 (Accent 6) */
			/* 20.1.4.1.9 dk1 (Dark 1) */
			/* 20.1.4.1.10 dk2 (Dark 2) */
			/* 20.1.4.1.15 folHlink (Followed Hyperlink) */
			/* 20.1.4.1.19 hlink (Hyperlink) */
			/* 20.1.4.1.22 lt1 (Light 1) */
			/* 20.1.4.1.23 lt2 (Light 2) */
			case '<a:dk1>': case '</a:dk1>':
			case '<a:lt1>': case '</a:lt1>':
			case '<a:dk2>': case '</a:dk2>':
			case '<a:lt2>': case '</a:lt2>':
			case '<a:accent1>': case '</a:accent1>':
			case '<a:accent2>': case '</a:accent2>':
			case '<a:accent3>': case '</a:accent3>':
			case '<a:accent4>': case '</a:accent4>':
			case '<a:accent5>': case '</a:accent5>':
			case '<a:accent6>': case '</a:accent6>':
			case '<a:hlink>': case '</a:hlink>':
			case '<a:folHlink>': case '</a:folHlink>':
				if (y[0].charAt(1) === '/') {
					themes.themeElements.clrScheme[XLSXThemeClrScheme.indexOf(y[0])] = color;
					color = {};
				} else {
					color.name = y[0].slice(3, y[0].length - 1);
				}
				break;

			default: if(opts && opts.WTF) throw new Error('Unrecognized ' + y[0] + ' in clrScheme');
		}
	});
}

/* 20.1.4.1.18 fontScheme CT_FontScheme */
function parse_fontScheme(/*::t, themes, opts*/) { }

/* 20.1.4.1.15 fmtScheme CT_StyleMatrix */
function parse_fmtScheme(/*::t, themes, opts*/) { }

var clrsregex = /<a:clrScheme([^>]*)>[\s\S]*<\/a:clrScheme>/;
var fntsregex = /<a:fontScheme([^>]*)>[\s\S]*<\/a:fontScheme>/;
var fmtsregex = /<a:fmtScheme([^>]*)>[\s\S]*<\/a:fmtScheme>/;

/* 20.1.6.10 themeElements CT_BaseStyles */
function parse_themeElements(data, themes, opts) {
	themes.themeElements = {};

	var t;

	[
		/* clrScheme CT_ColorScheme */
		['clrScheme', clrsregex, parse_clrScheme],
		/* fontScheme CT_FontScheme */
		['fontScheme', fntsregex, parse_fontScheme],
		/* fmtScheme CT_StyleMatrix */
		['fmtScheme', fmtsregex, parse_fmtScheme]
	].forEach(function(m) {
		if(!(t=data.match(m[1]))) throw new Error(m[0] + ' not found in themeElements');
		m[2](t, themes, opts);
	});
}

var themeltregex = /<a:themeElements([^>]*)>[\s\S]*<\/a:themeElements>/;

/* 14.2.7 Theme Part */
function parse_theme_xml(data/*:string*/, opts) {
	/* 20.1.6.9 theme CT_OfficeStyleSheet */
	if(!data || data.length === 0) data = write_theme();

	var t;
	var themes = {};

	/* themeElements CT_BaseStyles */
	if(!(t=data.match(themeltregex))) throw new Error('themeElements not found in theme');
	parse_themeElements(t[0], themes, opts);
	themes.raw = data;
	return themes;
}

function write_theme(Themes, opts)/*:string*/ {
	if(opts && opts.themeXLSX) return opts.themeXLSX;
	if(Themes && typeof Themes.raw == "string") return Themes.raw;
	var o = [XML_HEADER];
	o[o.length] = '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">';
	o[o.length] =  '<a:themeElements>';

	o[o.length] =   '<a:clrScheme name="Office">';
	o[o.length] =    '<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>';
	o[o.length] =    '<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>';
	o[o.length] =    '<a:dk2><a:srgbClr val="1F497D"/></a:dk2>';
	o[o.length] =    '<a:lt2><a:srgbClr val="EEECE1"/></a:lt2>';
	o[o.length] =    '<a:accent1><a:srgbClr val="4F81BD"/></a:accent1>';
	o[o.length] =    '<a:accent2><a:srgbClr val="C0504D"/></a:accent2>';
	o[o.length] =    '<a:accent3><a:srgbClr val="9BBB59"/></a:accent3>';
	o[o.length] =    '<a:accent4><a:srgbClr val="8064A2"/></a:accent4>';
	o[o.length] =    '<a:accent5><a:srgbClr val="4BACC6"/></a:accent5>';
	o[o.length] =    '<a:accent6><a:srgbClr val="F79646"/></a:accent6>';
	o[o.length] =    '<a:hlink><a:srgbClr val="0000FF"/></a:hlink>';
	o[o.length] =    '<a:folHlink><a:srgbClr val="800080"/></a:folHlink>';
	o[o.length] =   '</a:clrScheme>';

	o[o.length] =   '<a:fontScheme name="Office">';
	o[o.length] =    '<a:majorFont>';
	o[o.length] =     '<a:latin typeface="Cambria"/>';
	o[o.length] =     '<a:ea typeface=""/>';
	o[o.length] =     '<a:cs typeface=""/>';
	o[o.length] =     '<a:font script="Jpan" typeface="ＭＳ Ｐゴシック"/>';
	o[o.length] =     '<a:font script="Hang" typeface="맑은 고딕"/>';
	o[o.length] =     '<a:font script="Hans" typeface="宋体"/>';
	o[o.length] =     '<a:font script="Hant" typeface="新細明體"/>';
	o[o.length] =     '<a:font script="Arab" typeface="Times New Roman"/>';
	o[o.length] =     '<a:font script="Hebr" typeface="Times New Roman"/>';
	o[o.length] =     '<a:font script="Thai" typeface="Tahoma"/>';
	o[o.length] =     '<a:font script="Ethi" typeface="Nyala"/>';
	o[o.length] =     '<a:font script="Beng" typeface="Vrinda"/>';
	o[o.length] =     '<a:font script="Gujr" typeface="Shruti"/>';
	o[o.length] =     '<a:font script="Khmr" typeface="MoolBoran"/>';
	o[o.length] =     '<a:font script="Knda" typeface="Tunga"/>';
	o[o.length] =     '<a:font script="Guru" typeface="Raavi"/>';
	o[o.length] =     '<a:font script="Cans" typeface="Euphemia"/>';
	o[o.length] =     '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
	o[o.length] =     '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
	o[o.length] =     '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
	o[o.length] =     '<a:font script="Thaa" typeface="MV Boli"/>';
	o[o.length] =     '<a:font script="Deva" typeface="Mangal"/>';
	o[o.length] =     '<a:font script="Telu" typeface="Gautami"/>';
	o[o.length] =     '<a:font script="Taml" typeface="Latha"/>';
	o[o.length] =     '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
	o[o.length] =     '<a:font script="Orya" typeface="Kalinga"/>';
	o[o.length] =     '<a:font script="Mlym" typeface="Kartika"/>';
	o[o.length] =     '<a:font script="Laoo" typeface="DokChampa"/>';
	o[o.length] =     '<a:font script="Sinh" typeface="Iskoola Pota"/>';
	o[o.length] =     '<a:font script="Mong" typeface="Mongolian Baiti"/>';
	o[o.length] =     '<a:font script="Viet" typeface="Times New Roman"/>';
	o[o.length] =     '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
	o[o.length] =     '<a:font script="Geor" typeface="Sylfaen"/>';
	o[o.length] =    '</a:majorFont>';
	o[o.length] =    '<a:minorFont>';
	o[o.length] =     '<a:latin typeface="Calibri"/>';
	o[o.length] =     '<a:ea typeface=""/>';
	o[o.length] =     '<a:cs typeface=""/>';
	o[o.length] =     '<a:font script="Jpan" typeface="ＭＳ Ｐゴシック"/>';
	o[o.length] =     '<a:font script="Hang" typeface="맑은 고딕"/>';
	o[o.length] =     '<a:font script="Hans" typeface="宋体"/>';
	o[o.length] =     '<a:font script="Hant" typeface="新細明體"/>';
	o[o.length] =     '<a:font script="Arab" typeface="Arial"/>';
	o[o.length] =     '<a:font script="Hebr" typeface="Arial"/>';
	o[o.length] =     '<a:font script="Thai" typeface="Tahoma"/>';
	o[o.length] =     '<a:font script="Ethi" typeface="Nyala"/>';
	o[o.length] =     '<a:font script="Beng" typeface="Vrinda"/>';
	o[o.length] =     '<a:font script="Gujr" typeface="Shruti"/>';
	o[o.length] =     '<a:font script="Khmr" typeface="DaunPenh"/>';
	o[o.length] =     '<a:font script="Knda" typeface="Tunga"/>';
	o[o.length] =     '<a:font script="Guru" typeface="Raavi"/>';
	o[o.length] =     '<a:font script="Cans" typeface="Euphemia"/>';
	o[o.length] =     '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
	o[o.length] =     '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
	o[o.length] =     '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
	o[o.length] =     '<a:font script="Thaa" typeface="MV Boli"/>';
	o[o.length] =     '<a:font script="Deva" typeface="Mangal"/>';
	o[o.length] =     '<a:font script="Telu" typeface="Gautami"/>';
	o[o.length] =     '<a:font script="Taml" typeface="Latha"/>';
	o[o.length] =     '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
	o[o.length] =     '<a:font script="Orya" typeface="Kalinga"/>';
	o[o.length] =     '<a:font script="Mlym" typeface="Kartika"/>';
	o[o.length] =     '<a:font script="Laoo" typeface="DokChampa"/>';
	o[o.length] =     '<a:font script="Sinh" typeface="Iskoola Pota"/>';
	o[o.length] =     '<a:font script="Mong" typeface="Mongolian Baiti"/>';
	o[o.length] =     '<a:font script="Viet" typeface="Arial"/>';
	o[o.length] =     '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
	o[o.length] =     '<a:font script="Geor" typeface="Sylfaen"/>';
	o[o.length] =    '</a:minorFont>';
	o[o.length] =   '</a:fontScheme>';

	o[o.length] =   '<a:fmtScheme name="Office">';
	o[o.length] =    '<a:fillStyleLst>';
	o[o.length] =     '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
	o[o.length] =     '<a:gradFill rotWithShape="1">';
	o[o.length] =      '<a:gsLst>';
	o[o.length] =       '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
	o[o.length] =       '<a:gs pos="35000"><a:schemeClr val="phClr"><a:tint val="37000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
	o[o.length] =       '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="15000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
	o[o.length] =      '</a:gsLst>';
	o[o.length] =      '<a:lin ang="16200000" scaled="1"/>';
	o[o.length] =     '</a:gradFill>';
	o[o.length] =     '<a:gradFill rotWithShape="1">';
	o[o.length] =      '<a:gsLst>';
	o[o.length] =       '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="100000"/><a:shade val="100000"/><a:satMod val="130000"/></a:schemeClr></a:gs>';
	o[o.length] =       '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="50000"/><a:shade val="100000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
	o[o.length] =      '</a:gsLst>';
	o[o.length] =      '<a:lin ang="16200000" scaled="0"/>';
	o[o.length] =     '</a:gradFill>';
	o[o.length] =    '</a:fillStyleLst>';
	o[o.length] =    '<a:lnStyleLst>';
	o[o.length] =     '<a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"><a:shade val="95000"/><a:satMod val="105000"/></a:schemeClr></a:solidFill><a:prstDash val="solid"/></a:ln>';
	o[o.length] =     '<a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>';
	o[o.length] =     '<a:ln w="38100" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>';
	o[o.length] =    '</a:lnStyleLst>';
	o[o.length] =    '<a:effectStyleLst>';
	o[o.length] =     '<a:effectStyle>';
	o[o.length] =      '<a:effectLst>';
	o[o.length] =       '<a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="38000"/></a:srgbClr></a:outerShdw>';
	o[o.length] =      '</a:effectLst>';
	o[o.length] =     '</a:effectStyle>';
	o[o.length] =     '<a:effectStyle>';
	o[o.length] =      '<a:effectLst>';
	o[o.length] =       '<a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw>';
	o[o.length] =      '</a:effectLst>';
	o[o.length] =     '</a:effectStyle>';
	o[o.length] =     '<a:effectStyle>';
	o[o.length] =      '<a:effectLst>';
	o[o.length] =       '<a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw>';
	o[o.length] =      '</a:effectLst>';
	o[o.length] =      '<a:scene3d><a:camera prst="orthographicFront"><a:rot lat="0" lon="0" rev="0"/></a:camera><a:lightRig rig="threePt" dir="t"><a:rot lat="0" lon="0" rev="1200000"/></a:lightRig></a:scene3d>';
	o[o.length] =      '<a:sp3d><a:bevelT w="63500" h="25400"/></a:sp3d>';
	o[o.length] =     '</a:effectStyle>';
	o[o.length] =    '</a:effectStyleLst>';
	o[o.length] =    '<a:bgFillStyleLst>';
	o[o.length] =     '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
	o[o.length] =     '<a:gradFill rotWithShape="1">';
	o[o.length] =      '<a:gsLst>';
	o[o.length] =       '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="40000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
	o[o.length] =       '<a:gs pos="40000"><a:schemeClr val="phClr"><a:tint val="45000"/><a:shade val="99000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
	o[o.length] =       '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="20000"/><a:satMod val="255000"/></a:schemeClr></a:gs>';
	o[o.length] =      '</a:gsLst>';
	o[o.length] =      '<a:path path="circle"><a:fillToRect l="50000" t="-80000" r="50000" b="180000"/></a:path>';
	o[o.length] =     '</a:gradFill>';
	o[o.length] =     '<a:gradFill rotWithShape="1">';
	o[o.length] =      '<a:gsLst>';
	o[o.length] =       '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="80000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
	o[o.length] =       '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="30000"/><a:satMod val="200000"/></a:schemeClr></a:gs>';
	o[o.length] =      '</a:gsLst>';
	o[o.length] =      '<a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000"/></a:path>';
	o[o.length] =     '</a:gradFill>';
	o[o.length] =    '</a:bgFillStyleLst>';
	o[o.length] =   '</a:fmtScheme>';
	o[o.length] =  '</a:themeElements>';

	o[o.length] =  '<a:objectDefaults>';
	o[o.length] =   '<a:spDef>';
	o[o.length] =    '<a:spPr/><a:bodyPr/><a:lstStyle/><a:style><a:lnRef idx="1"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="3"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="2"><a:schemeClr val="accent1"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef></a:style>';
	o[o.length] =   '</a:spDef>';
	o[o.length] =   '<a:lnDef>';
	o[o.length] =    '<a:spPr/><a:bodyPr/><a:lstStyle/><a:style><a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="0"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="1"><a:schemeClr val="accent1"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="tx1"/></a:fontRef></a:style>';
	o[o.length] =   '</a:lnDef>';
	o[o.length] =  '</a:objectDefaults>';
	o[o.length] =  '<a:extraClrSchemeLst/>';
	o[o.length] = '</a:theme>';
	return o.join("");
}
/* [MS-XLS] 2.4.326 TODO: payload is a zip file */
function parse_Theme(blob, length, opts) {
	var end = blob.l + length;
	var dwThemeVersion = blob.read_shift(4);
	if(dwThemeVersion === 124226) return;
	if(!opts.cellStyles) { blob.l = end; return; }
	var data = blob.slice(blob.l);
	blob.l = end;
	var zip; try { zip = zip_read(data, {type: "array"}); } catch(e) { return; }
	var themeXML = getzipstr(zip, "theme/theme/theme1.xml", true);
	if(!themeXML) return;
	return parse_theme_xml(themeXML, opts);
}

/* 2.5.49 */
function parse_ColorTheme(blob/*::, length*/) { return blob.read_shift(4); }

/* 2.5.155 */
function parse_FullColorExt(blob/*::, length*/) {
	var o = {};
	o.xclrType = blob.read_shift(2);
	o.nTintShade = blob.read_shift(2);
	switch(o.xclrType) {
		case 0: blob.l += 4; break;
		case 1: o.xclrValue = parse_IcvXF(blob, 4); break;
		case 2: o.xclrValue = parse_LongRGBA(blob, 4); break;
		case 3: o.xclrValue = parse_ColorTheme(blob, 4); break;
		case 4: blob.l += 4; break;
	}
	blob.l += 8;
	return o;
}

/* 2.5.164 TODO: read 7 bits*/
function parse_IcvXF(blob, length) {
	return parsenoop(blob, length);
}

/* 2.5.280 */
function parse_XFExtGradient(blob, length) {
	return parsenoop(blob, length);
}

/* [MS-XLS] 2.5.108 */
function parse_ExtProp(blob/*::, length*/)/*:Array<any>*/ {
	var extType = blob.read_shift(2);
	var cb = blob.read_shift(2) - 4;
	var o = [extType];
	switch(extType) {
		case 0x04: case 0x05: case 0x07: case 0x08:
		case 0x09: case 0x0A: case 0x0B: case 0x0D:
			o[1] = parse_FullColorExt(blob, cb); break;
		case 0x06: o[1] = parse_XFExtGradient(blob, cb); break;
		case 0x0E: case 0x0F: o[1] = blob.read_shift(cb === 1 ? 1 : 2); break;
		default: throw new Error("Unrecognized ExtProp type: " + extType + " " + cb);
	}
	return o;
}

/* 2.4.355 */
function parse_XFExt(blob, length) {
	var end = blob.l + length;
	blob.l += 2;
	var ixfe = blob.read_shift(2);
	blob.l += 2;
	var cexts = blob.read_shift(2);
	var ext/*:AOA*/ = [];
	while(cexts-- > 0) ext.push(parse_ExtProp(blob, end-blob.l));
	return {ixfe:ixfe, ext:ext};
}

/* xf is an XF, see parse_XFExt for xfext */
function update_xfext(xf, xfext) {
	xfext.forEach(function(xfe) {
		switch(xfe[0]) { /* 2.5.108 extPropData */
			case 0x04: break; /* foreground color */
			case 0x05: break; /* background color */
			case 0x06: break; /* gradient fill */
			case 0x07: break; /* top cell border color */
			case 0x08: break; /* bottom cell border color */
			case 0x09: break; /* left cell border color */
			case 0x0a: break; /* right cell border color */
			case 0x0b: break; /* diagonal cell border color */
			case 0x0d: /* text color */
				break;
			case 0x0e: break; /* font scheme */
			case 0x0f: break; /* indentation level */
		}
	});
}

function parse_BrtMdtinfo(data, length) {
  return {
    flags: data.read_shift(4),
    version: data.read_shift(4),
    name: parse_XLWideString(data, length - 8)
  };
}
function write_BrtMdtinfo(data) {
  var o = new_buf(12 + 2 * data.name.length);
  o.write_shift(4, data.flags);
  o.write_shift(4, data.version);
  write_XLWideString(data.name, o);
  return o.slice(0, o.l);
}
function parse_BrtMdb(data) {
  var out = [];
  var cnt = data.read_shift(4);
  while (cnt-- > 0)
    out.push([data.read_shift(4), data.read_shift(4)]);
  return out;
}
function write_BrtMdb(mdb) {
  var o = new_buf(4 + 8 * mdb.length);
  o.write_shift(4, mdb.length);
  for (var i = 0; i < mdb.length; ++i) {
    o.write_shift(4, mdb[i][0]);
    o.write_shift(4, mdb[i][1]);
  }
  return o;
}
function write_BrtBeginEsfmd(cnt, name) {
  var o = new_buf(8 + 2 * name.length);
  o.write_shift(4, cnt);
  write_XLWideString(name, o);
  return o.slice(0, o.l);
}
function parse_BrtBeginEsmdb(data) {
  data.l += 4;
  return data.read_shift(4) != 0;
}
function write_BrtBeginEsmdb(cnt, cm) {
  var o = new_buf(8);
  o.write_shift(4, cnt);
  o.write_shift(4, cm ? 1 : 0);
  return o;
}
function parse_xlmeta_bin(data, name, _opts) {
  var out = { Types: [], Cell: [], Value: [] };
  var opts = _opts || {};
  var state = [];
  var pass = false;
  var metatype = 2;
  recordhopper(data, function(val, R, RT) {
    switch (RT) {
      case 335:
        out.Types.push({ name: val.name });
        break;
      case 51:
        val.forEach(function(r) {
          if (metatype == 1)
            out.Cell.push({ type: out.Types[r[0] - 1].name, index: r[1] });
          else if (metatype == 0)
            out.Value.push({ type: out.Types[r[0] - 1].name, index: r[1] });
        });
        break;
      case 337:
        metatype = val ? 1 : 0;
        break;
      case 338:
        metatype = 2;
        break;
      case 35:
        state.push(RT);
        pass = true;
        break;
      case 36:
        state.pop();
        pass = false;
        break;
      default:
        if (R.T) {
        } else if (!pass || opts.WTF && state[state.length - 1] != 35)
          throw new Error("Unexpected record 0x" + RT.toString(16));
    }
  });
  return out;
}
function write_xlmeta_bin() {
  var ba = buf_array();
  write_record(ba, 332);
  write_record(ba, 334, write_UInt32LE(1));
  write_record(ba, 335, write_BrtMdtinfo({
    name: "XLDAPR",
    version: 12e4,
    flags: 3496657072
  }));
  write_record(ba, 336);
  write_record(ba, 339, write_BrtBeginEsfmd(1, "XLDAPR"));
  write_record(ba, 52);
  write_record(ba, 35, write_UInt32LE(514));
  write_record(ba, 4096, write_UInt32LE(0));
  write_record(ba, 4097, writeuint16(1));
  write_record(ba, 36);
  write_record(ba, 53);
  write_record(ba, 340);
  write_record(ba, 337, write_BrtBeginEsmdb(1, true));
  write_record(ba, 51, write_BrtMdb([[1, 0]]));
  write_record(ba, 338);
  write_record(ba, 333);
  return ba.end();
}
function parse_xlmeta_xml(data, name, opts) {
  var out = { Types: [], Cell: [], Value: [] };
  if (!data)
    return out;
  var pass = false;
  var metatype = 2;
  var lastmeta;
  data.replace(tagregex, function(x) {
    var y = parsexmltag(x);
    switch (strip_ns(y[0])) {
      case "<?xml":
        break;
      case "<metadata":
      case "</metadata>":
        break;
      case "<metadataTypes":
      case "</metadataTypes>":
        break;
      case "<metadataType":
        out.Types.push({ name: y.name });
        break;
      case "</metadataType>":
        break;
      case "<futureMetadata":
        for (var j = 0; j < out.Types.length; ++j)
          if (out.Types[j].name == y.name)
            lastmeta = out.Types[j];
        break;
      case "</futureMetadata>":
        break;
      case "<bk>":
        break;
      case "</bk>":
        break;
      case "<rc":
        if (metatype == 1)
          out.Cell.push({ type: out.Types[y.t - 1].name, index: +y.v });
        else if (metatype == 0)
          out.Value.push({ type: out.Types[y.t - 1].name, index: +y.v });
        break;
      case "</rc>":
        break;
      case "<cellMetadata":
        metatype = 1;
        break;
      case "</cellMetadata>":
        metatype = 2;
        break;
      case "<valueMetadata":
        metatype = 0;
        break;
      case "</valueMetadata>":
        metatype = 2;
        break;
      case "<extLst":
      case "<extLst>":
      case "</extLst>":
      case "<extLst/>":
        break;
      case "<ext":
        pass = true;
        break;
      case "</ext>":
        pass = false;
        break;
      case "<rvb":
        if (!lastmeta)
          break;
        if (!lastmeta.offsets)
          lastmeta.offsets = [];
        lastmeta.offsets.push(+y.i);
        break;
      default:
        if (!pass && opts.WTF)
          throw new Error("unrecognized " + y[0] + " in metadata");
    }
    return x;
  });
  return out;
}
function write_xlmeta_xml() {
  var o = [XML_HEADER];
  o.push('<metadata xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:xlrd="http://schemas.microsoft.com/office/spreadsheetml/2017/richdata" xmlns:xda="http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray">\n  <metadataTypes count="1">\n    <metadataType name="XLDAPR" minSupportedVersion="120000" copy="1" pasteAll="1" pasteValues="1" merge="1" splitFirst="1" rowColShift="1" clearFormats="1" clearComments="1" assign="1" coerce="1" cellMeta="1"/>\n  </metadataTypes>\n  <futureMetadata name="XLDAPR" count="1">\n    <bk>\n      <extLst>\n        <ext uri="{bdbb8cdc-fa1e-496e-a857-3c3f30c029c3}">\n          <xda:dynamicArrayProperties fDynamic="1" fCollapsed="0"/>\n        </ext>\n      </extLst>\n    </bk>\n  </futureMetadata>\n  <cellMetadata count="1">\n    <bk>\n      <rc t="1" v="0"/>\n    </bk>\n  </cellMetadata>\n</metadata>');
  return o.join("");
}
/* 18.6 Calculation Chain */
function parse_cc_xml(data/*::, name, opts*/)/*:Array<any>*/ {
	var d = [];
	if(!data) return d;
	var i = 1;
	(data.match(tagregex)||[]).forEach(function(x) {
		var y = parsexmltag(x);
		switch(y[0]) {
			case '<?xml': break;
			/* 18.6.2  calcChain CT_CalcChain 1 */
			case '<calcChain': case '<calcChain>': case '</calcChain>': break;
			/* 18.6.1  c CT_CalcCell 1 */
			case '<c': delete y[0]; if(y.i) i = y.i; else y.i = i; d.push(y); break;
		}
	});
	return d;
}

//function write_cc_xml(data, opts) { }

/* [MS-XLSB] 2.6.4.1 */
function parse_BrtCalcChainItem$(data) {
	var out = {};
	out.i = data.read_shift(4);
	var cell = {};
	cell.r = data.read_shift(4);
	cell.c = data.read_shift(4);
	out.r = encode_cell(cell);
	var flags = data.read_shift(1);
	if(flags & 0x2) out.l = '1';
	if(flags & 0x8) out.a = '1';
	return out;
}

/* 18.6 Calculation Chain */
function parse_cc_bin(data, name, opts) {
	var out = [];
	var pass = false;
	recordhopper(data, function hopper_cc(val, R, RT) {
		switch(RT) {
			case 0x003F: /* 'BrtCalcChainItem$' */
				out.push(val); break;

			default:
				if(R.T){/* empty */}
				else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
		}
	});
	return out;
}

//function write_cc_bin(data, opts) { }
/* 18.14 Supplementary Workbook Data */
function parse_xlink_xml(/*::data, rel, name:string, _opts*/) {
	//var opts = _opts || {};
	//if(opts.WTF) throw "XLSX External Link";
}

/* [MS-XLSB] 2.1.7.25 External Link */
function parse_xlink_bin(data, rel, name/*:string*/, _opts) {
	if(!data) return data;
	var opts = _opts || {};

	var pass = false, end = false;

	recordhopper(data, function xlink_parse(val, R, RT) {
		if(end) return;
		switch(RT) {
			case 0x0167: /* 'BrtSupTabs' */
			case 0x016B: /* 'BrtExternTableStart' */
			case 0x016C: /* 'BrtExternTableEnd' */
			case 0x016E: /* 'BrtExternRowHdr' */
			case 0x016F: /* 'BrtExternCellBlank' */
			case 0x0170: /* 'BrtExternCellReal' */
			case 0x0171: /* 'BrtExternCellBool' */
			case 0x0172: /* 'BrtExternCellError' */
			case 0x0173: /* 'BrtExternCellString' */
			case 0x01D8: /* 'BrtExternValueMeta' */
			case 0x0241: /* 'BrtSupNameStart' */
			case 0x0242: /* 'BrtSupNameValueStart' */
			case 0x0243: /* 'BrtSupNameValueEnd' */
			case 0x0244: /* 'BrtSupNameNum' */
			case 0x0245: /* 'BrtSupNameErr' */
			case 0x0246: /* 'BrtSupNameSt' */
			case 0x0247: /* 'BrtSupNameNil' */
			case 0x0248: /* 'BrtSupNameBool' */
			case 0x0249: /* 'BrtSupNameFmla' */
			case 0x024A: /* 'BrtSupNameBits' */
			case 0x024B: /* 'BrtSupNameEnd' */
				break;

			case 0x0023: /* 'BrtFRTBegin' */
				pass = true; break;
			case 0x0024: /* 'BrtFRTEnd' */
				pass = false; break;

			default:
				if(R.T){/* empty */}
				else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
		}
	}, opts);
}
/* 20.5 DrawingML - SpreadsheetML Drawing */
/* 20.5.2.35 wsDr CT_Drawing */
function parse_drawing(data, rels/*:any*/) {
	if(!data) return "??";
	/*
	  Chartsheet Drawing:
	   - 20.5.2.35 wsDr CT_Drawing
	    - 20.5.2.1  absoluteAnchor CT_AbsoluteAnchor
	     - 20.5.2.16 graphicFrame CT_GraphicalObjectFrame
	      - 20.1.2.2.16 graphic CT_GraphicalObject
	       - 20.1.2.2.17 graphicData CT_GraphicalObjectData
          - chart reference
	   the actual type is based on the URI of the graphicData
		TODO: handle embedded charts and other types of graphics
	*/
	var id = (data.match(/<c:chart [^>]*r:id="([^"]*)"/)||["",""])[1];

	return rels['!id'][id].Target;
}

/* L.5.5.2 SpreadsheetML Comments + VML Schema */
var _shapeid = 1024;
function write_comments_vml(rId/*:number*/, comments) {
	var csize = [21600, 21600];
	/* L.5.2.1.2 Path Attribute */
	var bbox = ["m0,0l0",csize[1],csize[0],csize[1],csize[0],"0xe"].join(",");
	var o = [
		writextag("xml", null, { 'xmlns:v': XLMLNS.v, 'xmlns:o': XLMLNS.o, 'xmlns:x': XLMLNS.x, 'xmlns:mv': XLMLNS.mv }).replace(/\/>/,">"),
		writextag("o:shapelayout", writextag("o:idmap", null, {'v:ext':"edit", 'data':rId}), {'v:ext':"edit"}),
		writextag("v:shapetype", [
			writextag("v:stroke", null, {joinstyle:"miter"}),
			writextag("v:path", null, {gradientshapeok:"t", 'o:connecttype':"rect"})
		].join(""), {id:"_x0000_t202", 'o:spt':202, coordsize:csize.join(","),path:bbox})
	];
	while(_shapeid < rId * 1000) _shapeid += 1000;

	comments.forEach(function(x) {
	var c = decode_cell(x[0]);
	var fillopts = /*::(*/{'color2':"#BEFF82", 'type':"gradient"}/*:: :any)*/;
	if(fillopts.type == "gradient") fillopts.angle = "-180";
	var fillparm = fillopts.type == "gradient" ? writextag("o:fill", null, {type:"gradientUnscaled", 'v:ext':"view"}) : null;
	var fillxml = writextag('v:fill', fillparm, fillopts);

	var shadata = ({on:"t", 'obscured':"t"}/*:any*/);
	++_shapeid;

	o = o.concat([
	'<v:shape' + wxt_helper({
		id:'_x0000_s' + _shapeid,
		type:"#_x0000_t202",
		style:"position:absolute; margin-left:80pt;margin-top:5pt;width:104pt;height:64pt;z-index:10" + (x[1].hidden ? ";visibility:hidden" : "") ,
		fillcolor:"#ECFAD4",
		strokecolor:"#edeaa1"
	}) + '>',
		fillxml,
		writextag("v:shadow", null, shadata),
		writextag("v:path", null, {'o:connecttype':"none"}),
		'<v:textbox><div style="text-align:left"></div></v:textbox>',
		'<x:ClientData ObjectType="Note">',
			'<x:MoveWithCells/>',
			'<x:SizeWithCells/>',
			/* Part 4 19.4.2.3 Anchor (Anchor) */
			writetag('x:Anchor', [c.c+1, 0, c.r+1, 0, c.c+3, 20, c.r+5, 20].join(",")),
			writetag('x:AutoFill', "False"),
			writetag('x:Row', String(c.r)),
			writetag('x:Column', String(c.c)),
			x[1].hidden ? '' : '<x:Visible/>',
		'</x:ClientData>',
	'</v:shape>'
	]); });
	o.push('</xml>');
	return o.join("");
}
function sheet_insert_comments(sheet, comments/*:Array<RawComment>*/, threaded/*:boolean*/, people/*:?Array<any>*/) {
	var dense = Array.isArray(sheet);
	var cell/*:Cell*/;
	comments.forEach(function(comment) {
		var r = decode_cell(comment.ref);
		if(dense) {
			if(!sheet[r.r]) sheet[r.r] = [];
			cell = sheet[r.r][r.c];
		} else cell = sheet[comment.ref];
		if (!cell) {
			cell = ({t:"z"}/*:any*/);
			if(dense) sheet[r.r][r.c] = cell;
			else sheet[comment.ref] = cell;
			var range = safe_decode_range(sheet["!ref"]||"BDWGO1000001:A1");
			if(range.s.r > r.r) range.s.r = r.r;
			if(range.e.r < r.r) range.e.r = r.r;
			if(range.s.c > r.c) range.s.c = r.c;
			if(range.e.c < r.c) range.e.c = r.c;
			var encoded = encode_range(range);
			if (encoded !== sheet["!ref"]) sheet["!ref"] = encoded;
		}

		if (!cell.c) cell.c = [];
		var o/*:Comment*/ = ({a: comment.author, t: comment.t, r: comment.r, T: threaded});
		if(comment.h) o.h = comment.h;

		/* threaded comments always override */
		for(var i = cell.c.length - 1; i >= 0; --i) {
			if(!threaded && cell.c[i].T) return;
			if(threaded && !cell.c[i].T) cell.c.splice(i, 1);
		}
		if(threaded && people) for(i = 0; i < people.length; ++i) {
			if(o.a == people[i].id) { o.a = people[i].name || o.a; break; }
		}
		cell.c.push(o);
	});
}

/* 18.7 Comments */
function parse_comments_xml(data/*:string*/, opts)/*:Array<RawComment>*/ {
	/* 18.7.6 CT_Comments */
	if(data.match(/<(?:\w+:)?comments *\/>/)) return [];
	var authors/*:Array<string>*/ = [];
	var commentList/*:Array<RawComment>*/ = [];
	var authtag = data.match(/<(?:\w+:)?authors>([\s\S]*)<\/(?:\w+:)?authors>/);
	if(authtag && authtag[1]) authtag[1].split(/<\/\w*:?author>/).forEach(function(x) {
		if(x === "" || x.trim() === "") return;
		var a = x.match(/<(?:\w+:)?author[^>]*>(.*)/);
		if(a) authors.push(a[1]);
	});
	var cmnttag = data.match(/<(?:\w+:)?commentList>([\s\S]*)<\/(?:\w+:)?commentList>/);
	if(cmnttag && cmnttag[1]) cmnttag[1].split(/<\/\w*:?comment>/).forEach(function(x) {
		if(x === "" || x.trim() === "") return;
		var cm = x.match(/<(?:\w+:)?comment[^>]*>/);
		if(!cm) return;
		var y = parsexmltag(cm[0]);
		var comment/*:RawComment*/ = ({ author: y.authorId && authors[y.authorId] || "sheetjsghost", ref: y.ref, guid: y.guid }/*:any*/);
		var cell = decode_cell(y.ref);
		if(opts.sheetRows && opts.sheetRows <= cell.r) return;
		var textMatch = x.match(/<(?:\w+:)?text>([\s\S]*)<\/(?:\w+:)?text>/);
		var rt = !!textMatch && !!textMatch[1] && parse_si(textMatch[1]) || {r:"",t:"",h:""};
		comment.r = rt.r;
		if(rt.r == "<t></t>") rt.t = rt.h = "";
		comment.t = (rt.t||"").replace(/\r\n/g,"\n").replace(/\r/g,"\n");
		if(opts.cellHTML) comment.h = rt.h;
		commentList.push(comment);
	});
	return commentList;
}

function write_comments_xml(data/*::, opts*/) {
	var o = [XML_HEADER, writextag('comments', null, { 'xmlns': XMLNS_main[0] })];

	var iauthor/*:Array<string>*/ = [];
	o.push("<authors>");
	data.forEach(function(x) { x[1].forEach(function(w) { var a = escapexml(w.a);
		if(iauthor.indexOf(a) == -1) {
			iauthor.push(a);
			o.push("<author>" + a + "</author>");
		}
		if(w.T && w.ID && iauthor.indexOf("tc=" + w.ID) == -1) {
			iauthor.push("tc=" + w.ID);
			o.push("<author>" + "tc=" + w.ID + "</author>");
		}
	}); });
	if(iauthor.length == 0) { iauthor.push("SheetJ5"); o.push("<author>SheetJ5</author>"); }
	o.push("</authors>");
	o.push("<commentList>");
	data.forEach(function(d) {
		/* 18.7.3 CT_Comment */
		var lastauthor = 0, ts = [];
		if(d[1][0] && d[1][0].T && d[1][0].ID) lastauthor = iauthor.indexOf("tc=" + d[1][0].ID);
		else d[1].forEach(function(c) {
			if(c.a) lastauthor = iauthor.indexOf(escapexml(c.a));
			ts.push(c.t||"");
		});
		o.push('<comment ref="' + d[0] + '" authorId="' + lastauthor + '"><text>');
		if(ts.length <= 1) o.push(writetag("t", escapexml(ts[0]||"")));
		else {
			/* based on Threaded Comments -> Comments projection */
			var t = "Comment:\n    " + (ts[0]) + "\n";
			for(var i = 1; i < ts.length; ++i) t += "Reply:\n    " + ts[i] + "\n";
			o.push(writetag("t", escapexml(t)));
		}
		o.push('</text></comment>');
	});
	o.push("</commentList>");
	if(o.length>2) { o[o.length] = ('</comments>'); o[1]=o[1].replace("/>",">"); }
	return o.join("");
}

/* [MS-XLSX] 2.1.17 */
function parse_tcmnt_xml(data/*:string*/, opts)/*:Array<RawComment>*/ {
	var out = [];
	var pass = false, comment = {}, tidx = 0;
	data.replace(tagregex, function xml_tcmnt(x, idx) {
		var y/*:any*/ = parsexmltag(x);
		switch(strip_ns(y[0])) {
			case '<?xml': break;

			/* 2.6.207 ThreadedComments CT_ThreadedComments */
			case '<ThreadedComments': break;
			case '</ThreadedComments>': break;

			/* 2.6.205 threadedComment CT_ThreadedComment */
			case '<threadedComment': comment = {author: y.personId, guid: y.id, ref: y.ref, T: 1}; break;
			case '</threadedComment>': if(comment.t != null) out.push(comment); break;

			case '<text>': case '<text': tidx = idx + x.length; break;
			case '</text>': comment.t = data.slice(tidx, idx).replace(/\r\n/g, "\n").replace(/\r/g, "\n"); break;

			/* 2.6.206 mentions CT_ThreadedCommentMentions TODO */
			case '<mentions': case '<mentions>': pass = true; break;
			case '</mentions>': pass = false; break;

			/* 2.6.202 mention CT_Mention TODO */

			/* 18.2.10 extLst CT_ExtensionList ? */
			case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
			/* 18.2.7  ext CT_Extension + */
			case '<ext': pass=true; break;
			case '</ext>': pass=false; break;

			default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in threaded comments');
		}
		return x;
	});
	return out;
}

function write_tcmnt_xml(comments, people, opts) {
	var o = [XML_HEADER, writextag('ThreadedComments', null, { 'xmlns': XMLNS.TCMNT }).replace(/[\/]>/, ">")];
	comments.forEach(function(carr) {
		var rootid = "";
		(carr[1] || []).forEach(function(c, idx) {
			if(!c.T) { delete c.ID; return; }
			if(c.a && people.indexOf(c.a) == -1) people.push(c.a);
			var tcopts = {
				ref: carr[0],
				id: "{54EE7951-7262-4200-6969-" + ("000000000000" + opts.tcid++).slice(-12) + "}"
			};
			if(idx == 0) rootid = tcopts.id;
			else tcopts.parentId = rootid;
			c.ID = tcopts.id;
			if(c.a) tcopts.personId = "{54EE7950-7262-4200-6969-" + ("000000000000" + people.indexOf(c.a)).slice(-12) + "}";
			o.push(writextag('threadedComment', writetag('text', c.t||""), tcopts));
		});
	});
	o.push('</ThreadedComments>');
	return o.join("");
}

/* [MS-XLSX] 2.1.18 */
function parse_people_xml(data/*:string*/, opts) {
	var out = [];
	var pass = false;
	data.replace(tagregex, function xml_tcmnt(x) {
		var y/*:any*/ = parsexmltag(x);
		switch(strip_ns(y[0])) {
			case '<?xml': break;

			/* 2.4.85 personList CT_PersonList */
			case '<personList': break;
			case '</personList>': break;

			/* 2.6.203 person CT_Person TODO: providers */
			case '<person': out.push({name: y.displayname, id: y.id }); break;
			case '</person>': break;

			/* 18.2.10 extLst CT_ExtensionList ? */
			case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
			/* 18.2.7  ext CT_Extension + */
			case '<ext': pass=true; break;
			case '</ext>': pass=false; break;

			default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in threaded comments');
		}
		return x;
	});
	return out;
}
function write_people_xml(people/*, opts*/) {
	var o = [XML_HEADER, writextag('personList', null, {
		'xmlns': XMLNS.TCMNT,
		'xmlns:x': XMLNS_main[0]
	}).replace(/[\/]>/, ">")];
	people.forEach(function(person, idx) {
		o.push(writextag('person', null, {
			displayName: person,
			id: "{54EE7950-7262-4200-6969-" + ("000000000000" + idx).slice(-12) + "}",
			userId: person,
			providerId: "None"
		}));
	});
	o.push("</personList>");
	return o.join("");
}
/* [MS-XLSB] 2.4.28 BrtBeginComment */
function parse_BrtBeginComment(data) {
	var out = {};
	out.iauthor = data.read_shift(4);
	var rfx = parse_UncheckedRfX(data, 16);
	out.rfx = rfx.s;
	out.ref = encode_cell(rfx.s);
	data.l += 16; /*var guid = parse_GUID(data); */
	return out;
}
function write_BrtBeginComment(data, o) {
	if(o == null) o = new_buf(36);
	o.write_shift(4, data[1].iauthor);
	write_UncheckedRfX((data[0]/*:any*/), o);
	o.write_shift(4, 0);
	o.write_shift(4, 0);
	o.write_shift(4, 0);
	o.write_shift(4, 0);
	return o;
}

/* [MS-XLSB] 2.4.327 BrtCommentAuthor */
var parse_BrtCommentAuthor = parse_XLWideString;
function write_BrtCommentAuthor(data) { return write_XLWideString(data.slice(0, 54)); }

/* [MS-XLSB] 2.1.7.8 Comments */
function parse_comments_bin(data, opts)/*:Array<RawComment>*/ {
	var out/*:Array<RawComment>*/ = [];
	var authors/*:Array<string>*/ = [];
	var c = {};
	var pass = false;
	recordhopper(data, function hopper_cmnt(val, R, RT) {
		switch(RT) {
			case 0x0278: /* 'BrtCommentAuthor' */
				authors.push(val); break;
			case 0x027B: /* 'BrtBeginComment' */
				c = val; break;
			case 0x027D: /* 'BrtCommentText' */
				c.t = val.t; c.h = val.h; c.r = val.r; break;
			case 0x027C: /* 'BrtEndComment' */
				c.author = authors[c.iauthor];
				delete (c/*:any*/).iauthor;
				if(opts.sheetRows && c.rfx && opts.sheetRows <= c.rfx.r) break;
				if(!c.t) c.t = "";
				delete c.rfx; out.push(c); break;

			case 0x0C00: /* 'BrtUid' */
				break;

			case 0x0023: /* 'BrtFRTBegin' */
				pass = true; break;
			case 0x0024: /* 'BrtFRTEnd' */
				pass = false; break;
			case 0x0025: /* 'BrtACBegin' */ break;
			case 0x0026: /* 'BrtACEnd' */ break;


			default:
				if(R.T){/* empty */}
				else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
		}
	});
	return out;
}

function write_comments_bin(data/*::, opts*/) {
	var ba = buf_array();
	var iauthor/*:Array<string>*/ = [];
	write_record(ba, 0x0274 /* BrtBeginComments */);

	write_record(ba, 0x0276 /* BrtBeginCommentAuthors */);
	data.forEach(function(comment) {
		comment[1].forEach(function(c) {
			if(iauthor.indexOf(c.a) > -1) return;
			iauthor.push(c.a.slice(0,54));
			write_record(ba, 0x0278 /* BrtCommentAuthor */, write_BrtCommentAuthor(c.a));
		});
	});
	write_record(ba, 0x0277 /* BrtEndCommentAuthors */);

	write_record(ba, 0x0279 /* BrtBeginCommentList */);
	data.forEach(function(comment) {
		comment[1].forEach(function(c) {
			c.iauthor = iauthor.indexOf(c.a);
			var range = {s:decode_cell(comment[0]),e:decode_cell(comment[0])};
			write_record(ba, 0x027B /* BrtBeginComment */, write_BrtBeginComment([range, c]));
			if(c.t && c.t.length > 0) write_record(ba, 0x027D /* BrtCommentText */, write_BrtCommentText(c));
			write_record(ba, 0x027C /* BrtEndComment */);
			delete c.iauthor;
		});
	});
	write_record(ba, 0x027A /* BrtEndCommentList */);

	write_record(ba, 0x0275 /* BrtEndComments */);
	return ba.end();
}
var CT_VBA = "application/vnd.ms-office.vbaProject";
function make_vba_xls(cfb) {
  var newcfb = CFB.utils.cfb_new({ root: "R" });
  cfb.FullPaths.forEach(function(p, i) {
    if (p.slice(-1) === "/" || !p.match(/_VBA_PROJECT_CUR/))
      return;
    var newpath = p.replace(/^[^\/]*/, "R").replace(/\/_VBA_PROJECT_CUR\u0000*/, "");
    CFB.utils.cfb_add(newcfb, newpath, cfb.FileIndex[i].content);
  });
  return CFB.write(newcfb);
}
function fill_vba_xls(cfb, vba) {
  vba.FullPaths.forEach(function(p, i) {
    if (i == 0)
      return;
    var newpath = p.replace(/[^\/]*[\/]/, "/_VBA_PROJECT_CUR/");
    if (newpath.slice(-1) !== "/")
      CFB.utils.cfb_add(cfb, newpath, vba.FileIndex[i].content);
  });
}
var VBAFMTS = ["xlsb", "xlsm", "xlam", "biff8", "xla"];
/* macro and dialog sheet stubs */
function parse_ds_bin(/*::data:any, opts, idx:number, rels, wb, themes, styles*/)/*:Worksheet*/ { return {'!type':'dialog'}; }
function parse_ds_xml(/*::data:any, opts, idx:number, rels, wb, themes, styles*/)/*:Worksheet*/ { return {'!type':'dialog'}; }
function parse_ms_bin(/*::data:any, opts, idx:number, rels, wb, themes, styles*/)/*:Worksheet*/ { return {'!type':'macro'}; }
function parse_ms_xml(/*::data:any, opts, idx:number, rels, wb, themes, styles*/)/*:Worksheet*/ { return {'!type':'macro'}; }
/* TODO: it will be useful to parse the function str */
var rc_to_a1 = /*#__PURE__*/(function(){
	var rcregex = /(^|[^A-Za-z_])R(\[?-?\d+\]|[1-9]\d*|)C(\[?-?\d+\]|[1-9]\d*|)(?![A-Za-z0-9_])/g;
	var rcbase/*:Cell*/ = ({r:0,c:0}/*:any*/);
	function rcfunc($$,$1,$2,$3) {
		var cRel = false, rRel = false;

		if($2.length == 0) rRel = true;
		else if($2.charAt(0) == "[") { rRel = true; $2 = $2.slice(1, -1); }

		if($3.length == 0) cRel = true;
		else if($3.charAt(0) == "[") { cRel = true; $3 = $3.slice(1, -1); }

		var R = $2.length>0?parseInt($2,10)|0:0, C = $3.length>0?parseInt($3,10)|0:0;

		if(cRel) C += rcbase.c; else --C;
		if(rRel) R += rcbase.r; else --R;
		return $1 + (cRel ? "" : "$") + encode_col(C) + (rRel ? "" : "$") + encode_row(R);
	}
	return function rc_to_a1(fstr/*:string*/, base/*:Cell*/)/*:string*/ {
		rcbase = base;
		return fstr.replace(rcregex, rcfunc);
	};
})();

var crefregex = /(^|[^._A-Z0-9])([$]?)([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])([$]?)(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})(?![_.\(A-Za-z0-9])/g;
var a1_to_rc = /*#__PURE__*/(function(){
	return function a1_to_rc(fstr/*:string*/, base/*:CellAddress*/) {
		return fstr.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
			var c = decode_col($3) - ($2 ? 0 : base.c);
			var r = decode_row($5) - ($4 ? 0 : base.r);
			var R = (r == 0 ? "" : !$4 ? "[" + r + "]" : (r+1));
			var C = (c == 0 ? "" : !$2 ? "[" + c + "]" : (c+1));
			return $1 + "R" + R + "C" + C;
		});
	};
})();

/* no defined name can collide with a valid cell address A1:XFD1048576 ... except LOG10! */
function shift_formula_str(f/*:string*/, delta/*:Cell*/)/*:string*/ {
	return f.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
		return $1+($2=="$" ? $2+$3 : encode_col(decode_col($3)+delta.c))+($4=="$" ? $4+$5 : encode_row(decode_row($5) + delta.r));
	});
}

function shift_formula_xlsx(f/*:string*/, range/*:string*/, cell/*:string*/)/*:string*/ {
	var r = decode_range(range), s = r.s, c = decode_cell(cell);
	var delta = {r:c.r - s.r, c:c.c - s.c};
	return shift_formula_str(f, delta);
}

/* TODO: parse formula */
function fuzzyfmla(f/*:string*/)/*:boolean*/ {
	if(f.length == 1) return false;
	return true;
}

function _xlfn(f/*:string*/)/*:string*/ {
	return f.replace(/_xlfn\./g,"");
}
function parseread1(blob) { blob.l+=1; return; }

/* [MS-XLS] 2.5.51 */
function parse_ColRelU(blob, length) {
	var c = blob.read_shift(length == 1 ? 1 : 2);
	return [c & 0x3FFF, (c >> 14) & 1, (c >> 15) & 1];
}

/* [MS-XLS] 2.5.198.105 ; [MS-XLSB] 2.5.97.89 */
function parse_RgceArea(blob, length, opts) {
	var w = 2;
	if(opts) {
		if(opts.biff >= 2 && opts.biff <= 5) return parse_RgceArea_BIFF2(blob, length, opts);
		else if(opts.biff == 12) w = 4;
	}
	var r=blob.read_shift(w), R=blob.read_shift(w);
	var c=parse_ColRelU(blob, 2);
	var C=parse_ColRelU(blob, 2);
	return { s:{r:r, c:c[0], cRel:c[1], rRel:c[2]}, e:{r:R, c:C[0], cRel:C[1], rRel:C[2]} };
}
/* BIFF 2-5 encodes flags in the row field */
function parse_RgceArea_BIFF2(blob/*::, length, opts*/) {
	var r=parse_ColRelU(blob, 2), R=parse_ColRelU(blob, 2);
	var c=blob.read_shift(1);
	var C=blob.read_shift(1);
	return { s:{r:r[0], c:c, cRel:r[1], rRel:r[2]}, e:{r:R[0], c:C, cRel:R[1], rRel:R[2]} };
}

/* [MS-XLS] 2.5.198.105 ; [MS-XLSB] 2.5.97.90 */
function parse_RgceAreaRel(blob, length, opts) {
	if(opts.biff < 8) return parse_RgceArea_BIFF2(blob, length, opts);
	var r=blob.read_shift(opts.biff == 12 ? 4 : 2), R=blob.read_shift(opts.biff == 12 ? 4 : 2);
	var c=parse_ColRelU(blob, 2);
	var C=parse_ColRelU(blob, 2);
	return { s:{r:r, c:c[0], cRel:c[1], rRel:c[2]}, e:{r:R, c:C[0], cRel:C[1], rRel:C[2]} };
}

/* [MS-XLS] 2.5.198.109 ; [MS-XLSB] 2.5.97.91 */
function parse_RgceLoc(blob, length, opts) {
	if(opts && opts.biff >= 2 && opts.biff <= 5) return parse_RgceLoc_BIFF2(blob, length, opts);
	var r = blob.read_shift(opts && opts.biff == 12 ? 4 : 2);
	var c = parse_ColRelU(blob, 2);
	return {r:r, c:c[0], cRel:c[1], rRel:c[2]};
}
function parse_RgceLoc_BIFF2(blob/*::, length, opts*/) {
	var r = parse_ColRelU(blob, 2);
	var c = blob.read_shift(1);
	return {r:r[0], c:c, cRel:r[1], rRel:r[2]};
}

/* [MS-XLS] 2.5.198.107, 2.5.47 */
function parse_RgceElfLoc(blob/*::, length, opts*/) {
	var r = blob.read_shift(2);
	var c = blob.read_shift(2);
	return {r:r, c:c & 0xFF, fQuoted:!!(c & 0x4000), cRel:c>>15, rRel:c>>15 };
}

/* [MS-XLS] 2.5.198.111 ; [MS-XLSB] 2.5.97.92 TODO */
function parse_RgceLocRel(blob, length, opts) {
	var biff = opts && opts.biff ? opts.biff : 8;
	if(biff >= 2 && biff <= 5) return parse_RgceLocRel_BIFF2(blob, length, opts);
	var r = blob.read_shift(biff >= 12 ? 4 : 2);
	var cl = blob.read_shift(2);
	var cRel = (cl & 0x4000) >> 14, rRel = (cl & 0x8000) >> 15;
	cl &= 0x3FFF;
	if(rRel == 1) while(r > 0x7FFFF) r -= 0x100000;
	if(cRel == 1) while(cl > 0x1FFF) cl = cl - 0x4000;
	return {r:r,c:cl,cRel:cRel,rRel:rRel};
}
function parse_RgceLocRel_BIFF2(blob/*::, length:number, opts*/) {
	var rl = blob.read_shift(2);
	var c = blob.read_shift(1);
	var rRel = (rl & 0x8000) >> 15, cRel = (rl & 0x4000) >> 14;
	rl &= 0x3FFF;
	if(rRel == 1 && rl >= 0x2000) rl = rl - 0x4000;
	if(cRel == 1 && c >= 0x80) c = c - 0x100;
	return {r:rl,c:c,cRel:cRel,rRel:rRel};
}

/* [MS-XLS] 2.5.198.27 ; [MS-XLSB] 2.5.97.18 */
function parse_PtgArea(blob, length, opts) {
	var type = (blob[blob.l++] & 0x60) >> 5;
	var area = parse_RgceArea(blob, opts.biff >= 2 && opts.biff <= 5 ? 6 : 8, opts);
	return [type, area];
}

/* [MS-XLS] 2.5.198.28 ; [MS-XLSB] 2.5.97.19 */
function parse_PtgArea3d(blob, length, opts) {
	var type = (blob[blob.l++] & 0x60) >> 5;
	var ixti = blob.read_shift(2, 'i');
	var w = 8;
	if(opts) switch(opts.biff) {
		case 5: blob.l += 12; w = 6; break;
		case 12: w = 12; break;
	}
	var area = parse_RgceArea(blob, w, opts);
	return [type, ixti, area];
}

/* [MS-XLS] 2.5.198.29 ; [MS-XLSB] 2.5.97.20 */
function parse_PtgAreaErr(blob, length, opts) {
	var type = (blob[blob.l++] & 0x60) >> 5;
	blob.l += opts && (opts.biff > 8) ? 12 : (opts.biff < 8 ? 6 : 8);
	return [type];
}
/* [MS-XLS] 2.5.198.30 ; [MS-XLSB] 2.5.97.21 */
function parse_PtgAreaErr3d(blob, length, opts) {
	var type = (blob[blob.l++] & 0x60) >> 5;
	var ixti = blob.read_shift(2);
	var w = 8;
	if(opts) switch(opts.biff) {
		case 5: blob.l += 12; w = 6; break;
		case 12: w = 12; break;
	}
	blob.l += w;
	return [type, ixti];
}

/* [MS-XLS] 2.5.198.31 ; [MS-XLSB] 2.5.97.22 */
function parse_PtgAreaN(blob, length, opts) {
	var type = (blob[blob.l++] & 0x60) >> 5;
	var area = parse_RgceAreaRel(blob, length - 1, opts);
	return [type, area];
}

/* [MS-XLS] 2.5.198.32 ; [MS-XLSB] 2.5.97.23 */
function parse_PtgArray(blob, length, opts) {
	var type = (blob[blob.l++] & 0x60) >> 5;
	blob.l += opts.biff == 2 ? 6 : opts.biff == 12 ? 14 : 7;
	return [type];
}

/* [MS-XLS] 2.5.198.33 ; [MS-XLSB] 2.5.97.24 */
function parse_PtgAttrBaxcel(blob) {
	var bitSemi = blob[blob.l+1] & 0x01; /* 1 = volatile */
	var bitBaxcel = 1;
	blob.l += 4;
	return [bitSemi, bitBaxcel];
}

/* [MS-XLS] 2.5.198.34 ; [MS-XLSB] 2.5.97.25 */
function parse_PtgAttrChoose(blob, length, opts)/*:Array<number>*/ {
	blob.l +=2;
	var offset = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
	var o/*:Array<number>*/ = [];
	/* offset is 1 less than the number of elements */
	for(var i = 0; i <= offset; ++i) o.push(blob.read_shift(opts && opts.biff == 2 ? 1 : 2));
	return o;
}

/* [MS-XLS] 2.5.198.35 ; [MS-XLSB] 2.5.97.26 */
function parse_PtgAttrGoto(blob, length, opts) {
	var bitGoto = (blob[blob.l+1] & 0xFF) ? 1 : 0;
	blob.l += 2;
	return [bitGoto, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
}

/* [MS-XLS] 2.5.198.36 ; [MS-XLSB] 2.5.97.27 */
function parse_PtgAttrIf(blob, length, opts) {
	var bitIf = (blob[blob.l+1] & 0xFF) ? 1 : 0;
	blob.l += 2;
	return [bitIf, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
}

/* [MS-XLSB] 2.5.97.28 */
function parse_PtgAttrIfError(blob) {
	var bitIf = (blob[blob.l+1] & 0xFF) ? 1 : 0;
	blob.l += 2;
	return [bitIf, blob.read_shift(2)];
}

/* [MS-XLS] 2.5.198.37 ; [MS-XLSB] 2.5.97.29 */
function parse_PtgAttrSemi(blob, length, opts) {
	var bitSemi = (blob[blob.l+1] & 0xFF) ? 1 : 0;
	blob.l += opts && opts.biff == 2 ? 3 : 4;
	return [bitSemi];
}

/* [MS-XLS] 2.5.198.40 ; [MS-XLSB] 2.5.97.32 */
function parse_PtgAttrSpaceType(blob/*::, length*/) {
	var type = blob.read_shift(1), cch = blob.read_shift(1);
	return [type, cch];
}

/* [MS-XLS] 2.5.198.38 ; [MS-XLSB] 2.5.97.30 */
function parse_PtgAttrSpace(blob) {
	blob.read_shift(2);
	return parse_PtgAttrSpaceType(blob, 2);
}

/* [MS-XLS] 2.5.198.39 ; [MS-XLSB] 2.5.97.31 */
function parse_PtgAttrSpaceSemi(blob) {
	blob.read_shift(2);
	return parse_PtgAttrSpaceType(blob, 2);
}

/* [MS-XLS] 2.5.198.84 ; [MS-XLSB] 2.5.97.68 TODO */
function parse_PtgRef(blob, length, opts) {
	//var ptg = blob[blob.l] & 0x1F;
	var type = (blob[blob.l] & 0x60)>>5;
	blob.l += 1;
	var loc = parse_RgceLoc(blob, 0, opts);
	return [type, loc];
}

/* [MS-XLS] 2.5.198.88 ; [MS-XLSB] 2.5.97.72 TODO */
function parse_PtgRefN(blob, length, opts) {
	var type = (blob[blob.l] & 0x60)>>5;
	blob.l += 1;
	var loc = parse_RgceLocRel(blob, 0, opts);
	return [type, loc];
}

/* [MS-XLS] 2.5.198.85 ; [MS-XLSB] 2.5.97.69 TODO */
function parse_PtgRef3d(blob, length, opts) {
	var type = (blob[blob.l] & 0x60)>>5;
	blob.l += 1;
	var ixti = blob.read_shift(2); // XtiIndex
	if(opts && opts.biff == 5) blob.l += 12;
	var loc = parse_RgceLoc(blob, 0, opts); // TODO: or RgceLocRel
	return [type, ixti, loc];
}


/* [MS-XLS] 2.5.198.62 ; [MS-XLSB] 2.5.97.45 TODO */
function parse_PtgFunc(blob, length, opts) {
	//var ptg = blob[blob.l] & 0x1F;
	var type = (blob[blob.l] & 0x60)>>5;
	blob.l += 1;
	var iftab = blob.read_shift(opts && opts.biff <= 3 ? 1 : 2);
	return [FtabArgc[iftab], Ftab[iftab], type];
}
/* [MS-XLS] 2.5.198.63 ; [MS-XLSB] 2.5.97.46 TODO */
function parse_PtgFuncVar(blob, length, opts) {
	var type = blob[blob.l++];
	var cparams = blob.read_shift(1), tab = opts && opts.biff <= 3 ? [(type == 0x58 ? -1 : 0), blob.read_shift(1)]: parsetab(blob);
	return [cparams, (tab[0] === 0 ? Ftab : Cetab)[tab[1]]];
}

function parsetab(blob) {
	return [blob[blob.l+1]>>7, blob.read_shift(2) & 0x7FFF];
}

/* [MS-XLS] 2.5.198.41 ; [MS-XLSB] 2.5.97.33 */
function parse_PtgAttrSum(blob, length, opts) {
	blob.l += opts && opts.biff == 2 ? 3 : 4; return;
}

/* [MS-XLS] 2.5.198.58 ; [MS-XLSB] 2.5.97.40 */
function parse_PtgExp(blob, length, opts) {
	blob.l++;
	if(opts && opts.biff == 12) return [blob.read_shift(4, 'i'), 0];
	var row = blob.read_shift(2);
	var col = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
	return [row, col];
}

/* [MS-XLS] 2.5.198.57 ; [MS-XLSB] 2.5.97.39 */
function parse_PtgErr(blob) { blob.l++; return BErr[blob.read_shift(1)]; }

/* [MS-XLS] 2.5.198.66 ; [MS-XLSB] 2.5.97.49 */
function parse_PtgInt(blob) { blob.l++; return blob.read_shift(2); }

/* [MS-XLS] 2.5.198.42 ; [MS-XLSB] 2.5.97.34 */
function parse_PtgBool(blob) { blob.l++; return blob.read_shift(1)!==0;}

/* [MS-XLS] 2.5.198.79 ; [MS-XLSB] 2.5.97.63 */
function parse_PtgNum(blob) { blob.l++; return parse_Xnum(blob, 8); }

/* [MS-XLS] 2.5.198.89 ; [MS-XLSB] 2.5.97.74 */
function parse_PtgStr(blob, length, opts) { blob.l++; return parse_ShortXLUnicodeString(blob, length-1, opts); }

/* [MS-XLS] 2.5.192.112 + 2.5.192.11{3,4,5,6,7} */
/* [MS-XLSB] 2.5.97.93 + 2.5.97.9{4,5,6,7} */
function parse_SerAr(blob, biff/*:number*/) {
	var val = [blob.read_shift(1)];
	if(biff == 12) switch(val[0]) {
		case 0x02: val[0] = 0x04; break; /* SerBool */
		case 0x04: val[0] = 0x10; break; /* SerErr */
		case 0x00: val[0] = 0x01; break; /* SerNum */
		case 0x01: val[0] = 0x02; break; /* SerStr */
	}
	switch(val[0]) {
		case 0x04: /* SerBool -- boolean */
			val[1] = parsebool(blob, 1) ? 'TRUE' : 'FALSE';
			if(biff != 12) blob.l += 7; break;
		case 0x25: /* appears to be an alias */
		case 0x10: /* SerErr -- error */
			val[1] = BErr[blob[blob.l]];
			blob.l += ((biff == 12) ? 4 : 8); break;
		case 0x00: /* SerNil -- honestly, I'm not sure how to reproduce this */
			blob.l += 8; break;
		case 0x01: /* SerNum -- Xnum */
			val[1] = parse_Xnum(blob, 8); break;
		case 0x02: /* SerStr -- XLUnicodeString (<256 chars) */
			val[1] = parse_XLUnicodeString2(blob, 0, {biff:biff > 0 && biff < 8 ? 2 : biff}); break;
		default: throw new Error("Bad SerAr: " + val[0]); /* Unreachable */
	}
	return val;
}

/* [MS-XLS] 2.5.198.61 ; [MS-XLSB] 2.5.97.44 */
function parse_PtgExtraMem(blob, cce, opts) {
	var count = blob.read_shift((opts.biff == 12) ? 4 : 2);
	var out/*:Array<Range>*/ = [];
	for(var i = 0; i != count; ++i) out.push(((opts.biff == 12) ? parse_UncheckedRfX : parse_Ref8U)(blob, 8));
	return out;
}

/* [MS-XLS] 2.5.198.59 ; [MS-XLSB] 2.5.97.41 */
function parse_PtgExtraArray(blob, length, opts) {
	var rows = 0, cols = 0;
	if(opts.biff == 12) {
		rows = blob.read_shift(4); // DRw
		cols = blob.read_shift(4); // DCol
	} else {
		cols = 1 + blob.read_shift(1); //DColByteU
		rows = 1 + blob.read_shift(2); //DRw
	}
	if(opts.biff >= 2 && opts.biff < 8) { --rows; if(--cols == 0) cols = 0x100; }
	// $FlowIgnore
	for(var i = 0, o/*:Array<Array<any>>*/ = []; i != rows && (o[i] = []); ++i)
		for(var j = 0; j != cols; ++j) o[i][j] = parse_SerAr(blob, opts.biff);
	return o;
}

/* [MS-XLS] 2.5.198.76 ; [MS-XLSB] 2.5.97.60 */
function parse_PtgName(blob, length, opts) {
	var type = (blob.read_shift(1) >>> 5) & 0x03;
	var w = (!opts || (opts.biff >= 8)) ? 4 : 2;
	var nameindex = blob.read_shift(w);
	switch(opts.biff) {
		case 2: blob.l += 5; break;
		case 3: case 4: blob.l += 8; break;
		case 5: blob.l += 12; break;
	}
	return [type, 0, nameindex];
}

/* [MS-XLS] 2.5.198.77 ; [MS-XLSB] 2.5.97.61 */
function parse_PtgNameX(blob, length, opts) {
	if(opts.biff == 5) return parse_PtgNameX_BIFF5(blob, length, opts);
	var type = (blob.read_shift(1) >>> 5) & 0x03;
	var ixti = blob.read_shift(2); // XtiIndex
	var nameindex = blob.read_shift(4);
	return [type, ixti, nameindex];
}
function parse_PtgNameX_BIFF5(blob/*::, length, opts*/) {
	var type = (blob.read_shift(1) >>> 5) & 0x03;
	var ixti = blob.read_shift(2, 'i'); // XtiIndex
	blob.l += 8;
	var nameindex = blob.read_shift(2);
	blob.l += 12;
	return [type, ixti, nameindex];
}

/* [MS-XLS] 2.5.198.70 ; [MS-XLSB] 2.5.97.54 */
function parse_PtgMemArea(blob, length, opts) {
	var type = (blob.read_shift(1) >>> 5) & 0x03;
	blob.l += (opts && opts.biff == 2 ? 3 : 4);
	var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
	return [type, cce];
}

/* [MS-XLS] 2.5.198.72 ; [MS-XLSB] 2.5.97.56 */
function parse_PtgMemFunc(blob, length, opts) {
	var type = (blob.read_shift(1) >>> 5) & 0x03;
	var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
	return [type, cce];
}


/* [MS-XLS] 2.5.198.86 ; [MS-XLSB] 2.5.97.69 */
function parse_PtgRefErr(blob, length, opts) {
	var type = (blob.read_shift(1) >>> 5) & 0x03;
	blob.l += 4;
	if(opts.biff < 8) blob.l--;
	if(opts.biff == 12) blob.l += 2;
	return [type];
}

/* [MS-XLS] 2.5.198.87 ; [MS-XLSB] 2.5.97.71 */
function parse_PtgRefErr3d(blob, length, opts) {
	var type = (blob[blob.l++] & 0x60) >> 5;
	var ixti = blob.read_shift(2);
	var w = 4;
	if(opts) switch(opts.biff) {
		case 5: w = 15; break;
		case 12: w = 6; break;
	}
	blob.l += w;
	return [type, ixti];
}

/* [MS-XLS] 2.5.198.71 ; [MS-XLSB] 2.5.97.55 */
var parse_PtgMemErr = parsenoop;
/* [MS-XLS] 2.5.198.73  ; [MS-XLSB] 2.5.97.57 */
var parse_PtgMemNoMem = parsenoop;
/* [MS-XLS] 2.5.198.92 */
var parse_PtgTbl = parsenoop;

function parse_PtgElfLoc(blob, length, opts) {
	blob.l += 2;
	return [parse_RgceElfLoc(blob, 4, opts)];
}
function parse_PtgElfNoop(blob/*::, length, opts*/) {
	blob.l += 6;
	return [];
}
/* [MS-XLS] 2.5.198.46 */
var parse_PtgElfCol = parse_PtgElfLoc;
/* [MS-XLS] 2.5.198.47 */
var parse_PtgElfColS = parse_PtgElfNoop;
/* [MS-XLS] 2.5.198.48 */
var parse_PtgElfColSV = parse_PtgElfNoop;
/* [MS-XLS] 2.5.198.49 */
var parse_PtgElfColV = parse_PtgElfLoc;
/* [MS-XLS] 2.5.198.50 */
function parse_PtgElfLel(blob/*::, length, opts*/) {
	blob.l += 2;
	return [parseuint16(blob), blob.read_shift(2) & 0x01];
}
/* [MS-XLS] 2.5.198.51 */
var parse_PtgElfRadical = parse_PtgElfLoc;
/* [MS-XLS] 2.5.198.52 */
var parse_PtgElfRadicalLel = parse_PtgElfLel;
/* [MS-XLS] 2.5.198.53 */
var parse_PtgElfRadicalS = parse_PtgElfNoop;
/* [MS-XLS] 2.5.198.54 */
var parse_PtgElfRw = parse_PtgElfLoc;
/* [MS-XLS] 2.5.198.55 */
var parse_PtgElfRwV = parse_PtgElfLoc;

/* [MS-XLSB] 2.5.97.52 TODO */
var PtgListRT = [
	"Data",
	"All",
	"Headers",
	"??",
	"?Data2",
	"??",
	"?DataHeaders",
	"??",
	"Totals",
	"??",
	"??",
	"??",
	"?DataTotals",
	"??",
	"??",
	"??",
	"?Current"
];
function parse_PtgList(blob/*::, length, opts*/) {
	blob.l += 2;
	var ixti = blob.read_shift(2);
	var flags = blob.read_shift(2);
	var idx = blob.read_shift(4);
	var c = blob.read_shift(2);
	var C = blob.read_shift(2);
	var rt = PtgListRT[(flags >> 2) & 0x1F];
	return {ixti: ixti, coltype:(flags&0x3), rt:rt, idx:idx, c:c, C:C};
}
/* [MS-XLS] 2.5.198.91 ; [MS-XLSB] 2.5.97.76 */
function parse_PtgSxName(blob/*::, length, opts*/) {
	blob.l += 2;
	return [blob.read_shift(4)];
}

/* [XLS] old spec */
function parse_PtgSheet(blob, length, opts) {
	blob.l += 5;
	blob.l += 2;
	blob.l += (opts.biff == 2 ? 1 : 4);
	return ["PTGSHEET"];
}
function parse_PtgEndSheet(blob, length, opts) {
	blob.l += (opts.biff == 2 ? 4 : 5);
	return ["PTGENDSHEET"];
}
function parse_PtgMemAreaN(blob/*::, length, opts*/) {
	var type = (blob.read_shift(1) >>> 5) & 0x03;
	var cce = blob.read_shift(2);
	return [type, cce];
}
function parse_PtgMemNoMemN(blob/*::, length, opts*/) {
	var type = (blob.read_shift(1) >>> 5) & 0x03;
	var cce = blob.read_shift(2);
	return [type, cce];
}
function parse_PtgAttrNoop(blob/*::, length, opts*/) {
	blob.l += 4;
	return [0, 0];
}

/* [MS-XLS] 2.5.198.25 ; [MS-XLSB] 2.5.97.16 */
var PtgTypes = {
	/*::[*/0x01/*::]*/: { n:'PtgExp', f:parse_PtgExp },
	/*::[*/0x02/*::]*/: { n:'PtgTbl', f:parse_PtgTbl },
	/*::[*/0x03/*::]*/: { n:'PtgAdd', f:parseread1 },
	/*::[*/0x04/*::]*/: { n:'PtgSub', f:parseread1 },
	/*::[*/0x05/*::]*/: { n:'PtgMul', f:parseread1 },
	/*::[*/0x06/*::]*/: { n:'PtgDiv', f:parseread1 },
	/*::[*/0x07/*::]*/: { n:'PtgPower', f:parseread1 },
	/*::[*/0x08/*::]*/: { n:'PtgConcat', f:parseread1 },
	/*::[*/0x09/*::]*/: { n:'PtgLt', f:parseread1 },
	/*::[*/0x0A/*::]*/: { n:'PtgLe', f:parseread1 },
	/*::[*/0x0B/*::]*/: { n:'PtgEq', f:parseread1 },
	/*::[*/0x0C/*::]*/: { n:'PtgGe', f:parseread1 },
	/*::[*/0x0D/*::]*/: { n:'PtgGt', f:parseread1 },
	/*::[*/0x0E/*::]*/: { n:'PtgNe', f:parseread1 },
	/*::[*/0x0F/*::]*/: { n:'PtgIsect', f:parseread1 },
	/*::[*/0x10/*::]*/: { n:'PtgUnion', f:parseread1 },
	/*::[*/0x11/*::]*/: { n:'PtgRange', f:parseread1 },
	/*::[*/0x12/*::]*/: { n:'PtgUplus', f:parseread1 },
	/*::[*/0x13/*::]*/: { n:'PtgUminus', f:parseread1 },
	/*::[*/0x14/*::]*/: { n:'PtgPercent', f:parseread1 },
	/*::[*/0x15/*::]*/: { n:'PtgParen', f:parseread1 },
	/*::[*/0x16/*::]*/: { n:'PtgMissArg', f:parseread1 },
	/*::[*/0x17/*::]*/: { n:'PtgStr', f:parse_PtgStr },
	/*::[*/0x1A/*::]*/: { n:'PtgSheet', f:parse_PtgSheet },
	/*::[*/0x1B/*::]*/: { n:'PtgEndSheet', f:parse_PtgEndSheet },
	/*::[*/0x1C/*::]*/: { n:'PtgErr', f:parse_PtgErr },
	/*::[*/0x1D/*::]*/: { n:'PtgBool', f:parse_PtgBool },
	/*::[*/0x1E/*::]*/: { n:'PtgInt', f:parse_PtgInt },
	/*::[*/0x1F/*::]*/: { n:'PtgNum', f:parse_PtgNum },
	/*::[*/0x20/*::]*/: { n:'PtgArray', f:parse_PtgArray },
	/*::[*/0x21/*::]*/: { n:'PtgFunc', f:parse_PtgFunc },
	/*::[*/0x22/*::]*/: { n:'PtgFuncVar', f:parse_PtgFuncVar },
	/*::[*/0x23/*::]*/: { n:'PtgName', f:parse_PtgName },
	/*::[*/0x24/*::]*/: { n:'PtgRef', f:parse_PtgRef },
	/*::[*/0x25/*::]*/: { n:'PtgArea', f:parse_PtgArea },
	/*::[*/0x26/*::]*/: { n:'PtgMemArea', f:parse_PtgMemArea },
	/*::[*/0x27/*::]*/: { n:'PtgMemErr', f:parse_PtgMemErr },
	/*::[*/0x28/*::]*/: { n:'PtgMemNoMem', f:parse_PtgMemNoMem },
	/*::[*/0x29/*::]*/: { n:'PtgMemFunc', f:parse_PtgMemFunc },
	/*::[*/0x2A/*::]*/: { n:'PtgRefErr', f:parse_PtgRefErr },
	/*::[*/0x2B/*::]*/: { n:'PtgAreaErr', f:parse_PtgAreaErr },
	/*::[*/0x2C/*::]*/: { n:'PtgRefN', f:parse_PtgRefN },
	/*::[*/0x2D/*::]*/: { n:'PtgAreaN', f:parse_PtgAreaN },
	/*::[*/0x2E/*::]*/: { n:'PtgMemAreaN', f:parse_PtgMemAreaN },
	/*::[*/0x2F/*::]*/: { n:'PtgMemNoMemN', f:parse_PtgMemNoMemN },
	/*::[*/0x39/*::]*/: { n:'PtgNameX', f:parse_PtgNameX },
	/*::[*/0x3A/*::]*/: { n:'PtgRef3d', f:parse_PtgRef3d },
	/*::[*/0x3B/*::]*/: { n:'PtgArea3d', f:parse_PtgArea3d },
	/*::[*/0x3C/*::]*/: { n:'PtgRefErr3d', f:parse_PtgRefErr3d },
	/*::[*/0x3D/*::]*/: { n:'PtgAreaErr3d', f:parse_PtgAreaErr3d },
	/*::[*/0xFF/*::]*/: {}
};
/* These are duplicated in the PtgTypes table */
var PtgDupes = {
	/*::[*/0x40/*::]*/: 0x20, /*::[*/0x60/*::]*/: 0x20,
	/*::[*/0x41/*::]*/: 0x21, /*::[*/0x61/*::]*/: 0x21,
	/*::[*/0x42/*::]*/: 0x22, /*::[*/0x62/*::]*/: 0x22,
	/*::[*/0x43/*::]*/: 0x23, /*::[*/0x63/*::]*/: 0x23,
	/*::[*/0x44/*::]*/: 0x24, /*::[*/0x64/*::]*/: 0x24,
	/*::[*/0x45/*::]*/: 0x25, /*::[*/0x65/*::]*/: 0x25,
	/*::[*/0x46/*::]*/: 0x26, /*::[*/0x66/*::]*/: 0x26,
	/*::[*/0x47/*::]*/: 0x27, /*::[*/0x67/*::]*/: 0x27,
	/*::[*/0x48/*::]*/: 0x28, /*::[*/0x68/*::]*/: 0x28,
	/*::[*/0x49/*::]*/: 0x29, /*::[*/0x69/*::]*/: 0x29,
	/*::[*/0x4A/*::]*/: 0x2A, /*::[*/0x6A/*::]*/: 0x2A,
	/*::[*/0x4B/*::]*/: 0x2B, /*::[*/0x6B/*::]*/: 0x2B,
	/*::[*/0x4C/*::]*/: 0x2C, /*::[*/0x6C/*::]*/: 0x2C,
	/*::[*/0x4D/*::]*/: 0x2D, /*::[*/0x6D/*::]*/: 0x2D,
	/*::[*/0x4E/*::]*/: 0x2E, /*::[*/0x6E/*::]*/: 0x2E,
	/*::[*/0x4F/*::]*/: 0x2F, /*::[*/0x6F/*::]*/: 0x2F,
	/*::[*/0x58/*::]*/: 0x22, /*::[*/0x78/*::]*/: 0x22,
	/*::[*/0x59/*::]*/: 0x39, /*::[*/0x79/*::]*/: 0x39,
	/*::[*/0x5A/*::]*/: 0x3A, /*::[*/0x7A/*::]*/: 0x3A,
	/*::[*/0x5B/*::]*/: 0x3B, /*::[*/0x7B/*::]*/: 0x3B,
	/*::[*/0x5C/*::]*/: 0x3C, /*::[*/0x7C/*::]*/: 0x3C,
	/*::[*/0x5D/*::]*/: 0x3D, /*::[*/0x7D/*::]*/: 0x3D
};

var Ptg18 = {
	/*::[*/0x01/*::]*/: { n:'PtgElfLel', f:parse_PtgElfLel },
	/*::[*/0x02/*::]*/: { n:'PtgElfRw', f:parse_PtgElfRw },
	/*::[*/0x03/*::]*/: { n:'PtgElfCol', f:parse_PtgElfCol },
	/*::[*/0x06/*::]*/: { n:'PtgElfRwV', f:parse_PtgElfRwV },
	/*::[*/0x07/*::]*/: { n:'PtgElfColV', f:parse_PtgElfColV },
	/*::[*/0x0A/*::]*/: { n:'PtgElfRadical', f:parse_PtgElfRadical },
	/*::[*/0x0B/*::]*/: { n:'PtgElfRadicalS', f:parse_PtgElfRadicalS },
	/*::[*/0x0D/*::]*/: { n:'PtgElfColS', f:parse_PtgElfColS },
	/*::[*/0x0F/*::]*/: { n:'PtgElfColSV', f:parse_PtgElfColSV },
	/*::[*/0x10/*::]*/: { n:'PtgElfRadicalLel', f:parse_PtgElfRadicalLel },
	/*::[*/0x19/*::]*/: { n:'PtgList', f:parse_PtgList },
	/*::[*/0x1D/*::]*/: { n:'PtgSxName', f:parse_PtgSxName },
	/*::[*/0xFF/*::]*/: {}
};
var Ptg19 = {
	/*::[*/0x00/*::]*/: { n:'PtgAttrNoop', f:parse_PtgAttrNoop },
	/*::[*/0x01/*::]*/: { n:'PtgAttrSemi', f:parse_PtgAttrSemi },
	/*::[*/0x02/*::]*/: { n:'PtgAttrIf', f:parse_PtgAttrIf },
	/*::[*/0x04/*::]*/: { n:'PtgAttrChoose', f:parse_PtgAttrChoose },
	/*::[*/0x08/*::]*/: { n:'PtgAttrGoto', f:parse_PtgAttrGoto },
	/*::[*/0x10/*::]*/: { n:'PtgAttrSum', f:parse_PtgAttrSum },
	/*::[*/0x20/*::]*/: { n:'PtgAttrBaxcel', f:parse_PtgAttrBaxcel },
	/*::[*/0x21/*::]*/: { n:'PtgAttrBaxcel', f:parse_PtgAttrBaxcel },
	/*::[*/0x40/*::]*/: { n:'PtgAttrSpace', f:parse_PtgAttrSpace },
	/*::[*/0x41/*::]*/: { n:'PtgAttrSpaceSemi', f:parse_PtgAttrSpaceSemi },
	/*::[*/0x80/*::]*/: { n:'PtgAttrIfError', f:parse_PtgAttrIfError },
	/*::[*/0xFF/*::]*/: {}
};

/* [MS-XLS] 2.5.198.103 ; [MS-XLSB] 2.5.97.87 */
function parse_RgbExtra(blob, length, rgce, opts) {
	if(opts.biff < 8) return parsenoop(blob, length);
	var target = blob.l + length;
	var o = [];
	for(var i = 0; i !== rgce.length; ++i) {
		switch(rgce[i][0]) {
			case 'PtgArray': /* PtgArray -> PtgExtraArray */
				rgce[i][1] = parse_PtgExtraArray(blob, 0, opts);
				o.push(rgce[i][1]);
				break;
			case 'PtgMemArea': /* PtgMemArea -> PtgExtraMem */
				rgce[i][2] = parse_PtgExtraMem(blob, rgce[i][1], opts);
				o.push(rgce[i][2]);
				break;
			case 'PtgExp': /* PtgExp -> PtgExtraCol */
				if(opts && opts.biff == 12) {
					rgce[i][1][1] = blob.read_shift(4);
					o.push(rgce[i][1]);
				} break;
			case 'PtgList': /* TODO: PtgList -> PtgExtraList */
			case 'PtgElfRadicalS': /* TODO: PtgElfRadicalS -> PtgExtraElf */
			case 'PtgElfColS': /* TODO: PtgElfColS -> PtgExtraElf */
			case 'PtgElfColSV': /* TODO: PtgElfColSV -> PtgExtraElf */
				throw "Unsupported " + rgce[i][0];
			default: break;
		}
	}
	length = target - blob.l;
	/* note: this is technically an error but Excel disregards */
	//if(target !== blob.l && blob.l !== target - length) throw new Error(target + " != " + blob.l);
	if(length !== 0) o.push(parsenoop(blob, length));
	return o;
}

/* [MS-XLS] 2.5.198.104 ; [MS-XLSB] 2.5.97.88 */
function parse_Rgce(blob, length, opts) {
	var target = blob.l + length;
	var R, id, ptgs = [];
	while(target != blob.l) {
		length = target - blob.l;
		id = blob[blob.l];
		R = PtgTypes[id] || PtgTypes[PtgDupes[id]];
		if(id === 0x18 || id === 0x19) R = (id === 0x18 ? Ptg18 : Ptg19)[blob[blob.l + 1]];
		if(!R || !R.f) { /*ptgs.push*/(parsenoop(blob, length)); }
		else { ptgs.push([R.n, R.f(blob, length, opts)]); }
	}
	return ptgs;
}

function stringify_array(f/*:Array<Array<string>>*/)/*:string*/ {
	var o/*:Array<string>*/ = [];
	for(var i = 0; i < f.length; ++i) {
		var x = f[i], r/*:Array<string>*/ = [];
		for(var j = 0; j < x.length; ++j) {
			var y = x[j];
			if(y) switch(y[0]) {
				// TODO: handle embedded quotes
				case 0x02:
					/*:: if(typeof y[1] != 'string') throw "unreachable"; */
					r.push('"' + y[1].replace(/"/g,'""') + '"'); break;
				default: r.push(y[1]);
			} else r.push("");
		}
		o.push(r.join(","));
	}
	return o.join(";");
}

/* [MS-XLS] 2.2.2 ; [MS-XLSB] 2.2.2 TODO */
var PtgBinOp = {
	PtgAdd: "+",
	PtgConcat: "&",
	PtgDiv: "/",
	PtgEq: "=",
	PtgGe: ">=",
	PtgGt: ">",
	PtgLe: "<=",
	PtgLt: "<",
	PtgMul: "*",
	PtgNe: "<>",
	PtgPower: "^",
	PtgSub: "-"
};

// List of invalid characters needs to be tested further
function formula_quote_sheet_name(sname/*:string*/, opts)/*:string*/ {
	if(!sname && !(opts && opts.biff <= 5 && opts.biff >= 2)) throw new Error("empty sheet name");
	if (/[^\w\u4E00-\u9FFF\u3040-\u30FF]/.test(sname)) return "'" + sname + "'";
	return sname;
}
function get_ixti_raw(supbooks, ixti/*:number*/, opts)/*:string*/ {
	if(!supbooks) return "SH33TJSERR0";
	if(opts.biff > 8 && (!supbooks.XTI || !supbooks.XTI[ixti])) return supbooks.SheetNames[ixti];
	if(!supbooks.XTI) return "SH33TJSERR6";
	var XTI = supbooks.XTI[ixti];
	if(opts.biff < 8) {
		if(ixti > 10000) ixti-= 65536;
		if(ixti < 0) ixti = -ixti;
		return ixti == 0 ? "" : supbooks.XTI[ixti - 1];
	}
	if(!XTI) return "SH33TJSERR1";
	var o = "";
	if(opts.biff > 8) switch(supbooks[XTI[0]][0]) {
		case 0x0165: /* 'BrtSupSelf' */
			o = XTI[1] == -1 ? "#REF" : supbooks.SheetNames[XTI[1]];
			return XTI[1] == XTI[2] ? o : o + ":" + supbooks.SheetNames[XTI[2]];
		case 0x0166: /* 'BrtSupSame' */
			if(opts.SID != null) return supbooks.SheetNames[opts.SID];
			return "SH33TJSSAME" + supbooks[XTI[0]][0];
		case 0x0163: /* 'BrtSupBookSrc' */
			/* falls through */
		default: return "SH33TJSSRC" + supbooks[XTI[0]][0];
	}
	switch(supbooks[XTI[0]][0][0]) {
		case 0x0401:
			o = XTI[1] == -1 ? "#REF" : (supbooks.SheetNames[XTI[1]] || "SH33TJSERR3");
			return XTI[1] == XTI[2] ? o : o + ":" + supbooks.SheetNames[XTI[2]];
		case 0x3A01: return supbooks[XTI[0]].slice(1).map(function(name) { return name.Name; }).join(";;"); //return "SH33TJSERR8";
		default:
			if(!supbooks[XTI[0]][0][3]) return "SH33TJSERR2";
			o = XTI[1] == -1 ? "#REF" : (supbooks[XTI[0]][0][3][XTI[1]] || "SH33TJSERR4");
			return XTI[1] == XTI[2] ? o : o + ":" + supbooks[XTI[0]][0][3][XTI[2]];
	}
}
function get_ixti(supbooks, ixti/*:number*/, opts)/*:string*/ {
	var ixtiraw = get_ixti_raw(supbooks, ixti, opts);
	return ixtiraw == "#REF" ? ixtiraw : formula_quote_sheet_name(ixtiraw, opts);
}
function stringify_formula(formula/*Array<any>*/, range, cell/*:any*/, supbooks, opts)/*:string*/ {
	var biff = (opts && opts.biff) || 8;
	var _range = /*range != null ? range :*/ {s:{c:0, r:0},e:{c:0, r:0}};
	var stack/*:Array<string>*/ = [], e1, e2, /*::type,*/ c/*:CellAddress*/, ixti=0, nameidx=0, r, sname="";
	if(!formula[0] || !formula[0][0]) return "";
	var last_sp = -1, sp = "";
	for(var ff = 0, fflen = formula[0].length; ff < fflen; ++ff) {
		var f = formula[0][ff];
		switch(f[0]) {
			case 'PtgUminus': /* [MS-XLS] 2.5.198.93 */
				stack.push("-" + stack.pop()); break;
			case 'PtgUplus': /* [MS-XLS] 2.5.198.95 */
				stack.push("+" + stack.pop()); break;
			case 'PtgPercent': /* [MS-XLS] 2.5.198.81 */
				stack.push(stack.pop() + "%"); break;

			case 'PtgAdd':    /* [MS-XLS] 2.5.198.26 */
			case 'PtgConcat': /* [MS-XLS] 2.5.198.43 */
			case 'PtgDiv':    /* [MS-XLS] 2.5.198.45 */
			case 'PtgEq':     /* [MS-XLS] 2.5.198.56 */
			case 'PtgGe':     /* [MS-XLS] 2.5.198.64 */
			case 'PtgGt':     /* [MS-XLS] 2.5.198.65 */
			case 'PtgLe':     /* [MS-XLS] 2.5.198.68 */
			case 'PtgLt':     /* [MS-XLS] 2.5.198.69 */
			case 'PtgMul':    /* [MS-XLS] 2.5.198.75 */
			case 'PtgNe':     /* [MS-XLS] 2.5.198.78 */
			case 'PtgPower':  /* [MS-XLS] 2.5.198.82 */
			case 'PtgSub':    /* [MS-XLS] 2.5.198.90 */
				e1 = stack.pop(); e2 = stack.pop();
				if(last_sp >= 0) {
					switch(formula[0][last_sp][1][0]) {
						case 0:
							// $FlowIgnore
							sp = fill$1(" ", formula[0][last_sp][1][1]); break;
						case 1:
							// $FlowIgnore
							sp = fill$1("\r", formula[0][last_sp][1][1]); break;
						default:
							sp = "";
							// $FlowIgnore
							if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
					}
					e2 = e2 + sp;
					last_sp = -1;
				}
				stack.push(e2+PtgBinOp[f[0]]+e1);
				break;

			case 'PtgIsect': /* [MS-XLS] 2.5.198.67 */
				e1 = stack.pop(); e2 = stack.pop();
				stack.push(e2+" "+e1);
				break;
			case 'PtgUnion': /* [MS-XLS] 2.5.198.94 */
				e1 = stack.pop(); e2 = stack.pop();
				stack.push(e2+","+e1);
				break;
			case 'PtgRange': /* [MS-XLS] 2.5.198.83 */
				e1 = stack.pop(); e2 = stack.pop();
				stack.push(e2+":"+e1);
				break;

			case 'PtgAttrChoose': /* [MS-XLS] 2.5.198.34 */
				break;
			case 'PtgAttrGoto': /* [MS-XLS] 2.5.198.35 */
				break;
			case 'PtgAttrIf': /* [MS-XLS] 2.5.198.36 */
				break;
			case 'PtgAttrIfError': /* [MS-XLSB] 2.5.97.28 */
				break;


			case 'PtgRef': /* [MS-XLS] 2.5.198.84 */
				/*::type = f[1][0]; */c = shift_cell_xls((f[1][1]/*:any*/), _range, opts);
				stack.push(encode_cell_xls(c, biff));
				break;
			case 'PtgRefN': /* [MS-XLS] 2.5.198.88 */
				/*::type = f[1][0]; */c = cell ? shift_cell_xls((f[1][1]/*:any*/), cell, opts) : (f[1][1]/*:any*/);
				stack.push(encode_cell_xls(c, biff));
				break;
			case 'PtgRef3d': /* [MS-XLS] 2.5.198.85 */
				/*::type = f[1][0]; */ixti = /*::Number(*/f[1][1]/*::)*/; c = shift_cell_xls((f[1][2]/*:any*/), _range, opts);
				sname = get_ixti(supbooks, ixti, opts);
				var w = sname; /* IE9 fails on defined names */ // eslint-disable-line no-unused-vars
				stack.push(sname + "!" + encode_cell_xls(c, biff));
				break;

			case 'PtgFunc': /* [MS-XLS] 2.5.198.62 */
			case 'PtgFuncVar': /* [MS-XLS] 2.5.198.63 */
				/* f[1] = [argc, func, type] */
				var argc/*:number*/ = (f[1][0]/*:any*/), func/*:string*/ = (f[1][1]/*:any*/);
				if(!argc) argc = 0;
				argc &= 0x7F;
				var args = argc == 0 ? [] : stack.slice(-argc);
				stack.length -= argc;
				if(func === 'User') func = args.shift();
				stack.push(func + "(" + args.join(",") + ")");
				break;

			case 'PtgBool': /* [MS-XLS] 2.5.198.42 */
				stack.push(f[1] ? "TRUE" : "FALSE"); break;
			case 'PtgInt': /* [MS-XLS] 2.5.198.66 */
				stack.push(/*::String(*/f[1]/*::)*/); break;
			case 'PtgNum': /* [MS-XLS] 2.5.198.79 TODO: precision? */
				stack.push(String(f[1])); break;
			case 'PtgStr': /* [MS-XLS] 2.5.198.89 */
				// $FlowIgnore
				stack.push('"' + f[1].replace(/"/g, '""') + '"'); break;
			case 'PtgErr': /* [MS-XLS] 2.5.198.57 */
				stack.push(/*::String(*/f[1]/*::)*/); break;
			case 'PtgAreaN': /* [MS-XLS] 2.5.198.31 TODO */
				/*::type = f[1][0]; */r = shift_range_xls(f[1][1], cell ? {s:cell} : _range, opts);
				stack.push(encode_range_xls((r/*:any*/), opts));
				break;
			case 'PtgArea': /* [MS-XLS] 2.5.198.27 TODO: fixed points */
				/*::type = f[1][0]; */r = shift_range_xls(f[1][1], _range, opts);
				stack.push(encode_range_xls((r/*:any*/), opts));
				break;
			case 'PtgArea3d': /* [MS-XLS] 2.5.198.28 TODO */
				/*::type = f[1][0]; */ixti = /*::Number(*/f[1][1]/*::)*/; r = f[1][2];
				sname = get_ixti(supbooks, ixti, opts);
				stack.push(sname + "!" + encode_range_xls((r/*:any*/), opts));
				break;
			case 'PtgAttrSum': /* [MS-XLS] 2.5.198.41 */
				stack.push("SUM(" + stack.pop() + ")");
				break;

			case 'PtgAttrBaxcel': /* [MS-XLS] 2.5.198.33 */
			case 'PtgAttrSemi': /* [MS-XLS] 2.5.198.37 */
				break;

			case 'PtgName': /* [MS-XLS] 2.5.198.76 ; [MS-XLSB] 2.5.97.60 TODO: revisions */
				/* f[1] = type, 0, nameindex */
				nameidx = (f[1][2]/*:any*/);
				var lbl = (supbooks.names||[])[nameidx-1] || (supbooks[0]||[])[nameidx];
				var name = lbl ? lbl.Name : "SH33TJSNAME" + String(nameidx);
				/* [MS-XLSB] 2.5.97.10 Ftab -- last verified 20220204 */
				if(name && name.slice(0,6) == "_xlfn." && !opts.xlfn) name = name.slice(6);
				stack.push(name);
				break;

			case 'PtgNameX': /* [MS-XLS] 2.5.198.77 ; [MS-XLSB] 2.5.97.61 TODO: revisions */
				/* f[1] = type, ixti, nameindex */
				var bookidx/*:number*/ = (f[1][1]/*:any*/); nameidx = (f[1][2]/*:any*/); var externbook;
				/* TODO: Properly handle missing values -- this should be using get_ixti_raw primarily */
				if(opts.biff <= 5) {
					if(bookidx < 0) bookidx = -bookidx;
					if(supbooks[bookidx]) externbook = supbooks[bookidx][nameidx];
				} else {
					var o = "";
					if(((supbooks[bookidx]||[])[0]||[])[0] == 0x3A01){/* empty */}
					else if(((supbooks[bookidx]||[])[0]||[])[0] == 0x0401){
						if(supbooks[bookidx][nameidx] && supbooks[bookidx][nameidx].itab > 0) {
							o = supbooks.SheetNames[supbooks[bookidx][nameidx].itab-1] + "!";
						}
					}
					else o = supbooks.SheetNames[nameidx-1]+ "!";
					if(supbooks[bookidx] && supbooks[bookidx][nameidx]) o += supbooks[bookidx][nameidx].Name;
					else if(supbooks[0] && supbooks[0][nameidx]) o += supbooks[0][nameidx].Name;
					else {
						var ixtidata = (get_ixti_raw(supbooks, bookidx, opts)||"").split(";;");
						if(ixtidata[nameidx - 1]) o = ixtidata[nameidx - 1]; // TODO: confirm this is correct
						else o += "SH33TJSERRX";
					}
					stack.push(o);
					break;
				}
				if(!externbook) externbook = {Name: "SH33TJSERRY"};
				stack.push(externbook.Name);
				break;

			case 'PtgParen': /* [MS-XLS] 2.5.198.80 */
				var lp = '(', rp = ')';
				if(last_sp >= 0) {
					sp = "";
					switch(formula[0][last_sp][1][0]) {
						// $FlowIgnore
						case 2: lp = fill$1(" ", formula[0][last_sp][1][1]) + lp; break;
						// $FlowIgnore
						case 3: lp = fill$1("\r", formula[0][last_sp][1][1]) + lp; break;
						// $FlowIgnore
						case 4: rp = fill$1(" ", formula[0][last_sp][1][1]) + rp; break;
						// $FlowIgnore
						case 5: rp = fill$1("\r", formula[0][last_sp][1][1]) + rp; break;
						default:
							// $FlowIgnore
							if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
					}
					last_sp = -1;
				}
				stack.push(lp + stack.pop() + rp); break;

			case 'PtgRefErr': /* [MS-XLS] 2.5.198.86 */
				stack.push('#REF!'); break;

			case 'PtgRefErr3d': /* [MS-XLS] 2.5.198.87 */
				stack.push('#REF!'); break;

			case 'PtgExp': /* [MS-XLS] 2.5.198.58 TODO */
				c = {c:(f[1][1]/*:any*/),r:(f[1][0]/*:any*/)};
				var q = ({c: cell.c, r:cell.r}/*:any*/);
				if(supbooks.sharedf[encode_cell(c)]) {
					var parsedf = (supbooks.sharedf[encode_cell(c)]);
					stack.push(stringify_formula(parsedf, _range, q, supbooks, opts));
				} else {
					var fnd = false;
					for(e1=0;e1!=supbooks.arrayf.length; ++e1) {
						/* TODO: should be something like range_has */
						e2 = supbooks.arrayf[e1];
						if(c.c < e2[0].s.c || c.c > e2[0].e.c) continue;
						if(c.r < e2[0].s.r || c.r > e2[0].e.r) continue;
						stack.push(stringify_formula(e2[1], _range, q, supbooks, opts));
						fnd = true;
						break;
					}
					if(!fnd) stack.push(/*::String(*/f[1]/*::)*/);
				}
				break;

			case 'PtgArray': /* [MS-XLS] 2.5.198.32 TODO */
				stack.push("{" + stringify_array(/*::(*/f[1]/*:: :any)*/) + "}");
				break;

			case 'PtgMemArea': /* [MS-XLS] 2.5.198.70 TODO: confirm this is a non-display */
				//stack.push("(" + f[2].map(encode_range).join(",") + ")");
				break;

			case 'PtgAttrSpace': /* [MS-XLS] 2.5.198.38 */
			case 'PtgAttrSpaceSemi': /* [MS-XLS] 2.5.198.39 */
				last_sp = ff;
				break;

			case 'PtgTbl': /* [MS-XLS] 2.5.198.92 TODO */
				break;

			case 'PtgMemErr': /* [MS-XLS] 2.5.198.71 */
				break;

			case 'PtgMissArg': /* [MS-XLS] 2.5.198.74 */
				stack.push("");
				break;

			case 'PtgAreaErr': /* [MS-XLS] 2.5.198.29 */
				stack.push("#REF!"); break;

			case 'PtgAreaErr3d': /* [MS-XLS] 2.5.198.30 */
				stack.push("#REF!"); break;

			case 'PtgList': /* [MS-XLSB] 2.5.97.52 */
				// $FlowIgnore
				stack.push("Table" + f[1].idx + "[#" + f[1].rt + "]");
				break;

			case 'PtgMemAreaN':
			case 'PtgMemNoMemN':
			case 'PtgAttrNoop':
			case 'PtgSheet':
			case 'PtgEndSheet':
				break;

			case 'PtgMemFunc': /* [MS-XLS] 2.5.198.72 TODO */
				break;
			case 'PtgMemNoMem': /* [MS-XLS] 2.5.198.73 TODO */
				break;

			case 'PtgElfCol': /* [MS-XLS] 2.5.198.46 */
			case 'PtgElfColS': /* [MS-XLS] 2.5.198.47 */
			case 'PtgElfColSV': /* [MS-XLS] 2.5.198.48 */
			case 'PtgElfColV': /* [MS-XLS] 2.5.198.49 */
			case 'PtgElfLel': /* [MS-XLS] 2.5.198.50 */
			case 'PtgElfRadical': /* [MS-XLS] 2.5.198.51 */
			case 'PtgElfRadicalLel': /* [MS-XLS] 2.5.198.52 */
			case 'PtgElfRadicalS': /* [MS-XLS] 2.5.198.53 */
			case 'PtgElfRw': /* [MS-XLS] 2.5.198.54 */
			case 'PtgElfRwV': /* [MS-XLS] 2.5.198.55 */
				throw new Error("Unsupported ELFs");

			case 'PtgSxName': /* [MS-XLS] 2.5.198.91 TODO -- find a test case */
				throw new Error('Unrecognized Formula Token: ' + String(f));
			default: throw new Error('Unrecognized Formula Token: ' + String(f));
		}
		var PtgNonDisp = ['PtgAttrSpace', 'PtgAttrSpaceSemi', 'PtgAttrGoto'];
		if(opts.biff != 3) if(last_sp >= 0 && PtgNonDisp.indexOf(formula[0][ff][0]) == -1) {
			f = formula[0][last_sp];
			var _left = true;
			switch(f[1][0]) {
				/* note: some bad XLSB files omit the PtgParen */
				case 4: _left = false;
				/* falls through */
				case 0:
					// $FlowIgnore
					sp = fill$1(" ", f[1][1]); break;
				case 5: _left = false;
				/* falls through */
				case 1:
					// $FlowIgnore
					sp = fill$1("\r", f[1][1]); break;
				default:
					sp = "";
					// $FlowIgnore
					if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + f[1][0]);
			}
			stack.push((_left ? sp : "") + stack.pop() + (_left ? "" : sp));
			last_sp = -1;
		}
	}
	if(stack.length > 1 && opts.WTF) throw new Error("bad formula stack");
	return stack[0];
}

/* [MS-XLS] 2.5.198.1 TODO */
function parse_ArrayParsedFormula(blob, length, opts/*::, ref*/) {
	var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
	var rgcb, cce = blob.read_shift(len); // length of rgce
	if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
	var rgce = parse_Rgce(blob, cce, opts);
	if(length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
	blob.l = target;
	return [rgce, rgcb];
}

/* [MS-XLS] 2.5.198.3 TODO */
function parse_XLSCellParsedFormula(blob, length, opts) {
	var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
	var rgcb, cce = blob.read_shift(len); // length of rgce
	if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
	var rgce = parse_Rgce(blob, cce, opts);
	if(length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
	blob.l = target;
	return [rgce, rgcb];
}

/* [MS-XLS] 2.5.198.21 */
function parse_NameParsedFormula(blob, length, opts, cce) {
	var target = blob.l + length;
	var rgce = parse_Rgce(blob, cce, opts);
	var rgcb;
	if(target !== blob.l) rgcb = parse_RgbExtra(blob, target - blob.l, rgce, opts);
	return [rgce, rgcb];
}

/* [MS-XLS] 2.5.198.118 TODO */
function parse_SharedParsedFormula(blob, length, opts) {
	var target = blob.l + length;
	var rgcb, cce = blob.read_shift(2); // length of rgce
	var rgce = parse_Rgce(blob, cce, opts);
	if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
	if(length !== cce + 2) rgcb = parse_RgbExtra(blob, target - cce - 2, rgce, opts);
	return [rgce, rgcb];
}

/* [MS-XLS] 2.5.133 TODO: how to emit empty strings? */
function parse_FormulaValue(blob/*::, length*/) {
	var b;
	if(__readUInt16LE(blob,blob.l + 6) !== 0xFFFF) return [parse_Xnum(blob),'n'];
	switch(blob[blob.l]) {
		case 0x00: blob.l += 8; return ["String", 's'];
		case 0x01: b = blob[blob.l+2] === 0x1; blob.l += 8; return [b,'b'];
		case 0x02: b = blob[blob.l+2]; blob.l += 8; return [b,'e'];
		case 0x03: blob.l += 8; return ["",'s'];
	}
	return [];
}
function write_FormulaValue(value) {
	if(value == null) {
		// Blank String Value
		var o = new_buf(8);
		o.write_shift(1, 0x03);
		o.write_shift(1, 0);
		o.write_shift(2, 0);
		o.write_shift(2, 0);
		o.write_shift(2, 0xFFFF);
		return o;
	} else if(typeof value == "number") return write_Xnum(value);
	return write_Xnum(0);
}

/* [MS-XLS] 2.4.127 TODO */
function parse_Formula(blob, length, opts) {
	var end = blob.l + length;
	var cell = parse_XLSCell(blob, 6);
	if(opts.biff == 2) ++blob.l;
	var val = parse_FormulaValue(blob,8);
	var flags = blob.read_shift(1);
	if(opts.biff != 2) {
		blob.read_shift(1);
		if(opts.biff >= 5) {
			/*var chn = */blob.read_shift(4);
		}
	}
	var cbf = parse_XLSCellParsedFormula(blob, end - blob.l, opts);
	return {cell:cell, val:val[0], formula:cbf, shared: (flags >> 3) & 1, tt:val[1]};
}
function write_Formula(cell/*:Cell*/, R/*:number*/, C/*:number*/, opts, os/*:number*/) {
	// Cell
	var o1 = write_XLSCell(R, C, os);

	// FormulaValue
	var o2 = write_FormulaValue(cell.v);

	// flags + cache
	var o3 = new_buf(6);
	var flags = 0x01 | 0x20;
	o3.write_shift(2, flags);
	o3.write_shift(4, 0);

	// CellParsedFormula
	var bf = new_buf(cell.bf.length);
	for(var i = 0; i < cell.bf.length; ++i) bf[i] = cell.bf[i];

	var out = bconcat([o1, o2, o3, bf]);
	return out;
}


/* XLSB Parsed Formula records have the same shape */
function parse_XLSBParsedFormula(data, length, opts) {
	var cce = data.read_shift(4);
	var rgce = parse_Rgce(data, cce, opts);
	var cb = data.read_shift(4);
	var rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;
	return [rgce, rgcb];
}

/* [MS-XLSB] 2.5.97.1 ArrayParsedFormula */
var parse_XLSBArrayParsedFormula = parse_XLSBParsedFormula;
/* [MS-XLSB] 2.5.97.4 CellParsedFormula */
var parse_XLSBCellParsedFormula = parse_XLSBParsedFormula;
/* [MS-XLSB] 2.5.97.8 DVParsedFormula */
//var parse_XLSBDVParsedFormula = parse_XLSBParsedFormula;
/* [MS-XLSB] 2.5.97.9 FRTParsedFormula */
//var parse_XLSBFRTParsedFormula = parse_XLSBParsedFormula2;
/* [MS-XLSB] 2.5.97.12 NameParsedFormula */
var parse_XLSBNameParsedFormula = parse_XLSBParsedFormula;
/* [MS-XLSB] 2.5.97.98 SharedParsedFormula */
var parse_XLSBSharedParsedFormula = parse_XLSBParsedFormula;
var Cetab = {
  0: "BEEP",
  1: "OPEN",
  2: "OPEN.LINKS",
  3: "CLOSE.ALL",
  4: "SAVE",
  5: "SAVE.AS",
  6: "FILE.DELETE",
  7: "PAGE.SETUP",
  8: "PRINT",
  9: "PRINTER.SETUP",
  10: "QUIT",
  11: "NEW.WINDOW",
  12: "ARRANGE.ALL",
  13: "WINDOW.SIZE",
  14: "WINDOW.MOVE",
  15: "FULL",
  16: "CLOSE",
  17: "RUN",
  22: "SET.PRINT.AREA",
  23: "SET.PRINT.TITLES",
  24: "SET.PAGE.BREAK",
  25: "REMOVE.PAGE.BREAK",
  26: "FONT",
  27: "DISPLAY",
  28: "PROTECT.DOCUMENT",
  29: "PRECISION",
  30: "A1.R1C1",
  31: "CALCULATE.NOW",
  32: "CALCULATION",
  34: "DATA.FIND",
  35: "EXTRACT",
  36: "DATA.DELETE",
  37: "SET.DATABASE",
  38: "SET.CRITERIA",
  39: "SORT",
  40: "DATA.SERIES",
  41: "TABLE",
  42: "FORMAT.NUMBER",
  43: "ALIGNMENT",
  44: "STYLE",
  45: "BORDER",
  46: "CELL.PROTECTION",
  47: "COLUMN.WIDTH",
  48: "UNDO",
  49: "CUT",
  50: "COPY",
  51: "PASTE",
  52: "CLEAR",
  53: "PASTE.SPECIAL",
  54: "EDIT.DELETE",
  55: "INSERT",
  56: "FILL.RIGHT",
  57: "FILL.DOWN",
  61: "DEFINE.NAME",
  62: "CREATE.NAMES",
  63: "FORMULA.GOTO",
  64: "FORMULA.FIND",
  65: "SELECT.LAST.CELL",
  66: "SHOW.ACTIVE.CELL",
  67: "GALLERY.AREA",
  68: "GALLERY.BAR",
  69: "GALLERY.COLUMN",
  70: "GALLERY.LINE",
  71: "GALLERY.PIE",
  72: "GALLERY.SCATTER",
  73: "COMBINATION",
  74: "PREFERRED",
  75: "ADD.OVERLAY",
  76: "GRIDLINES",
  77: "SET.PREFERRED",
  78: "AXES",
  79: "LEGEND",
  80: "ATTACH.TEXT",
  81: "ADD.ARROW",
  82: "SELECT.CHART",
  83: "SELECT.PLOT.AREA",
  84: "PATTERNS",
  85: "MAIN.CHART",
  86: "OVERLAY",
  87: "SCALE",
  88: "FORMAT.LEGEND",
  89: "FORMAT.TEXT",
  90: "EDIT.REPEAT",
  91: "PARSE",
  92: "JUSTIFY",
  93: "HIDE",
  94: "UNHIDE",
  95: "WORKSPACE",
  96: "FORMULA",
  97: "FORMULA.FILL",
  98: "FORMULA.ARRAY",
  99: "DATA.FIND.NEXT",
  100: "DATA.FIND.PREV",
  101: "FORMULA.FIND.NEXT",
  102: "FORMULA.FIND.PREV",
  103: "ACTIVATE",
  104: "ACTIVATE.NEXT",
  105: "ACTIVATE.PREV",
  106: "UNLOCKED.NEXT",
  107: "UNLOCKED.PREV",
  108: "COPY.PICTURE",
  109: "SELECT",
  110: "DELETE.NAME",
  111: "DELETE.FORMAT",
  112: "VLINE",
  113: "HLINE",
  114: "VPAGE",
  115: "HPAGE",
  116: "VSCROLL",
  117: "HSCROLL",
  118: "ALERT",
  119: "NEW",
  120: "CANCEL.COPY",
  121: "SHOW.CLIPBOARD",
  122: "MESSAGE",
  124: "PASTE.LINK",
  125: "APP.ACTIVATE",
  126: "DELETE.ARROW",
  127: "ROW.HEIGHT",
  128: "FORMAT.MOVE",
  129: "FORMAT.SIZE",
  130: "FORMULA.REPLACE",
  131: "SEND.KEYS",
  132: "SELECT.SPECIAL",
  133: "APPLY.NAMES",
  134: "REPLACE.FONT",
  135: "FREEZE.PANES",
  136: "SHOW.INFO",
  137: "SPLIT",
  138: "ON.WINDOW",
  139: "ON.DATA",
  140: "DISABLE.INPUT",
  142: "OUTLINE",
  143: "LIST.NAMES",
  144: "FILE.CLOSE",
  145: "SAVE.WORKBOOK",
  146: "DATA.FORM",
  147: "COPY.CHART",
  148: "ON.TIME",
  149: "WAIT",
  150: "FORMAT.FONT",
  151: "FILL.UP",
  152: "FILL.LEFT",
  153: "DELETE.OVERLAY",
  155: "SHORT.MENUS",
  159: "SET.UPDATE.STATUS",
  161: "COLOR.PALETTE",
  162: "DELETE.STYLE",
  163: "WINDOW.RESTORE",
  164: "WINDOW.MAXIMIZE",
  166: "CHANGE.LINK",
  167: "CALCULATE.DOCUMENT",
  168: "ON.KEY",
  169: "APP.RESTORE",
  170: "APP.MOVE",
  171: "APP.SIZE",
  172: "APP.MINIMIZE",
  173: "APP.MAXIMIZE",
  174: "BRING.TO.FRONT",
  175: "SEND.TO.BACK",
  185: "MAIN.CHART.TYPE",
  186: "OVERLAY.CHART.TYPE",
  187: "SELECT.END",
  188: "OPEN.MAIL",
  189: "SEND.MAIL",
  190: "STANDARD.FONT",
  191: "CONSOLIDATE",
  192: "SORT.SPECIAL",
  193: "GALLERY.3D.AREA",
  194: "GALLERY.3D.COLUMN",
  195: "GALLERY.3D.LINE",
  196: "GALLERY.3D.PIE",
  197: "VIEW.3D",
  198: "GOAL.SEEK",
  199: "WORKGROUP",
  200: "FILL.GROUP",
  201: "UPDATE.LINK",
  202: "PROMOTE",
  203: "DEMOTE",
  204: "SHOW.DETAIL",
  206: "UNGROUP",
  207: "OBJECT.PROPERTIES",
  208: "SAVE.NEW.OBJECT",
  209: "SHARE",
  210: "SHARE.NAME",
  211: "DUPLICATE",
  212: "APPLY.STYLE",
  213: "ASSIGN.TO.OBJECT",
  214: "OBJECT.PROTECTION",
  215: "HIDE.OBJECT",
  216: "SET.EXTRACT",
  217: "CREATE.PUBLISHER",
  218: "SUBSCRIBE.TO",
  219: "ATTRIBUTES",
  220: "SHOW.TOOLBAR",
  222: "PRINT.PREVIEW",
  223: "EDIT.COLOR",
  224: "SHOW.LEVELS",
  225: "FORMAT.MAIN",
  226: "FORMAT.OVERLAY",
  227: "ON.RECALC",
  228: "EDIT.SERIES",
  229: "DEFINE.STYLE",
  240: "LINE.PRINT",
  243: "ENTER.DATA",
  249: "GALLERY.RADAR",
  250: "MERGE.STYLES",
  251: "EDITION.OPTIONS",
  252: "PASTE.PICTURE",
  253: "PASTE.PICTURE.LINK",
  254: "SPELLING",
  256: "ZOOM",
  259: "INSERT.OBJECT",
  260: "WINDOW.MINIMIZE",
  265: "SOUND.NOTE",
  266: "SOUND.PLAY",
  267: "FORMAT.SHAPE",
  268: "EXTEND.POLYGON",
  269: "FORMAT.AUTO",
  272: "GALLERY.3D.BAR",
  273: "GALLERY.3D.SURFACE",
  274: "FILL.AUTO",
  276: "CUSTOMIZE.TOOLBAR",
  277: "ADD.TOOL",
  278: "EDIT.OBJECT",
  279: "ON.DOUBLECLICK",
  280: "ON.ENTRY",
  281: "WORKBOOK.ADD",
  282: "WORKBOOK.MOVE",
  283: "WORKBOOK.COPY",
  284: "WORKBOOK.OPTIONS",
  285: "SAVE.WORKSPACE",
  288: "CHART.WIZARD",
  289: "DELETE.TOOL",
  290: "MOVE.TOOL",
  291: "WORKBOOK.SELECT",
  292: "WORKBOOK.ACTIVATE",
  293: "ASSIGN.TO.TOOL",
  295: "COPY.TOOL",
  296: "RESET.TOOL",
  297: "CONSTRAIN.NUMERIC",
  298: "PASTE.TOOL",
  302: "WORKBOOK.NEW",
  305: "SCENARIO.CELLS",
  306: "SCENARIO.DELETE",
  307: "SCENARIO.ADD",
  308: "SCENARIO.EDIT",
  309: "SCENARIO.SHOW",
  310: "SCENARIO.SHOW.NEXT",
  311: "SCENARIO.SUMMARY",
  312: "PIVOT.TABLE.WIZARD",
  313: "PIVOT.FIELD.PROPERTIES",
  314: "PIVOT.FIELD",
  315: "PIVOT.ITEM",
  316: "PIVOT.ADD.FIELDS",
  318: "OPTIONS.CALCULATION",
  319: "OPTIONS.EDIT",
  320: "OPTIONS.VIEW",
  321: "ADDIN.MANAGER",
  322: "MENU.EDITOR",
  323: "ATTACH.TOOLBARS",
  324: "VBAActivate",
  325: "OPTIONS.CHART",
  328: "VBA.INSERT.FILE",
  330: "VBA.PROCEDURE.DEFINITION",
  336: "ROUTING.SLIP",
  338: "ROUTE.DOCUMENT",
  339: "MAIL.LOGON",
  342: "INSERT.PICTURE",
  343: "EDIT.TOOL",
  344: "GALLERY.DOUGHNUT",
  350: "CHART.TREND",
  352: "PIVOT.ITEM.PROPERTIES",
  354: "WORKBOOK.INSERT",
  355: "OPTIONS.TRANSITION",
  356: "OPTIONS.GENERAL",
  370: "FILTER.ADVANCED",
  373: "MAIL.ADD.MAILER",
  374: "MAIL.DELETE.MAILER",
  375: "MAIL.REPLY",
  376: "MAIL.REPLY.ALL",
  377: "MAIL.FORWARD",
  378: "MAIL.NEXT.LETTER",
  379: "DATA.LABEL",
  380: "INSERT.TITLE",
  381: "FONT.PROPERTIES",
  382: "MACRO.OPTIONS",
  383: "WORKBOOK.HIDE",
  384: "WORKBOOK.UNHIDE",
  385: "WORKBOOK.DELETE",
  386: "WORKBOOK.NAME",
  388: "GALLERY.CUSTOM",
  390: "ADD.CHART.AUTOFORMAT",
  391: "DELETE.CHART.AUTOFORMAT",
  392: "CHART.ADD.DATA",
  393: "AUTO.OUTLINE",
  394: "TAB.ORDER",
  395: "SHOW.DIALOG",
  396: "SELECT.ALL",
  397: "UNGROUP.SHEETS",
  398: "SUBTOTAL.CREATE",
  399: "SUBTOTAL.REMOVE",
  400: "RENAME.OBJECT",
  412: "WORKBOOK.SCROLL",
  413: "WORKBOOK.NEXT",
  414: "WORKBOOK.PREV",
  415: "WORKBOOK.TAB.SPLIT",
  416: "FULL.SCREEN",
  417: "WORKBOOK.PROTECT",
  420: "SCROLLBAR.PROPERTIES",
  421: "PIVOT.SHOW.PAGES",
  422: "TEXT.TO.COLUMNS",
  423: "FORMAT.CHARTTYPE",
  424: "LINK.FORMAT",
  425: "TRACER.DISPLAY",
  430: "TRACER.NAVIGATE",
  431: "TRACER.CLEAR",
  432: "TRACER.ERROR",
  433: "PIVOT.FIELD.GROUP",
  434: "PIVOT.FIELD.UNGROUP",
  435: "CHECKBOX.PROPERTIES",
  436: "LABEL.PROPERTIES",
  437: "LISTBOX.PROPERTIES",
  438: "EDITBOX.PROPERTIES",
  439: "PIVOT.REFRESH",
  440: "LINK.COMBO",
  441: "OPEN.TEXT",
  442: "HIDE.DIALOG",
  443: "SET.DIALOG.FOCUS",
  444: "ENABLE.OBJECT",
  445: "PUSHBUTTON.PROPERTIES",
  446: "SET.DIALOG.DEFAULT",
  447: "FILTER",
  448: "FILTER.SHOW.ALL",
  449: "CLEAR.OUTLINE",
  450: "FUNCTION.WIZARD",
  451: "ADD.LIST.ITEM",
  452: "SET.LIST.ITEM",
  453: "REMOVE.LIST.ITEM",
  454: "SELECT.LIST.ITEM",
  455: "SET.CONTROL.VALUE",
  456: "SAVE.COPY.AS",
  458: "OPTIONS.LISTS.ADD",
  459: "OPTIONS.LISTS.DELETE",
  460: "SERIES.AXES",
  461: "SERIES.X",
  462: "SERIES.Y",
  463: "ERRORBAR.X",
  464: "ERRORBAR.Y",
  465: "FORMAT.CHART",
  466: "SERIES.ORDER",
  467: "MAIL.LOGOFF",
  468: "CLEAR.ROUTING.SLIP",
  469: "APP.ACTIVATE.MICROSOFT",
  470: "MAIL.EDIT.MAILER",
  471: "ON.SHEET",
  472: "STANDARD.WIDTH",
  473: "SCENARIO.MERGE",
  474: "SUMMARY.INFO",
  475: "FIND.FILE",
  476: "ACTIVE.CELL.FONT",
  477: "ENABLE.TIPWIZARD",
  478: "VBA.MAKE.ADDIN",
  480: "INSERTDATATABLE",
  481: "WORKGROUP.OPTIONS",
  482: "MAIL.SEND.MAILER",
  485: "AUTOCORRECT",
  489: "POST.DOCUMENT",
  491: "PICKLIST",
  493: "VIEW.SHOW",
  494: "VIEW.DEFINE",
  495: "VIEW.DELETE",
  509: "SHEET.BACKGROUND",
  510: "INSERT.MAP.OBJECT",
  511: "OPTIONS.MENONO",
  517: "MSOCHECKS",
  518: "NORMAL",
  519: "LAYOUT",
  520: "RM.PRINT.AREA",
  521: "CLEAR.PRINT.AREA",
  522: "ADD.PRINT.AREA",
  523: "MOVE.BRK",
  545: "HIDECURR.NOTE",
  546: "HIDEALL.NOTES",
  547: "DELETE.NOTE",
  548: "TRAVERSE.NOTES",
  549: "ACTIVATE.NOTES",
  620: "PROTECT.REVISIONS",
  621: "UNPROTECT.REVISIONS",
  647: "OPTIONS.ME",
  653: "WEB.PUBLISH",
  667: "NEWWEBQUERY",
  673: "PIVOT.TABLE.CHART",
  753: "OPTIONS.SAVE",
  755: "OPTIONS.SPELL",
  808: "HIDEALL.INKANNOTS"
};
var Ftab = {
  0: "COUNT",
  1: "IF",
  2: "ISNA",
  3: "ISERROR",
  4: "SUM",
  5: "AVERAGE",
  6: "MIN",
  7: "MAX",
  8: "ROW",
  9: "COLUMN",
  10: "NA",
  11: "NPV",
  12: "STDEV",
  13: "DOLLAR",
  14: "FIXED",
  15: "SIN",
  16: "COS",
  17: "TAN",
  18: "ATAN",
  19: "PI",
  20: "SQRT",
  21: "EXP",
  22: "LN",
  23: "LOG10",
  24: "ABS",
  25: "INT",
  26: "SIGN",
  27: "ROUND",
  28: "LOOKUP",
  29: "INDEX",
  30: "REPT",
  31: "MID",
  32: "LEN",
  33: "VALUE",
  34: "TRUE",
  35: "FALSE",
  36: "AND",
  37: "OR",
  38: "NOT",
  39: "MOD",
  40: "DCOUNT",
  41: "DSUM",
  42: "DAVERAGE",
  43: "DMIN",
  44: "DMAX",
  45: "DSTDEV",
  46: "VAR",
  47: "DVAR",
  48: "TEXT",
  49: "LINEST",
  50: "TREND",
  51: "LOGEST",
  52: "GROWTH",
  53: "GOTO",
  54: "HALT",
  55: "RETURN",
  56: "PV",
  57: "FV",
  58: "NPER",
  59: "PMT",
  60: "RATE",
  61: "MIRR",
  62: "IRR",
  63: "RAND",
  64: "MATCH",
  65: "DATE",
  66: "TIME",
  67: "DAY",
  68: "MONTH",
  69: "YEAR",
  70: "WEEKDAY",
  71: "HOUR",
  72: "MINUTE",
  73: "SECOND",
  74: "NOW",
  75: "AREAS",
  76: "ROWS",
  77: "COLUMNS",
  78: "OFFSET",
  79: "ABSREF",
  80: "RELREF",
  81: "ARGUMENT",
  82: "SEARCH",
  83: "TRANSPOSE",
  84: "ERROR",
  85: "STEP",
  86: "TYPE",
  87: "ECHO",
  88: "SET.NAME",
  89: "CALLER",
  90: "DEREF",
  91: "WINDOWS",
  92: "SERIES",
  93: "DOCUMENTS",
  94: "ACTIVE.CELL",
  95: "SELECTION",
  96: "RESULT",
  97: "ATAN2",
  98: "ASIN",
  99: "ACOS",
  100: "CHOOSE",
  101: "HLOOKUP",
  102: "VLOOKUP",
  103: "LINKS",
  104: "INPUT",
  105: "ISREF",
  106: "GET.FORMULA",
  107: "GET.NAME",
  108: "SET.VALUE",
  109: "LOG",
  110: "EXEC",
  111: "CHAR",
  112: "LOWER",
  113: "UPPER",
  114: "PROPER",
  115: "LEFT",
  116: "RIGHT",
  117: "EXACT",
  118: "TRIM",
  119: "REPLACE",
  120: "SUBSTITUTE",
  121: "CODE",
  122: "NAMES",
  123: "DIRECTORY",
  124: "FIND",
  125: "CELL",
  126: "ISERR",
  127: "ISTEXT",
  128: "ISNUMBER",
  129: "ISBLANK",
  130: "T",
  131: "N",
  132: "FOPEN",
  133: "FCLOSE",
  134: "FSIZE",
  135: "FREADLN",
  136: "FREAD",
  137: "FWRITELN",
  138: "FWRITE",
  139: "FPOS",
  140: "DATEVALUE",
  141: "TIMEVALUE",
  142: "SLN",
  143: "SYD",
  144: "DDB",
  145: "GET.DEF",
  146: "REFTEXT",
  147: "TEXTREF",
  148: "INDIRECT",
  149: "REGISTER",
  150: "CALL",
  151: "ADD.BAR",
  152: "ADD.MENU",
  153: "ADD.COMMAND",
  154: "ENABLE.COMMAND",
  155: "CHECK.COMMAND",
  156: "RENAME.COMMAND",
  157: "SHOW.BAR",
  158: "DELETE.MENU",
  159: "DELETE.COMMAND",
  160: "GET.CHART.ITEM",
  161: "DIALOG.BOX",
  162: "CLEAN",
  163: "MDETERM",
  164: "MINVERSE",
  165: "MMULT",
  166: "FILES",
  167: "IPMT",
  168: "PPMT",
  169: "COUNTA",
  170: "CANCEL.KEY",
  171: "FOR",
  172: "WHILE",
  173: "BREAK",
  174: "NEXT",
  175: "INITIATE",
  176: "REQUEST",
  177: "POKE",
  178: "EXECUTE",
  179: "TERMINATE",
  180: "RESTART",
  181: "HELP",
  182: "GET.BAR",
  183: "PRODUCT",
  184: "FACT",
  185: "GET.CELL",
  186: "GET.WORKSPACE",
  187: "GET.WINDOW",
  188: "GET.DOCUMENT",
  189: "DPRODUCT",
  190: "ISNONTEXT",
  191: "GET.NOTE",
  192: "NOTE",
  193: "STDEVP",
  194: "VARP",
  195: "DSTDEVP",
  196: "DVARP",
  197: "TRUNC",
  198: "ISLOGICAL",
  199: "DCOUNTA",
  200: "DELETE.BAR",
  201: "UNREGISTER",
  204: "USDOLLAR",
  205: "FINDB",
  206: "SEARCHB",
  207: "REPLACEB",
  208: "LEFTB",
  209: "RIGHTB",
  210: "MIDB",
  211: "LENB",
  212: "ROUNDUP",
  213: "ROUNDDOWN",
  214: "ASC",
  215: "DBCS",
  216: "RANK",
  219: "ADDRESS",
  220: "DAYS360",
  221: "TODAY",
  222: "VDB",
  223: "ELSE",
  224: "ELSE.IF",
  225: "END.IF",
  226: "FOR.CELL",
  227: "MEDIAN",
  228: "SUMPRODUCT",
  229: "SINH",
  230: "COSH",
  231: "TANH",
  232: "ASINH",
  233: "ACOSH",
  234: "ATANH",
  235: "DGET",
  236: "CREATE.OBJECT",
  237: "VOLATILE",
  238: "LAST.ERROR",
  239: "CUSTOM.UNDO",
  240: "CUSTOM.REPEAT",
  241: "FORMULA.CONVERT",
  242: "GET.LINK.INFO",
  243: "TEXT.BOX",
  244: "INFO",
  245: "GROUP",
  246: "GET.OBJECT",
  247: "DB",
  248: "PAUSE",
  251: "RESUME",
  252: "FREQUENCY",
  253: "ADD.TOOLBAR",
  254: "DELETE.TOOLBAR",
  255: "User",
  256: "RESET.TOOLBAR",
  257: "EVALUATE",
  258: "GET.TOOLBAR",
  259: "GET.TOOL",
  260: "SPELLING.CHECK",
  261: "ERROR.TYPE",
  262: "APP.TITLE",
  263: "WINDOW.TITLE",
  264: "SAVE.TOOLBAR",
  265: "ENABLE.TOOL",
  266: "PRESS.TOOL",
  267: "REGISTER.ID",
  268: "GET.WORKBOOK",
  269: "AVEDEV",
  270: "BETADIST",
  271: "GAMMALN",
  272: "BETAINV",
  273: "BINOMDIST",
  274: "CHIDIST",
  275: "CHIINV",
  276: "COMBIN",
  277: "CONFIDENCE",
  278: "CRITBINOM",
  279: "EVEN",
  280: "EXPONDIST",
  281: "FDIST",
  282: "FINV",
  283: "FISHER",
  284: "FISHERINV",
  285: "FLOOR",
  286: "GAMMADIST",
  287: "GAMMAINV",
  288: "CEILING",
  289: "HYPGEOMDIST",
  290: "LOGNORMDIST",
  291: "LOGINV",
  292: "NEGBINOMDIST",
  293: "NORMDIST",
  294: "NORMSDIST",
  295: "NORMINV",
  296: "NORMSINV",
  297: "STANDARDIZE",
  298: "ODD",
  299: "PERMUT",
  300: "POISSON",
  301: "TDIST",
  302: "WEIBULL",
  303: "SUMXMY2",
  304: "SUMX2MY2",
  305: "SUMX2PY2",
  306: "CHITEST",
  307: "CORREL",
  308: "COVAR",
  309: "FORECAST",
  310: "FTEST",
  311: "INTERCEPT",
  312: "PEARSON",
  313: "RSQ",
  314: "STEYX",
  315: "SLOPE",
  316: "TTEST",
  317: "PROB",
  318: "DEVSQ",
  319: "GEOMEAN",
  320: "HARMEAN",
  321: "SUMSQ",
  322: "KURT",
  323: "SKEW",
  324: "ZTEST",
  325: "LARGE",
  326: "SMALL",
  327: "QUARTILE",
  328: "PERCENTILE",
  329: "PERCENTRANK",
  330: "MODE",
  331: "TRIMMEAN",
  332: "TINV",
  334: "MOVIE.COMMAND",
  335: "GET.MOVIE",
  336: "CONCATENATE",
  337: "POWER",
  338: "PIVOT.ADD.DATA",
  339: "GET.PIVOT.TABLE",
  340: "GET.PIVOT.FIELD",
  341: "GET.PIVOT.ITEM",
  342: "RADIANS",
  343: "DEGREES",
  344: "SUBTOTAL",
  345: "SUMIF",
  346: "COUNTIF",
  347: "COUNTBLANK",
  348: "SCENARIO.GET",
  349: "OPTIONS.LISTS.GET",
  350: "ISPMT",
  351: "DATEDIF",
  352: "DATESTRING",
  353: "NUMBERSTRING",
  354: "ROMAN",
  355: "OPEN.DIALOG",
  356: "SAVE.DIALOG",
  357: "VIEW.GET",
  358: "GETPIVOTDATA",
  359: "HYPERLINK",
  360: "PHONETIC",
  361: "AVERAGEA",
  362: "MAXA",
  363: "MINA",
  364: "STDEVPA",
  365: "VARPA",
  366: "STDEVA",
  367: "VARA",
  368: "BAHTTEXT",
  369: "THAIDAYOFWEEK",
  370: "THAIDIGIT",
  371: "THAIMONTHOFYEAR",
  372: "THAINUMSOUND",
  373: "THAINUMSTRING",
  374: "THAISTRINGLENGTH",
  375: "ISTHAIDIGIT",
  376: "ROUNDBAHTDOWN",
  377: "ROUNDBAHTUP",
  378: "THAIYEAR",
  379: "RTD",
  380: "CUBEVALUE",
  381: "CUBEMEMBER",
  382: "CUBEMEMBERPROPERTY",
  383: "CUBERANKEDMEMBER",
  384: "HEX2BIN",
  385: "HEX2DEC",
  386: "HEX2OCT",
  387: "DEC2BIN",
  388: "DEC2HEX",
  389: "DEC2OCT",
  390: "OCT2BIN",
  391: "OCT2HEX",
  392: "OCT2DEC",
  393: "BIN2DEC",
  394: "BIN2OCT",
  395: "BIN2HEX",
  396: "IMSUB",
  397: "IMDIV",
  398: "IMPOWER",
  399: "IMABS",
  400: "IMSQRT",
  401: "IMLN",
  402: "IMLOG2",
  403: "IMLOG10",
  404: "IMSIN",
  405: "IMCOS",
  406: "IMEXP",
  407: "IMARGUMENT",
  408: "IMCONJUGATE",
  409: "IMAGINARY",
  410: "IMREAL",
  411: "COMPLEX",
  412: "IMSUM",
  413: "IMPRODUCT",
  414: "SERIESSUM",
  415: "FACTDOUBLE",
  416: "SQRTPI",
  417: "QUOTIENT",
  418: "DELTA",
  419: "GESTEP",
  420: "ISEVEN",
  421: "ISODD",
  422: "MROUND",
  423: "ERF",
  424: "ERFC",
  425: "BESSELJ",
  426: "BESSELK",
  427: "BESSELY",
  428: "BESSELI",
  429: "XIRR",
  430: "XNPV",
  431: "PRICEMAT",
  432: "YIELDMAT",
  433: "INTRATE",
  434: "RECEIVED",
  435: "DISC",
  436: "PRICEDISC",
  437: "YIELDDISC",
  438: "TBILLEQ",
  439: "TBILLPRICE",
  440: "TBILLYIELD",
  441: "PRICE",
  442: "YIELD",
  443: "DOLLARDE",
  444: "DOLLARFR",
  445: "NOMINAL",
  446: "EFFECT",
  447: "CUMPRINC",
  448: "CUMIPMT",
  449: "EDATE",
  450: "EOMONTH",
  451: "YEARFRAC",
  452: "COUPDAYBS",
  453: "COUPDAYS",
  454: "COUPDAYSNC",
  455: "COUPNCD",
  456: "COUPNUM",
  457: "COUPPCD",
  458: "DURATION",
  459: "MDURATION",
  460: "ODDLPRICE",
  461: "ODDLYIELD",
  462: "ODDFPRICE",
  463: "ODDFYIELD",
  464: "RANDBETWEEN",
  465: "WEEKNUM",
  466: "AMORDEGRC",
  467: "AMORLINC",
  468: "CONVERT",
  724: "SHEETJS",
  469: "ACCRINT",
  470: "ACCRINTM",
  471: "WORKDAY",
  472: "NETWORKDAYS",
  473: "GCD",
  474: "MULTINOMIAL",
  475: "LCM",
  476: "FVSCHEDULE",
  477: "CUBEKPIMEMBER",
  478: "CUBESET",
  479: "CUBESETCOUNT",
  480: "IFERROR",
  481: "COUNTIFS",
  482: "SUMIFS",
  483: "AVERAGEIF",
  484: "AVERAGEIFS"
};
var FtabArgc = {
  2: 1,
  3: 1,
  10: 0,
  15: 1,
  16: 1,
  17: 1,
  18: 1,
  19: 0,
  20: 1,
  21: 1,
  22: 1,
  23: 1,
  24: 1,
  25: 1,
  26: 1,
  27: 2,
  30: 2,
  31: 3,
  32: 1,
  33: 1,
  34: 0,
  35: 0,
  38: 1,
  39: 2,
  40: 3,
  41: 3,
  42: 3,
  43: 3,
  44: 3,
  45: 3,
  47: 3,
  48: 2,
  53: 1,
  61: 3,
  63: 0,
  65: 3,
  66: 3,
  67: 1,
  68: 1,
  69: 1,
  70: 1,
  71: 1,
  72: 1,
  73: 1,
  74: 0,
  75: 1,
  76: 1,
  77: 1,
  79: 2,
  80: 2,
  83: 1,
  85: 0,
  86: 1,
  89: 0,
  90: 1,
  94: 0,
  95: 0,
  97: 2,
  98: 1,
  99: 1,
  101: 3,
  102: 3,
  105: 1,
  106: 1,
  108: 2,
  111: 1,
  112: 1,
  113: 1,
  114: 1,
  117: 2,
  118: 1,
  119: 4,
  121: 1,
  126: 1,
  127: 1,
  128: 1,
  129: 1,
  130: 1,
  131: 1,
  133: 1,
  134: 1,
  135: 1,
  136: 2,
  137: 2,
  138: 2,
  140: 1,
  141: 1,
  142: 3,
  143: 4,
  144: 4,
  161: 1,
  162: 1,
  163: 1,
  164: 1,
  165: 2,
  172: 1,
  175: 2,
  176: 2,
  177: 3,
  178: 2,
  179: 1,
  184: 1,
  186: 1,
  189: 3,
  190: 1,
  195: 3,
  196: 3,
  197: 1,
  198: 1,
  199: 3,
  201: 1,
  207: 4,
  210: 3,
  211: 1,
  212: 2,
  213: 2,
  214: 1,
  215: 1,
  225: 0,
  229: 1,
  230: 1,
  231: 1,
  232: 1,
  233: 1,
  234: 1,
  235: 3,
  244: 1,
  247: 4,
  252: 2,
  257: 1,
  261: 1,
  271: 1,
  273: 4,
  274: 2,
  275: 2,
  276: 2,
  277: 3,
  278: 3,
  279: 1,
  280: 3,
  281: 3,
  282: 3,
  283: 1,
  284: 1,
  285: 2,
  286: 4,
  287: 3,
  288: 2,
  289: 4,
  290: 3,
  291: 3,
  292: 3,
  293: 4,
  294: 1,
  295: 3,
  296: 1,
  297: 3,
  298: 1,
  299: 2,
  300: 3,
  301: 3,
  302: 4,
  303: 2,
  304: 2,
  305: 2,
  306: 2,
  307: 2,
  308: 2,
  309: 3,
  310: 2,
  311: 2,
  312: 2,
  313: 2,
  314: 2,
  315: 2,
  316: 4,
  325: 2,
  326: 2,
  327: 2,
  328: 2,
  331: 2,
  332: 2,
  337: 2,
  342: 1,
  343: 1,
  346: 2,
  347: 1,
  350: 4,
  351: 3,
  352: 1,
  353: 2,
  360: 1,
  368: 1,
  369: 1,
  370: 1,
  371: 1,
  372: 1,
  373: 1,
  374: 1,
  375: 1,
  376: 1,
  377: 1,
  378: 1,
  382: 3,
  385: 1,
  392: 1,
  393: 1,
  396: 2,
  397: 2,
  398: 2,
  399: 1,
  400: 1,
  401: 1,
  402: 1,
  403: 1,
  404: 1,
  405: 1,
  406: 1,
  407: 1,
  408: 1,
  409: 1,
  410: 1,
  414: 4,
  415: 1,
  416: 1,
  417: 2,
  420: 1,
  421: 1,
  422: 2,
  424: 1,
  425: 2,
  426: 2,
  427: 2,
  428: 2,
  430: 3,
  438: 3,
  439: 3,
  440: 3,
  443: 2,
  444: 2,
  445: 2,
  446: 2,
  447: 6,
  448: 6,
  449: 2,
  450: 2,
  464: 2,
  468: 3,
  476: 2,
  479: 1,
  480: 2,
  65535: 0
};
/* Part 3 TODO: actually parse formulae */
function ods_to_csf_formula(f/*:string*/)/*:string*/ {
	if(f.slice(0,3) == "of:") f = f.slice(3);
	/* 5.2 Basic Expressions */
	if(f.charCodeAt(0) == 61) {
		f = f.slice(1);
		if(f.charCodeAt(0) == 61) f = f.slice(1);
	}
	f = f.replace(/COM\.MICROSOFT\./g, "");
	/* Part 3 Section 5.8 References */
	f = f.replace(/\[((?:\.[A-Z]+[0-9]+)(?::\.[A-Z]+[0-9]+)?)\]/g, function($$, $1) { return $1.replace(/\./g,""); });
	/* TODO: something other than this */
	f = f.replace(/\[.(#[A-Z]*[?!])\]/g, "$1");
	return f.replace(/[;~]/g,",").replace(/\|/g,";");
}

function csf_to_ods_formula(f/*:string*/)/*:string*/ {
	var o = "of:=" + f.replace(crefregex, "$1[.$2$3$4$5]").replace(/\]:\[/g,":");
	/* TODO: something other than this */
	return o.replace(/;/g, "|").replace(/,/g,";");
}

function ods_to_csf_3D(r/*:string*/)/*:[string, string]*/ {
	var a = r.split(":");
	var s = a[0].split(".")[0];
	return [s, a[0].split(".")[1] + (a.length > 1 ? (":" + (a[1].split(".")[1] || a[1].split(".")[0])) : "")];
}

function csf_to_ods_3D(r/*:string*/)/*:string*/ {
	return r.replace(/\./,"!");
}

var strs = {}; // shared strings
var _ssfopts = {}; // spreadsheet formatting options


/*global Map */
var browser_has_Map = typeof Map !== 'undefined';

function get_sst_id(sst/*:SST*/, str/*:string*/, rev)/*:number*/ {
	var i = 0, len = sst.length;
	if(rev) {
		if(browser_has_Map ? rev.has(str) : Object.prototype.hasOwnProperty.call(rev, str)) {
			var revarr = browser_has_Map ? rev.get(str) : rev[str];
			for(; i < revarr.length; ++i) {
				if(sst[revarr[i]].t === str) { sst.Count ++; return revarr[i]; }
			}
		}
	} else for(; i < len; ++i) {
		if(sst[i].t === str) { sst.Count ++; return i; }
	}
	sst[len] = ({t:str}/*:any*/); sst.Count ++; sst.Unique ++;
	if(rev) {
		if(browser_has_Map) {
			if(!rev.has(str)) rev.set(str, []);
			rev.get(str).push(len);
		} else {
			if(!Object.prototype.hasOwnProperty.call(rev, str)) rev[str] = [];
			rev[str].push(len);
		}
	}
	return len;
}

function col_obj_w(C/*:number*/, col) {
	var p = ({min:C+1,max:C+1}/*:any*/);
	/* wch (chars), wpx (pixels) */
	var wch = -1;
	if(col.MDW) MDW = col.MDW;
	if(col.width != null) p.customWidth = 1;
	else if(col.wpx != null) wch = px2char(col.wpx);
	else if(col.wch != null) wch = col.wch;
	if(wch > -1) { p.width = char2width(wch); p.customWidth = 1; }
	else if(col.width != null) p.width = col.width;
	if(col.hidden) p.hidden = true;
	if(col.level != null) { p.outlineLevel = p.level = col.level; }
	return p;
}

function default_margins(margins/*:Margins*/, mode/*:?string*/) {
	if(!margins) return;
	var defs = [0.7, 0.7, 0.75, 0.75, 0.3, 0.3];
	if(mode == 'xlml') defs = [1, 1, 1, 1, 0.5, 0.5];
	if(margins.left   == null) margins.left   = defs[0];
	if(margins.right  == null) margins.right  = defs[1];
	if(margins.top    == null) margins.top    = defs[2];
	if(margins.bottom == null) margins.bottom = defs[3];
	if(margins.header == null) margins.header = defs[4];
	if(margins.footer == null) margins.footer = defs[5];
}

function get_cell_style(styles/*:Array<any>*/, cell/*:Cell*/, opts) {
	var z = opts.revssf[cell.z != null ? cell.z : "General"];
	var i = 0x3c, len = styles.length;
	if(z == null && opts.ssf) {
		for(; i < 0x188; ++i) if(opts.ssf[i] == null) {
			SSF_load(cell.z, i);
			// $FlowIgnore
			opts.ssf[i] = cell.z;
			opts.revssf[cell.z] = z = i;
			break;
		}
	}
	for(i = 0; i != len; ++i) if(styles[i].numFmtId === z) return i;
	styles[len] = {
		numFmtId:z,
		fontId:0,
		fillId:0,
		borderId:0,
		xfId:0,
		applyNumberFormat:1
	};
	return len;
}

function safe_format(p/*:Cell*/, fmtid/*:number*/, fillid/*:?number*/, opts, themes, styles) {
	try {
		if(opts.cellNF) p.z = table_fmt[fmtid];
	} catch(e) { if(opts.WTF) throw e; }
	if(p.t === 'z' && !opts.cellStyles) return;
	if(p.t === 'd' && typeof p.v === 'string') p.v = parseDate(p.v);
	if((!opts || opts.cellText !== false) && p.t !== 'z') try {
		if(table_fmt[fmtid] == null) SSF_load(SSFImplicit[fmtid] || "General", fmtid);
		if(p.t === 'e') p.w = p.w || BErr[p.v];
		else if(fmtid === 0) {
			if(p.t === 'n') {
				if((p.v|0) === p.v) p.w = p.v.toString(10);
				else p.w = SSF_general_num(p.v);
			}
			else if(p.t === 'd') {
				var dd = datenum(p.v);
				if((dd|0) === dd) p.w = dd.toString(10);
				else p.w = SSF_general_num(dd);
			}
			else if(p.v === undefined) return "";
			else p.w = SSF_general(p.v,_ssfopts);
		}
		else if(p.t === 'd') p.w = SSF_format(fmtid,datenum(p.v),_ssfopts);
		else p.w = SSF_format(fmtid,p.v,_ssfopts);
	} catch(e) { if(opts.WTF) throw e; }
	if(!opts.cellStyles) return;
	if(fillid != null) try {
		p.s = styles.Fills[fillid];
		if (p.s.fgColor && p.s.fgColor.theme && !p.s.fgColor.rgb) {
			p.s.fgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.fgColor.theme].rgb, p.s.fgColor.tint || 0);
			if(opts.WTF) p.s.fgColor.raw_rgb = themes.themeElements.clrScheme[p.s.fgColor.theme].rgb;
		}
		if (p.s.bgColor && p.s.bgColor.theme) {
			p.s.bgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.bgColor.theme].rgb, p.s.bgColor.tint || 0);
			if(opts.WTF) p.s.bgColor.raw_rgb = themes.themeElements.clrScheme[p.s.bgColor.theme].rgb;
		}
	} catch(e) { if(opts.WTF && styles.Fills) throw e; }
}

function check_ws(ws/*:Worksheet*/, sname/*:string*/, i/*:number*/) {
	if(ws && ws['!ref']) {
		var range = safe_decode_range(ws['!ref']);
		if(range.e.c < range.s.c || range.e.r < range.s.r) throw new Error("Bad range (" + i + "): " + ws['!ref']);
	}
}
function parse_ws_xml_dim(ws/*:Worksheet*/, s/*:string*/) {
	var d = safe_decode_range(s);
	if(d.s.r<=d.e.r && d.s.c<=d.e.c && d.s.r>=0 && d.s.c>=0) ws["!ref"] = encode_range(d);
}
var mergecregex = /<(?:\w:)?mergeCell ref="[A-Z0-9:]+"\s*[\/]?>/g;
var sheetdataregex = /<(?:\w+:)?sheetData[^>]*>([\s\S]*)<\/(?:\w+:)?sheetData>/;
var hlinkregex = /<(?:\w:)?hyperlink [^>]*>/mg;
var dimregex = /"(\w*:\w*)"/;
var colregex = /<(?:\w:)?col\b[^>]*[\/]?>/g;
var afregex = /<(?:\w:)?autoFilter[^>]*([\/]|>([\s\S]*)<\/(?:\w:)?autoFilter)>/g;
var marginregex= /<(?:\w:)?pageMargins[^>]*\/>/g;
var sheetprregex = /<(?:\w:)?sheetPr\b(?:[^>a-z][^>]*)?\/>/;
var sheetprregex2= /<(?:\w:)?sheetPr[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetPr)>/;
var svsregex = /<(?:\w:)?sheetViews[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetViews)>/;

/* 18.3 Worksheets */
function parse_ws_xml(data/*:?string*/, opts, idx/*:number*/, rels, wb/*:WBWBProps*/, themes, styles)/*:Worksheet*/ {
	if(!data) return data;
	if(!rels) rels = {'!id':{}};
	if(DENSE != null && opts.dense == null) opts.dense = DENSE;

	/* 18.3.1.99 worksheet CT_Worksheet */
	var s = opts.dense ? ([]/*:any*/) : ({}/*:any*/);
	var refguess/*:Range*/ = ({s: {r:2000000, c:2000000}, e: {r:0, c:0} }/*:any*/);

	var data1 = "", data2 = "";
	var mtch/*:?any*/ = data.match(sheetdataregex);
	if(mtch) {
		data1 = data.slice(0, mtch.index);
		data2 = data.slice(mtch.index + mtch[0].length);
	} else data1 = data2 = data;

	/* 18.3.1.82 sheetPr CT_SheetPr */
	var sheetPr = data1.match(sheetprregex);
	if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
	else if((sheetPr = data1.match(sheetprregex2))) parse_ws_xml_sheetpr2(sheetPr[0], sheetPr[1]||"", s, wb, idx, styles, themes);

	/* 18.3.1.35 dimension CT_SheetDimension */
	var ridx = (data1.match(/<(?:\w*:)?dimension/)||{index:-1}).index;
	if(ridx > 0) {
		var ref = data1.slice(ridx,ridx+50).match(dimregex);
		if(ref) parse_ws_xml_dim(s, ref[1]);
	}

	/* 18.3.1.88 sheetViews CT_SheetViews */
	var svs = data1.match(svsregex);
	if(svs && svs[1]) parse_ws_xml_sheetviews(svs[1], wb);

	/* 18.3.1.17 cols CT_Cols */
	var columns/*:Array<ColInfo>*/ = [];
	if(opts.cellStyles) {
		/* 18.3.1.13 col CT_Col */
		var cols = data1.match(colregex);
		if(cols) parse_ws_xml_cols(columns, cols);
	}

	/* 18.3.1.80 sheetData CT_SheetData ? */
	if(mtch) parse_ws_xml_data(mtch[1], s, opts, refguess, themes, styles);

	/* 18.3.1.2  autoFilter CT_AutoFilter */
	var afilter = data2.match(afregex);
	if(afilter) s['!autofilter'] = parse_ws_xml_autofilter(afilter[0]);

	/* 18.3.1.55 mergeCells CT_MergeCells */
	var merges/*:Array<Range>*/ = [];
	var _merge = data2.match(mergecregex);
	if(_merge) for(ridx = 0; ridx != _merge.length; ++ridx)
		merges[ridx] = safe_decode_range(_merge[ridx].slice(_merge[ridx].indexOf("\"")+1));

	/* 18.3.1.48 hyperlinks CT_Hyperlinks */
	var hlink = data2.match(hlinkregex);
	if(hlink) parse_ws_xml_hlinks(s, hlink, rels);

	/* 18.3.1.62 pageMargins CT_PageMargins */
	var margins = data2.match(marginregex);
	if(margins) s['!margins'] = parse_ws_xml_margins(parsexmltag(margins[0]));

	if(!s["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s["!ref"] = encode_range(refguess);
	if(opts.sheetRows > 0 && s["!ref"]) {
		var tmpref = safe_decode_range(s["!ref"]);
		if(opts.sheetRows <= +tmpref.e.r) {
			tmpref.e.r = opts.sheetRows - 1;
			if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
			if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
			if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
			if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
			s["!fullref"] = s["!ref"];
			s["!ref"] = encode_range(tmpref);
		}
	}
	if(columns.length > 0) s["!cols"] = columns;
	if(merges.length > 0) s["!merges"] = merges;
	return s;
}

function write_ws_xml_merges(merges/*:Array<Range>*/)/*:string*/ {
	if(merges.length === 0) return "";
	var o = '<mergeCells count="' + merges.length + '">';
	for(var i = 0; i != merges.length; ++i) o += '<mergeCell ref="' + encode_range(merges[i]) + '"/>';
	return o + '</mergeCells>';
}

/* 18.3.1.82-3 sheetPr CT_ChartsheetPr / CT_SheetPr */
function parse_ws_xml_sheetpr(sheetPr/*:string*/, s, wb/*:WBWBProps*/, idx/*:number*/) {
	var data = parsexmltag(sheetPr);
	if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
	if(data.codeName) wb.Sheets[idx].CodeName = unescapexml(utf8read(data.codeName));
}
function parse_ws_xml_sheetpr2(sheetPr/*:string*/, body/*:string*/, s, wb/*:WBWBProps*/, idx/*:number*/) {
	parse_ws_xml_sheetpr(sheetPr.slice(0, sheetPr.indexOf(">")), s, wb, idx);
}
function write_ws_xml_sheetpr(ws, wb, idx, opts, o) {
	var needed = false;
	var props = {}, payload = null;
	if(opts.bookType !== 'xlsx' && wb.vbaraw) {
		var cname = wb.SheetNames[idx];
		try { if(wb.Workbook) cname = wb.Workbook.Sheets[idx].CodeName || cname; } catch(e) {}
		needed = true;
		props.codeName = utf8write(escapexml(cname));
	}

	if(ws && ws["!outline"]) {
		var outlineprops = {summaryBelow:1, summaryRight:1};
		if(ws["!outline"].above) outlineprops.summaryBelow = 0;
		if(ws["!outline"].left) outlineprops.summaryRight = 0;
		payload = (payload||"") + writextag('outlinePr', null, outlineprops);
	}

	if(!needed && !payload) return;
	o[o.length] = (writextag('sheetPr', payload, props));
}

/* 18.3.1.85 sheetProtection CT_SheetProtection */
var sheetprot_deffalse = ["objects", "scenarios", "selectLockedCells", "selectUnlockedCells"];
var sheetprot_deftrue = [
	"formatColumns", "formatRows", "formatCells",
	"insertColumns", "insertRows", "insertHyperlinks",
	"deleteColumns", "deleteRows",
	"sort", "autoFilter", "pivotTables"
];
function write_ws_xml_protection(sp)/*:string*/ {
	// algorithmName, hashValue, saltValue, spinCount
	var o = ({sheet:1}/*:any*/);
	sheetprot_deffalse.forEach(function(n) { if(sp[n] != null && sp[n]) o[n] = "1"; });
	sheetprot_deftrue.forEach(function(n) { if(sp[n] != null && !sp[n]) o[n] = "0"; });
	/* TODO: algorithm */
	if(sp.password) o.password = crypto_CreatePasswordVerifier_Method1(sp.password).toString(16).toUpperCase();
	return writextag('sheetProtection', null, o);
}

function parse_ws_xml_hlinks(s, data/*:Array<string>*/, rels) {
	var dense = Array.isArray(s);
	for(var i = 0; i != data.length; ++i) {
		var val = parsexmltag(utf8read(data[i]), true);
		if(!val.ref) return;
		var rel = ((rels || {})['!id']||[])[val.id];
		if(rel) {
			val.Target = rel.Target;
			if(val.location) val.Target += "#"+unescapexml(val.location);
		} else {
			val.Target = "#" + unescapexml(val.location);
			rel = {Target: val.Target, TargetMode: 'Internal'};
		}
		val.Rel = rel;
		if(val.tooltip) { val.Tooltip = val.tooltip; delete val.tooltip; }
		var rng = safe_decode_range(val.ref);
		for(var R=rng.s.r;R<=rng.e.r;++R) for(var C=rng.s.c;C<=rng.e.c;++C) {
			var addr = encode_cell({c:C,r:R});
			if(dense) {
				if(!s[R]) s[R] = [];
				if(!s[R][C]) s[R][C] = {t:"z",v:undefined};
				s[R][C].l = val;
			} else {
				if(!s[addr]) s[addr] = {t:"z",v:undefined};
				s[addr].l = val;
			}
		}
	}
}

function parse_ws_xml_margins(margin) {
	var o = {};
	["left", "right", "top", "bottom", "header", "footer"].forEach(function(k) {
		if(margin[k]) o[k] = parseFloat(margin[k]);
	});
	return o;
}
function write_ws_xml_margins(margin)/*:string*/ {
	default_margins(margin);
	return writextag('pageMargins', null, margin);
}

function parse_ws_xml_cols(columns, cols) {
	var seencol = false;
	for(var coli = 0; coli != cols.length; ++coli) {
		var coll = parsexmltag(cols[coli], true);
		if(coll.hidden) coll.hidden = parsexmlbool(coll.hidden);
		var colm=parseInt(coll.min, 10)-1, colM=parseInt(coll.max,10)-1;
		if(coll.outlineLevel) coll.level = (+coll.outlineLevel || 0);
		delete coll.min; delete coll.max; coll.width = +coll.width;
		if(!seencol && coll.width) { seencol = true; find_mdw_colw(coll.width); }
		process_col(coll);
		while(colm <= colM) columns[colm++] = dup(coll);
	}
}
function write_ws_xml_cols(ws, cols)/*:string*/ {
	var o = ["<cols>"], col;
	for(var i = 0; i != cols.length; ++i) {
		if(!(col = cols[i])) continue;
		o[o.length] = (writextag('col', null, col_obj_w(i, col)));
	}
	o[o.length] = "</cols>";
	return o.join("");
}

function parse_ws_xml_autofilter(data/*:string*/) {
	var o = { ref: (data.match(/ref="([^"]*)"/)||[])[1]};
	return o;
}
function write_ws_xml_autofilter(data, ws, wb, idx)/*:string*/ {
	var ref = typeof data.ref == "string" ? data.ref : encode_range(data.ref);
	if(!wb.Workbook) wb.Workbook = ({Sheets:[]}/*:any*/);
	if(!wb.Workbook.Names) wb.Workbook.Names = [];
	var names/*: Array<any> */ = wb.Workbook.Names;
	var range = decode_range(ref);
	if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
	for(var i = 0; i < names.length; ++i) {
		var name = names[i];
		if(name.Name != '_xlnm._FilterDatabase') continue;
		if(name.Sheet != idx) continue;
		name.Ref = "'" + wb.SheetNames[idx] + "'!" + ref; break;
	}
	if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref  });
	return writextag("autoFilter", null, {ref:ref});
}

/* 18.3.1.88 sheetViews CT_SheetViews */
/* 18.3.1.87 sheetView CT_SheetView */
var sviewregex = /<(?:\w:)?sheetView(?:[^>a-z][^>]*)?\/?>/;
function parse_ws_xml_sheetviews(data, wb/*:WBWBProps*/) {
	if(!wb.Views) wb.Views = [{}];
	(data.match(sviewregex)||[]).forEach(function(r/*:string*/, i/*:number*/) {
		var tag = parsexmltag(r);
		// $FlowIgnore
		if(!wb.Views[i]) wb.Views[i] = {};
		// $FlowIgnore
		if(+tag.zoomScale) wb.Views[i].zoom = +tag.zoomScale;
		// $FlowIgnore
		if(parsexmlbool(tag.rightToLeft)) wb.Views[i].RTL = true;
	});
}
function write_ws_xml_sheetviews(ws, opts, idx, wb)/*:string*/ {
	var sview = ({workbookViewId:"0"}/*:any*/);
	// $FlowIgnore
	if((((wb||{}).Workbook||{}).Views||[])[0]) sview.rightToLeft = wb.Workbook.Views[0].RTL ? "1" : "0";
	return writextag("sheetViews", writextag("sheetView", null, sview), {});
}

function write_ws_xml_cell(cell/*:Cell*/, ref, ws, opts/*::, idx, wb*/)/*:string*/ {
	if(cell.c) ws['!comments'].push([ref, cell.c]);
	if(cell.v === undefined && typeof cell.f !== "string" || cell.t === 'z' && !cell.f) return "";
	var vv = "";
	var oldt = cell.t, oldv = cell.v;
	if(cell.t !== "z") switch(cell.t) {
		case 'b': vv = cell.v ? "1" : "0"; break;
		case 'n': vv = ''+cell.v; break;
		case 'e': vv = BErr[cell.v]; break;
		case 'd':
			if(opts && opts.cellDates) vv = parseDate(cell.v, -1).toISOString();
			else {
				cell = dup(cell);
				cell.t = 'n';
				vv = ''+(cell.v = datenum(parseDate(cell.v)));
			}
			if(typeof cell.z === 'undefined') cell.z = table_fmt[14];
			break;
		default: vv = cell.v; break;
	}
	var v = writetag('v', escapexml(vv)), o = ({r:ref}/*:any*/);
	/* TODO: cell style */
	var os = get_cell_style(opts.cellXfs, cell, opts);
	if(os !== 0) o.s = os;
	switch(cell.t) {
		case 'n': break;
		case 'd': o.t = "d"; break;
		case 'b': o.t = "b"; break;
		case 'e': o.t = "e"; break;
		case 'z': break;
		default: if(cell.v == null) { delete cell.t; break; }
			if(cell.v.length > 32767) throw new Error("Text length must not exceed 32767 characters");
			if(opts && opts.bookSST) {
				v = writetag('v', ''+get_sst_id(opts.Strings, cell.v, opts.revStrings));
				o.t = "s"; break;
			}
			o.t = "str"; break;
	}
	if(cell.t != oldt) { cell.t = oldt; cell.v = oldv; }
	if(typeof cell.f == "string" && cell.f) {
		var ff = cell.F && cell.F.slice(0, ref.length) == ref ? {t:"array", ref:cell.F} : null;
		v = writextag('f', escapexml(cell.f), ff) + (cell.v != null ? v : "");
	}
	if(cell.l) ws['!links'].push([ref, cell.l]);
	if(cell.D) o.cm = 1;
	return writextag('c', v, o);
}

var parse_ws_xml_data = /*#__PURE__*/(function() {
	var cellregex = /<(?:\w+:)?c[ \/>]/, rowregex = /<\/(?:\w+:)?row>/;
	var rregex = /r=["']([^"']*)["']/, isregex = /<(?:\w+:)?is>([\S\s]*?)<\/(?:\w+:)?is>/;
	var refregex = /ref=["']([^"']*)["']/;
	var match_v = matchtag("v"), match_f = matchtag("f");

return function parse_ws_xml_data(sdata/*:string*/, s, opts, guess/*:Range*/, themes, styles) {
	var ri = 0, x = "", cells/*:Array<string>*/ = [], cref/*:?Array<string>*/ = [], idx=0, i=0, cc=0, d="", p/*:any*/;
	var tag, tagr = 0, tagc = 0;
	var sstr, ftag;
	var fmtid = 0, fillid = 0;
	var do_format = Array.isArray(styles.CellXf), cf;
	var arrayf/*:Array<[Range, string]>*/ = [];
	var sharedf = [];
	var dense = Array.isArray(s);
	var rows/*:Array<RowInfo>*/ = [], rowobj = {}, rowrite = false;
	var sheetStubs = !!opts.sheetStubs;
	for(var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) {
		x = marr[mt].trim();
		var xlen = x.length;
		if(xlen === 0) continue;

		/* 18.3.1.73 row CT_Row */
		var rstarti = 0;
		outa: for(ri = 0; ri < xlen; ++ri) switch(/*x.charCodeAt(ri)*/x[ri]) {
			case ">" /*62*/:
				if(/*x.charCodeAt(ri-1) != 47*/x[ri-1] != "/") { ++ri; break outa; }
				if(opts && opts.cellStyles) {
					// TODO: avoid duplication
					tag = parsexmltag(x.slice(rstarti,ri), true);
					tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
					if(opts.sheetRows && opts.sheetRows < tagr) continue;
					rowobj = {}; rowrite = false;
					if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
					if(tag.hidden == "1") { rowrite = true; rowobj.hidden = true; }
					if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
					if(rowrite) rows[tagr-1] = rowobj;
				}
				break;
			case "<" /*60*/: rstarti = ri; break;
		}
		if(rstarti >= ri) break;
		tag = parsexmltag(x.slice(rstarti,ri), true);
		tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
		if(opts.sheetRows && opts.sheetRows < tagr) continue;
		if(guess.s.r > tagr - 1) guess.s.r = tagr - 1;
		if(guess.e.r < tagr - 1) guess.e.r = tagr - 1;

		if(opts && opts.cellStyles) {
			rowobj = {}; rowrite = false;
			if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
			if(tag.hidden == "1") { rowrite = true; rowobj.hidden = true; }
			if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
			if(rowrite) rows[tagr-1] = rowobj;
		}

		/* 18.3.1.4 c CT_Cell */
		cells = x.slice(ri).split(cellregex);
		for(var rslice = 0; rslice != cells.length; ++rslice) if(cells[rslice].trim().charAt(0) != "<") break;
		cells = cells.slice(rslice);
		for(ri = 0; ri != cells.length; ++ri) {
			x = cells[ri].trim();
			if(x.length === 0) continue;
			cref = x.match(rregex); idx = ri; i=0; cc=0;
			x = "<c " + (x.slice(0,1)=="<"?">":"") + x;
			if(cref != null && cref.length === 2) {
				idx = 0; d=cref[1];
				for(i=0; i != d.length; ++i) {
					if((cc=d.charCodeAt(i)-64) < 1 || cc > 26) break;
					idx = 26*idx + cc;
				}
				--idx;
				tagc = idx;
			} else ++tagc;
			for(i = 0; i != x.length; ++i) if(x.charCodeAt(i) === 62) break; ++i;
			tag = parsexmltag(x.slice(0,i), true);
			if(!tag.r) tag.r = encode_cell({r:tagr-1, c:tagc});
			d = x.slice(i);
			p = ({t:""}/*:any*/);

			if((cref=d.match(match_v))!= null && /*::cref != null && */cref[1] !== '') p.v=unescapexml(cref[1]);
			if(opts.cellFormula) {
				if((cref=d.match(match_f))!= null && /*::cref != null && */cref[1] !== '') {
					/* TODO: match against XLSXFutureFunctions */
					p.f=unescapexml(utf8read(cref[1])).replace(/\r\n/g, "\n");
					if(!opts.xlfn) p.f = _xlfn(p.f);
					if(/*::cref != null && cref[0] != null && */cref[0].indexOf('t="array"') > -1) {
						p.F = (d.match(refregex)||[])[1];
						if(p.F.indexOf(":") > -1) arrayf.push([safe_decode_range(p.F), p.F]);
					} else if(/*::cref != null && cref[0] != null && */cref[0].indexOf('t="shared"') > -1) {
						// TODO: parse formula
						ftag = parsexmltag(cref[0]);
						var ___f = unescapexml(utf8read(cref[1]));
						if(!opts.xlfn) ___f = _xlfn(___f);
						sharedf[parseInt(ftag.si, 10)] = [ftag, ___f, tag.r];
					}
				} else if((cref=d.match(/<f[^>]*\/>/))) {
					ftag = parsexmltag(cref[0]);
					if(sharedf[ftag.si]) p.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2]/*[0].ref*/, tag.r);
				}
				/* TODO: factor out contains logic */
				var _tag = decode_cell(tag.r);
				for(i = 0; i < arrayf.length; ++i)
					if(_tag.r >= arrayf[i][0].s.r && _tag.r <= arrayf[i][0].e.r)
						if(_tag.c >= arrayf[i][0].s.c && _tag.c <= arrayf[i][0].e.c)
							p.F = arrayf[i][1];
			}

			if(tag.t == null && p.v === undefined) {
				if(p.f || p.F) {
					p.v = 0; p.t = "n";
				} else if(!sheetStubs) continue;
				else p.t = "z";
			}
			else p.t = tag.t || "n";
			if(guess.s.c > tagc) guess.s.c = tagc;
			if(guess.e.c < tagc) guess.e.c = tagc;
			/* 18.18.11 t ST_CellType */
			switch(p.t) {
				case 'n':
					if(p.v == "" || p.v == null) {
						if(!sheetStubs) continue;
						p.t = 'z';
					} else p.v = parseFloat(p.v);
					break;
				case 's':
					if(typeof p.v == 'undefined') {
						if(!sheetStubs) continue;
						p.t = 'z';
					} else {
						sstr = strs[parseInt(p.v, 10)];
						p.v = sstr.t;
						p.r = sstr.r;
						if(opts.cellHTML) p.h = sstr.h;
					}
					break;
				case 'str':
					p.t = "s";
					p.v = (p.v!=null) ? utf8read(p.v) : '';
					if(opts.cellHTML) p.h = escapehtml(p.v);
					break;
				case 'inlineStr':
					cref = d.match(isregex);
					p.t = 's';
					if(cref != null && (sstr = parse_si(cref[1]))) {
						p.v = sstr.t;
						if(opts.cellHTML) p.h = sstr.h;
					} else p.v = "";
					break;
				case 'b': p.v = parsexmlbool(p.v); break;
				case 'd':
					if(opts.cellDates) p.v = parseDate(p.v, 1);
					else { p.v = datenum(parseDate(p.v, 1)); p.t = 'n'; }
					break;
				/* error string in .w, number in .v */
				case 'e':
					if(!opts || opts.cellText !== false) p.w = p.v;
					p.v = RBErr[p.v]; break;
			}
			/* formatting */
			fmtid = fillid = 0;
			cf = null;
			if(do_format && tag.s !== undefined) {
				cf = styles.CellXf[tag.s];
				if(cf != null) {
					if(cf.numFmtId != null) fmtid = cf.numFmtId;
					if(opts.cellStyles) {
						if(cf.fillId != null) fillid = cf.fillId;
					}
				}
			}
			safe_format(p, fmtid, fillid, opts, themes, styles);
			if(opts.cellDates && do_format && p.t == 'n' && fmt_is_date(table_fmt[fmtid])) { p.t = 'd'; p.v = numdate(p.v); }
			if(tag.cm && opts.xlmeta) {
				var cm = (opts.xlmeta.Cell||[])[+tag.cm-1];
				if(cm && cm.type == 'XLDAPR') p.D = true;
			}
			if(dense) {
				var _r = decode_cell(tag.r);
				if(!s[_r.r]) s[_r.r] = [];
				s[_r.r][_r.c] = p;
			} else s[tag.r] = p;
		}
	}
	if(rows.length > 0) s['!rows'] = rows;
}; })();

function write_ws_xml_data(ws/*:Worksheet*/, opts, idx/*:number*/, wb/*:Workbook*//*::, rels*/)/*:string*/ {
	var o/*:Array<string>*/ = [], r/*:Array<string>*/ = [], range = safe_decode_range(ws['!ref']), cell="", ref, rr = "", cols/*:Array<string>*/ = [], R=0, C=0, rows = ws['!rows'];
	var dense = Array.isArray(ws);
	var params = ({r:rr}/*:any*/), row/*:RowInfo*/, height = -1;
	for(C = range.s.c; C <= range.e.c; ++C) cols[C] = encode_col(C);
	for(R = range.s.r; R <= range.e.r; ++R) {
		r = [];
		rr = encode_row(R);
		for(C = range.s.c; C <= range.e.c; ++C) {
			ref = cols[C] + rr;
			var _cell = dense ? (ws[R]||[])[C]: ws[ref];
			if(_cell === undefined) continue;
			if((cell = write_ws_xml_cell(_cell, ref, ws, opts, idx, wb)) != null) r.push(cell);
		}
		if(r.length > 0 || (rows && rows[R])) {
			params = ({r:rr}/*:any*/);
			if(rows && rows[R]) {
				row = rows[R];
				if(row.hidden) params.hidden = 1;
				height = -1;
				if(row.hpx) height = px2pt(row.hpx);
				else if(row.hpt) height = row.hpt;
				if(height > -1) { params.ht = height; params.customHeight = 1; }
				if(row.level) { params.outlineLevel = row.level; }
			}
			o[o.length] = (writextag('row', r.join(""), params));
		}
	}
	if(rows) for(; R < rows.length; ++R) {
		if(rows && rows[R]) {
			params = ({r:R+1}/*:any*/);
			row = rows[R];
			if(row.hidden) params.hidden = 1;
			height = -1;
			if (row.hpx) height = px2pt(row.hpx);
			else if (row.hpt) height = row.hpt;
			if (height > -1) { params.ht = height; params.customHeight = 1; }
			if (row.level) { params.outlineLevel = row.level; }
			o[o.length] = (writextag('row', "", params));
		}
	}
	return o.join("");
}

function write_ws_xml(idx/*:number*/, opts, wb/*:Workbook*/, rels)/*:string*/ {
	var o = [XML_HEADER, writextag('worksheet', null, {
		'xmlns': XMLNS_main[0],
		'xmlns:r': XMLNS.r
	})];
	var s = wb.SheetNames[idx], sidx = 0, rdata = "";
	var ws = wb.Sheets[s];
	if(ws == null) ws = {};
	var ref = ws['!ref'] || 'A1';
	var range = safe_decode_range(ref);
	if(range.e.c > 0x3FFF || range.e.r > 0xFFFFF) {
		if(opts.WTF) throw new Error("Range " + ref + " exceeds format limit A1:XFD1048576");
		range.e.c = Math.min(range.e.c, 0x3FFF);
		range.e.r = Math.min(range.e.c, 0xFFFFF);
		ref = encode_range(range);
	}
	if(!rels) rels = {};
	ws['!comments'] = [];
	var _drawing = [];

	write_ws_xml_sheetpr(ws, wb, idx, opts, o);

	o[o.length] = (writextag('dimension', null, {'ref': ref}));

	o[o.length] = write_ws_xml_sheetviews(ws, opts, idx, wb);

	/* TODO: store in WB, process styles */
	if(opts.sheetFormat) o[o.length] = (writextag('sheetFormatPr', null, {
		defaultRowHeight:opts.sheetFormat.defaultRowHeight||'16',
		baseColWidth:opts.sheetFormat.baseColWidth||'10',
		outlineLevelRow:opts.sheetFormat.outlineLevelRow||'7'
	}));

	if(ws['!cols'] != null && ws['!cols'].length > 0) o[o.length] = (write_ws_xml_cols(ws, ws['!cols']));

	o[sidx = o.length] = '<sheetData/>';
	ws['!links'] = [];
	if(ws['!ref'] != null) {
		rdata = write_ws_xml_data(ws, opts, idx, wb, rels);
		if(rdata.length > 0) o[o.length] = (rdata);
	}
	if(o.length>sidx+1) { o[o.length] = ('</sheetData>'); o[sidx]=o[sidx].replace("/>",">"); }

	/* sheetCalcPr */

	if(ws['!protect']) o[o.length] = write_ws_xml_protection(ws['!protect']);

	/* protectedRanges */
	/* scenarios */

	if(ws['!autofilter'] != null) o[o.length] = write_ws_xml_autofilter(ws['!autofilter'], ws, wb, idx);

	/* sortState */
	/* dataConsolidate */
	/* customSheetViews */

	if(ws['!merges'] != null && ws['!merges'].length > 0) o[o.length] = (write_ws_xml_merges(ws['!merges']));

	/* phoneticPr */
	/* conditionalFormatting */
	/* dataValidations */

	var relc = -1, rel, rId = -1;
	if(/*::(*/ws['!links']/*::||[])*/.length > 0) {
		o[o.length] = "<hyperlinks>";
		/*::(*/ws['!links']/*::||[])*/.forEach(function(l) {
			if(!l[1].Target) return;
			rel = ({"ref":l[0]}/*:any*/);
			if(l[1].Target.charAt(0) != "#") {
				rId = add_rels(rels, -1, escapexml(l[1].Target).replace(/#.*$/, ""), RELS.HLINK);
				rel["r:id"] = "rId"+rId;
			}
			if((relc = l[1].Target.indexOf("#")) > -1) rel.location = escapexml(l[1].Target.slice(relc+1));
			if(l[1].Tooltip) rel.tooltip = escapexml(l[1].Tooltip);
			o[o.length] = writextag("hyperlink",null,rel);
		});
		o[o.length] = "</hyperlinks>";
	}
	delete ws['!links'];

	/* printOptions */

	if(ws['!margins'] != null) o[o.length] =  write_ws_xml_margins(ws['!margins']);

	/* pageSetup */
	/* headerFooter */
	/* rowBreaks */
	/* colBreaks */
	/* customProperties */
	/* cellWatches */

	if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) o[o.length] = writetag("ignoredErrors", writextag("ignoredError", null, {numberStoredAsText:1, sqref:ref}));

	/* smartTags */

	if(_drawing.length > 0) {
		rId = add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
		o[o.length] = writextag("drawing", null, {"r:id":"rId" + rId});
		ws['!drawing'] = _drawing;
	}

	if(ws['!comments'].length > 0) {
		rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
		o[o.length] = writextag("legacyDrawing", null, {"r:id":"rId" + rId});
		ws['!legacy'] = rId;
	}

	/* legacyDrawingHF */
	/* picture */
	/* oleObjects */
	/* controls */
	/* webPublishItems */
	/* tableParts */
	/* extLst */

	if(o.length>1) { o[o.length] = ('</worksheet>'); o[1]=o[1].replace("/>",">"); }
	return o.join("");
}

/* [MS-XLSB] 2.4.726 BrtRowHdr */
function parse_BrtRowHdr(data, length) {
	var z = ({}/*:any*/);
	var tgt = data.l + length;
	z.r = data.read_shift(4);
	data.l += 4; // TODO: ixfe
	var miyRw = data.read_shift(2);
	data.l += 1; // TODO: top/bot padding
	var flags = data.read_shift(1);
	data.l = tgt;
	if(flags & 0x07) z.level = flags & 0x07;
	if(flags & 0x10) z.hidden = true;
	if(flags & 0x20) z.hpt = miyRw / 20;
	return z;
}
function write_BrtRowHdr(R/*:number*/, range, ws) {
	var o = new_buf(17+8*16);
	var row = (ws['!rows']||[])[R]||{};
	o.write_shift(4, R);

	o.write_shift(4, 0); /* TODO: ixfe */

	var miyRw = 0x0140;
	if(row.hpx) miyRw = px2pt(row.hpx) * 20;
	else if(row.hpt) miyRw = row.hpt * 20;
	o.write_shift(2, miyRw);

	o.write_shift(1, 0); /* top/bot padding */

	var flags = 0x0;
	if(row.level) flags |= row.level;
	if(row.hidden) flags |= 0x10;
	if(row.hpx || row.hpt) flags |= 0x20;
	o.write_shift(1, flags);

	o.write_shift(1, 0); /* phonetic guide */

	/* [MS-XLSB] 2.5.8 BrtColSpan explains the mechanism */
	var ncolspan = 0, lcs = o.l;
	o.l += 4;

	var caddr = {r:R, c:0};
	for(var i = 0; i < 16; ++i) {
		if((range.s.c > ((i+1) << 10)) || (range.e.c < (i << 10))) continue;
		var first = -1, last = -1;
		for(var j = (i<<10); j < ((i+1)<<10); ++j) {
			caddr.c = j;
			var cell = Array.isArray(ws) ? (ws[caddr.r]||[])[caddr.c] : ws[encode_cell(caddr)];
			if(cell) { if(first < 0) first = j; last = j; }
		}
		if(first < 0) continue;
		++ncolspan;
		o.write_shift(4, first);
		o.write_shift(4, last);
	}

	var l = o.l;
	o.l = lcs;
	o.write_shift(4, ncolspan);
	o.l = l;

	return o.length > o.l ? o.slice(0, o.l) : o;
}
function write_row_header(ba, ws, range, R) {
	var o = write_BrtRowHdr(R, range, ws);
	if((o.length > 17) || (ws['!rows']||[])[R]) write_record(ba, 0x0000 /* BrtRowHdr */, o);
}

/* [MS-XLSB] 2.4.820 BrtWsDim */
var parse_BrtWsDim = parse_UncheckedRfX;
var write_BrtWsDim = write_UncheckedRfX;

/* [MS-XLSB] 2.4.821 BrtWsFmtInfo */
function parse_BrtWsFmtInfo(/*::data, length*/) {
}
//function write_BrtWsFmtInfo(ws, o) { }

/* [MS-XLSB] 2.4.823 BrtWsProp */
function parse_BrtWsProp(data, length) {
	var z = {};
	var f = data[data.l]; ++data.l;
	z.above = !(f & 0x40);
	z.left  = !(f & 0x80);
	/* TODO: pull flags */
	data.l += 18;
	z.name = parse_XLSBCodeName(data, length - 19);
	return z;
}
function write_BrtWsProp(str, outl, o) {
	if(o == null) o = new_buf(84+4*str.length);
	var f = 0xC0;
	if(outl) {
		if(outl.above) f &= ~0x40;
		if(outl.left)  f &= ~0x80;
	}
	o.write_shift(1, f);
	for(var i = 1; i < 3; ++i) o.write_shift(1,0);
	write_BrtColor({auto:1}, o);
	o.write_shift(-4,-1);
	o.write_shift(-4,-1);
	write_XLSBCodeName(str, o);
	return o.slice(0, o.l);
}

/* [MS-XLSB] 2.4.306 BrtCellBlank */
function parse_BrtCellBlank(data) {
	var cell = parse_XLSBCell(data);
	return [cell];
}
function write_BrtCellBlank(cell, ncell, o) {
	if(o == null) o = new_buf(8);
	return write_XLSBCell(ncell, o);
}
function parse_BrtShortBlank(data) {
	var cell = parse_XLSBShortCell(data);
	return [cell];
}
function write_BrtShortBlank(cell, ncell, o) {
	if(o == null) o = new_buf(4);
	return write_XLSBShortCell(ncell, o);
}

/* [MS-XLSB] 2.4.307 BrtCellBool */
function parse_BrtCellBool(data) {
	var cell = parse_XLSBCell(data);
	var fBool = data.read_shift(1);
	return [cell, fBool, 'b'];
}
function write_BrtCellBool(cell, ncell, o) {
	if(o == null) o = new_buf(9);
	write_XLSBCell(ncell, o);
	o.write_shift(1, cell.v ? 1 : 0);
	return o;
}
function parse_BrtShortBool(data) {
	var cell = parse_XLSBShortCell(data);
	var fBool = data.read_shift(1);
	return [cell, fBool, 'b'];
}
function write_BrtShortBool(cell, ncell, o) {
	if(o == null) o = new_buf(5);
	write_XLSBShortCell(ncell, o);
	o.write_shift(1, cell.v ? 1 : 0);
	return o;
}

/* [MS-XLSB] 2.4.308 BrtCellError */
function parse_BrtCellError(data) {
	var cell = parse_XLSBCell(data);
	var bError = data.read_shift(1);
	return [cell, bError, 'e'];
}
function write_BrtCellError(cell, ncell, o) {
	if(o == null) o = new_buf(9);
	write_XLSBCell(ncell, o);
	o.write_shift(1, cell.v);
	return o;
}
function parse_BrtShortError(data) {
	var cell = parse_XLSBShortCell(data);
	var bError = data.read_shift(1);
	return [cell, bError, 'e'];
}
function write_BrtShortError(cell, ncell, o) {
	if(o == null) o = new_buf(8);
	write_XLSBShortCell(ncell, o);
	o.write_shift(1, cell.v);
	o.write_shift(2, 0);
	o.write_shift(1, 0);
	return o;
}


/* [MS-XLSB] 2.4.311 BrtCellIsst */
function parse_BrtCellIsst(data) {
	var cell = parse_XLSBCell(data);
	var isst = data.read_shift(4);
	return [cell, isst, 's'];
}
function write_BrtCellIsst(cell, ncell, o) {
	if(o == null) o = new_buf(12);
	write_XLSBCell(ncell, o);
	o.write_shift(4, ncell.v);
	return o;
}
function parse_BrtShortIsst(data) {
	var cell = parse_XLSBShortCell(data);
	var isst = data.read_shift(4);
	return [cell, isst, 's'];
}
function write_BrtShortIsst(cell, ncell, o) {
	if(o == null) o = new_buf(8);
	write_XLSBShortCell(ncell, o);
	o.write_shift(4, ncell.v);
	return o;
}

/* [MS-XLSB] 2.4.313 BrtCellReal */
function parse_BrtCellReal(data) {
	var cell = parse_XLSBCell(data);
	var value = parse_Xnum(data);
	return [cell, value, 'n'];
}
function write_BrtCellReal(cell, ncell, o) {
	if(o == null) o = new_buf(16);
	write_XLSBCell(ncell, o);
	write_Xnum(cell.v, o);
	return o;
}
function parse_BrtShortReal(data) {
	var cell = parse_XLSBShortCell(data);
	var value = parse_Xnum(data);
	return [cell, value, 'n'];
}
function write_BrtShortReal(cell, ncell, o) {
	if(o == null) o = new_buf(12);
	write_XLSBShortCell(ncell, o);
	write_Xnum(cell.v, o);
	return o;
}

/* [MS-XLSB] 2.4.314 BrtCellRk */
function parse_BrtCellRk(data) {
	var cell = parse_XLSBCell(data);
	var value = parse_RkNumber(data);
	return [cell, value, 'n'];
}
function write_BrtCellRk(cell, ncell, o) {
	if(o == null) o = new_buf(12);
	write_XLSBCell(ncell, o);
	write_RkNumber(cell.v, o);
	return o;
}
function parse_BrtShortRk(data) {
	var cell = parse_XLSBShortCell(data);
	var value = parse_RkNumber(data);
	return [cell, value, 'n'];
}
function write_BrtShortRk(cell, ncell, o) {
	if(o == null) o = new_buf(8);
	write_XLSBShortCell(ncell, o);
	write_RkNumber(cell.v, o);
	return o;
}

/* [MS-XLSB] 2.4.323 BrtCellRString */
function parse_BrtCellRString(data) {
	var cell = parse_XLSBCell(data);
	var value = parse_RichStr(data);
	return [cell, value, 'is'];
}

/* [MS-XLSB] 2.4.317 BrtCellSt */
function parse_BrtCellSt(data) {
	var cell = parse_XLSBCell(data);
	var value = parse_XLWideString(data);
	return [cell, value, 'str'];
}
function write_BrtCellSt(cell, ncell, o) {
	if(o == null) o = new_buf(12 + 4 * cell.v.length);
	write_XLSBCell(ncell, o);
	write_XLWideString(cell.v, o);
	return o.length > o.l ? o.slice(0, o.l) : o;
}
function parse_BrtShortSt(data) {
	var cell = parse_XLSBShortCell(data);
	var value = parse_XLWideString(data);
	return [cell, value, 'str'];
}
function write_BrtShortSt(cell, ncell, o) {
	if(o == null) o = new_buf(8 + 4 * cell.v.length);
	write_XLSBShortCell(ncell, o);
	write_XLWideString(cell.v, o);
	return o.length > o.l ? o.slice(0, o.l) : o;
}

/* [MS-XLSB] 2.4.653 BrtFmlaBool */
function parse_BrtFmlaBool(data, length, opts) {
	var end = data.l + length;
	var cell = parse_XLSBCell(data);
	cell.r = opts['!row'];
	var value = data.read_shift(1);
	var o = [cell, value, 'b'];
	if(opts.cellFormula) {
		data.l += 2;
		var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
		o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
	}
	else data.l = end;
	return o;
}

/* [MS-XLSB] 2.4.654 BrtFmlaError */
function parse_BrtFmlaError(data, length, opts) {
	var end = data.l + length;
	var cell = parse_XLSBCell(data);
	cell.r = opts['!row'];
	var value = data.read_shift(1);
	var o = [cell, value, 'e'];
	if(opts.cellFormula) {
		data.l += 2;
		var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
		o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
	}
	else data.l = end;
	return o;
}

/* [MS-XLSB] 2.4.655 BrtFmlaNum */
function parse_BrtFmlaNum(data, length, opts) {
	var end = data.l + length;
	var cell = parse_XLSBCell(data);
	cell.r = opts['!row'];
	var value = parse_Xnum(data);
	var o = [cell, value, 'n'];
	if(opts.cellFormula) {
		data.l += 2;
		var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
		o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
	}
	else data.l = end;
	return o;
}

/* [MS-XLSB] 2.4.656 BrtFmlaString */
function parse_BrtFmlaString(data, length, opts) {
	var end = data.l + length;
	var cell = parse_XLSBCell(data);
	cell.r = opts['!row'];
	var value = parse_XLWideString(data);
	var o = [cell, value, 'str'];
	if(opts.cellFormula) {
		data.l += 2;
		var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
		o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
	}
	else data.l = end;
	return o;
}

/* [MS-XLSB] 2.4.682 BrtMergeCell */
var parse_BrtMergeCell = parse_UncheckedRfX;
var write_BrtMergeCell = write_UncheckedRfX;
/* [MS-XLSB] 2.4.107 BrtBeginMergeCells */
function write_BrtBeginMergeCells(cnt, o) {
	if(o == null) o = new_buf(4);
	o.write_shift(4, cnt);
	return o;
}

/* [MS-XLSB] 2.4.662 BrtHLink */
function parse_BrtHLink(data, length/*::, opts*/) {
	var end = data.l + length;
	var rfx = parse_UncheckedRfX(data, 16);
	var relId = parse_XLNullableWideString(data);
	var loc = parse_XLWideString(data);
	var tooltip = parse_XLWideString(data);
	var display = parse_XLWideString(data);
	data.l = end;
	var o = ({rfx:rfx, relId:relId, loc:loc, display:display}/*:any*/);
	if(tooltip) o.Tooltip = tooltip;
	return o;
}
function write_BrtHLink(l, rId) {
	var o = new_buf(50+4*(l[1].Target.length + (l[1].Tooltip || "").length));
	write_UncheckedRfX({s:decode_cell(l[0]), e:decode_cell(l[0])}, o);
	write_RelID("rId" + rId, o);
	var locidx = l[1].Target.indexOf("#");
	var loc = locidx == -1 ? "" : l[1].Target.slice(locidx+1);
	write_XLWideString(loc || "", o);
	write_XLWideString(l[1].Tooltip || "", o);
	write_XLWideString("", o);
	return o.slice(0, o.l);
}

/* [MS-XLSB] 2.4.692 BrtPane */
function parse_BrtPane(/*data, length, opts*/) {
}

/* [MS-XLSB] 2.4.6 BrtArrFmla */
function parse_BrtArrFmla(data, length, opts) {
	var end = data.l + length;
	var rfx = parse_RfX(data, 16);
	var fAlwaysCalc = data.read_shift(1);
	var o = [rfx]; o[2] = fAlwaysCalc;
	if(opts.cellFormula) {
		var formula = parse_XLSBArrayParsedFormula(data, end - data.l, opts);
		o[1] = formula;
	} else data.l = end;
	return o;
}

/* [MS-XLSB] 2.4.750 BrtShrFmla */
function parse_BrtShrFmla(data, length, opts) {
	var end = data.l + length;
	var rfx = parse_UncheckedRfX(data, 16);
	var o = [rfx];
	if(opts.cellFormula) {
		var formula = parse_XLSBSharedParsedFormula(data, end - data.l, opts);
		o[1] = formula;
		data.l = end;
	} else data.l = end;
	return o;
}

/* [MS-XLSB] 2.4.323 BrtColInfo */
/* TODO: once XLS ColInfo is set, combine the functions */
function write_BrtColInfo(C/*:number*/, col, o) {
	if(o == null) o = new_buf(18);
	var p = col_obj_w(C, col);
	o.write_shift(-4, C);
	o.write_shift(-4, C);
	o.write_shift(4, (p.width || 10) * 256);
	o.write_shift(4, 0/*ixfe*/); // style
	var flags = 0;
	if(col.hidden) flags |= 0x01;
	if(typeof p.width == 'number') flags |= 0x02;
	if(col.level) flags |= (col.level << 8);
	o.write_shift(2, flags); // bit flag
	return o;
}

/* [MS-XLSB] 2.4.678 BrtMargins */
var BrtMarginKeys = ["left","right","top","bottom","header","footer"];
function parse_BrtMargins(data/*::, length, opts*/)/*:Margins*/ {
	var margins = ({}/*:any*/);
	BrtMarginKeys.forEach(function(k) { margins[k] = parse_Xnum(data, 8); });
	return margins;
}
function write_BrtMargins(margins/*:Margins*/, o) {
	if(o == null) o = new_buf(6*8);
	default_margins(margins);
	BrtMarginKeys.forEach(function(k) { write_Xnum((margins/*:any*/)[k], o); });
	return o;
}

/* [MS-XLSB] 2.4.299 BrtBeginWsView */
function parse_BrtBeginWsView(data/*::, length, opts*/) {
	var f = data.read_shift(2);
	data.l += 28;
	return { RTL: f & 0x20 };
}
function write_BrtBeginWsView(ws, Workbook, o) {
	if(o == null) o = new_buf(30);
	var f = 0x39c;
	if((((Workbook||{}).Views||[])[0]||{}).RTL) f |= 0x20;
	o.write_shift(2, f); // bit flag
	o.write_shift(4, 0);
	o.write_shift(4, 0); // view first row
	o.write_shift(4, 0); // view first col
	o.write_shift(1, 0); // gridline color ICV
	o.write_shift(1, 0);
	o.write_shift(2, 0);
	o.write_shift(2, 100); // zoom scale
	o.write_shift(2, 0);
	o.write_shift(2, 0);
	o.write_shift(2, 0);
	o.write_shift(4, 0); // workbook view id
	return o;
}

/* [MS-XLSB] 2.4.309 BrtCellIgnoreEC */
function write_BrtCellIgnoreEC(ref) {
	var o = new_buf(24);
	o.write_shift(4, 4);
	o.write_shift(4, 1);
	write_UncheckedRfX(ref, o);
	return o;
}

/* [MS-XLSB] 2.4.748 BrtSheetProtection */
function write_BrtSheetProtection(sp, o) {
	if(o == null) o = new_buf(16*4+2);
	o.write_shift(2, sp.password ? crypto_CreatePasswordVerifier_Method1(sp.password) : 0);
	o.write_shift(4, 1); // this record should not be written if no protection
	[
		["objects",             false], // fObjects
		["scenarios",           false], // fScenarios
		["formatCells",          true], // fFormatCells
		["formatColumns",        true], // fFormatColumns
		["formatRows",           true], // fFormatRows
		["insertColumns",        true], // fInsertColumns
		["insertRows",           true], // fInsertRows
		["insertHyperlinks",     true], // fInsertHyperlinks
		["deleteColumns",        true], // fDeleteColumns
		["deleteRows",           true], // fDeleteRows
		["selectLockedCells",   false], // fSelLockedCells
		["sort",                 true], // fSort
		["autoFilter",           true], // fAutoFilter
		["pivotTables",          true], // fPivotTables
		["selectUnlockedCells", false]  // fSelUnlockedCells
	].forEach(function(n) {
		/*:: if(o == null) throw "unreachable"; */
		if(n[1]) o.write_shift(4, sp[n[0]] != null && !sp[n[0]] ? 1 : 0);
		else      o.write_shift(4, sp[n[0]] != null && sp[n[0]] ? 0 : 1);
	});
	return o;
}

function parse_BrtDVal(/*data, length, opts*/) {
}
function parse_BrtDVal14(/*data, length, opts*/) {
}
/* [MS-XLSB] 2.1.7.61 Worksheet */
function parse_ws_bin(data, _opts, idx, rels, wb/*:WBWBProps*/, themes, styles)/*:Worksheet*/ {
	if(!data) return data;
	var opts = _opts || {};
	if(!rels) rels = {'!id':{}};
	if(DENSE != null && opts.dense == null) opts.dense = DENSE;
	var s/*:Worksheet*/ = (opts.dense ? [] : {});

	var ref;
	var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };

	var state/*:Array<string>*/ = [];
	var pass = false, end = false;
	var row, p, cf, R, C, addr, sstr, rr, cell/*:Cell*/;
	var merges/*:Array<Range>*/ = [];
	opts.biff = 12;
	opts['!row'] = 0;

	var ai = 0, af = false;

	var arrayf/*:Array<[Range, string]>*/ = [];
	var sharedf = {};
	var supbooks = opts.supbooks || /*::(*/wb/*:: :any)*/.supbooks || ([[]]/*:any*/);
	supbooks.sharedf = sharedf;
	supbooks.arrayf = arrayf;
	supbooks.SheetNames = wb.SheetNames || wb.Sheets.map(function(x) { return x.name; });
	if(!opts.supbooks) {
		opts.supbooks = supbooks;
		if(wb.Names) for(var i = 0; i < wb.Names.length; ++i) supbooks[0][i+1] = wb.Names[i];
	}

	var colinfo/*:Array<ColInfo>*/ = [], rowinfo/*:Array<RowInfo>*/ = [];
	var seencol = false;

	XLSBRecordEnum[0x0010] = { n:"BrtShortReal", f:parse_BrtShortReal };

	var cm, vm;

	recordhopper(data, function ws_parse(val, RR, RT) {
		if(end) return;
		switch(RT) {
			case 0x0094: /* 'BrtWsDim' */
				ref = val; break;
			case 0x0000: /* 'BrtRowHdr' */
				row = val;
				if(opts.sheetRows && opts.sheetRows <= row.r) end=true;
				rr = encode_row(R = row.r);
				opts['!row'] = row.r;
				if(val.hidden || val.hpt || val.level != null) {
					if(val.hpt) val.hpx = pt2px(val.hpt);
					rowinfo[val.r] = val;
				}
				break;

			case 0x0002: /* 'BrtCellRk' */
			case 0x0003: /* 'BrtCellError' */
			case 0x0004: /* 'BrtCellBool' */
			case 0x0005: /* 'BrtCellReal' */
			case 0x0006: /* 'BrtCellSt' */
			case 0x0007: /* 'BrtCellIsst' */
			case 0x0008: /* 'BrtFmlaString' */
			case 0x0009: /* 'BrtFmlaNum' */
			case 0x000A: /* 'BrtFmlaBool' */
			case 0x000B: /* 'BrtFmlaError' */
			case 0x000D: /* 'BrtShortRk' */
			case 0x000E: /* 'BrtShortError' */
			case 0x000F: /* 'BrtShortBool' */
			case 0x0010: /* 'BrtShortReal' */
			case 0x0011: /* 'BrtShortSt' */
			case 0x0012: /* 'BrtShortIsst' */
			case 0x003E: /* 'BrtCellRString' */
				p = ({t:val[2]}/*:any*/);
				switch(val[2]) {
					case 'n': p.v = val[1]; break;
					case 's': sstr = strs[val[1]]; p.v = sstr.t; p.r = sstr.r; break;
					case 'b': p.v = val[1] ? true : false; break;
					case 'e': p.v = val[1]; if(opts.cellText !== false) p.w = BErr[p.v]; break;
					case 'str': p.t = 's'; p.v = val[1]; break;
					case 'is': p.t = 's'; p.v = val[1].t; break;
				}
				if((cf = styles.CellXf[val[0].iStyleRef])) safe_format(p,cf.numFmtId,null,opts, themes, styles);
				C = val[0].c == -1 ? C + 1 : val[0].c;
				if(opts.dense) { if(!s[R]) s[R] = []; s[R][C] = p; }
				else s[encode_col(C) + rr] = p;
				if(opts.cellFormula) {
					af = false;
					for(ai = 0; ai < arrayf.length; ++ai) {
						var aii = arrayf[ai];
						if(row.r >= aii[0].s.r && row.r <= aii[0].e.r)
							if(C >= aii[0].s.c && C <= aii[0].e.c) {
								p.F = encode_range(aii[0]); af = true;
							}
					}
					if(!af && val.length > 3) p.f = val[3];
				}

				if(refguess.s.r > row.r) refguess.s.r = row.r;
				if(refguess.s.c > C) refguess.s.c = C;
				if(refguess.e.r < row.r) refguess.e.r = row.r;
				if(refguess.e.c < C) refguess.e.c = C;
				if(opts.cellDates && cf && p.t == 'n' && fmt_is_date(table_fmt[cf.numFmtId])) {
					var _d = SSF_parse_date_code(p.v); if(_d) { p.t = 'd'; p.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
				}
				if(cm) {
					if(cm.type == 'XLDAPR') p.D = true;
					cm = void 0;
				}
				if(vm) vm = void 0;
				break;

			case 0x0001: /* 'BrtCellBlank' */
			case 0x000C: /* 'BrtShortBlank' */
				if(!opts.sheetStubs || pass) break;
				p = ({t:'z',v:void 0}/*:any*/);
				C = val[0].c == -1 ? C + 1 : val[0].c;
				if(opts.dense) { if(!s[R]) s[R] = []; s[R][C] = p; }
				else s[encode_col(C) + rr] = p;
				if(refguess.s.r > row.r) refguess.s.r = row.r;
				if(refguess.s.c > C) refguess.s.c = C;
				if(refguess.e.r < row.r) refguess.e.r = row.r;
				if(refguess.e.c < C) refguess.e.c = C;
				if(cm) {
					if(cm.type == 'XLDAPR') p.D = true;
					cm = void 0;
				}
				if(vm) vm = void 0;
				break;

			case 0x00B0: /* 'BrtMergeCell' */
				merges.push(val); break;

			case 0x0031: { /* 'BrtCellMeta' */
				cm = ((opts.xlmeta||{}).Cell||[])[val-1];
			} break;

			case 0x01EE: /* 'BrtHLink' */
				var rel = rels['!id'][val.relId];
				if(rel) {
					val.Target = rel.Target;
					if(val.loc) val.Target += "#"+val.loc;
					val.Rel = rel;
				} else if(val.relId == '') {
					val.Target = "#" + val.loc;
				}
				for(R=val.rfx.s.r;R<=val.rfx.e.r;++R) for(C=val.rfx.s.c;C<=val.rfx.e.c;++C) {
					if(opts.dense) {
						if(!s[R]) s[R] = [];
						if(!s[R][C]) s[R][C] = {t:'z',v:undefined};
						s[R][C].l = val;
					} else {
						addr = encode_cell({c:C,r:R});
						if(!s[addr]) s[addr] = {t:'z',v:undefined};
						s[addr].l = val;
					}
				}
				break;

			case 0x01AA: /* 'BrtArrFmla' */
				if(!opts.cellFormula) break;
				arrayf.push(val);
				cell = ((opts.dense ? s[R][C] : s[encode_col(C) + rr])/*:any*/);
				cell.f = stringify_formula(val[1], refguess, {r:row.r, c:C}, supbooks, opts);
				cell.F = encode_range(val[0]);
				break;
			case 0x01AB: /* 'BrtShrFmla' */
				if(!opts.cellFormula) break;
				sharedf[encode_cell(val[0].s)] = val[1];
				cell = (opts.dense ? s[R][C] : s[encode_col(C) + rr]);
				cell.f = stringify_formula(val[1], refguess, {r:row.r, c:C}, supbooks, opts);
				break;

			/* identical to 'ColInfo' in XLS */
			case 0x003C: /* 'BrtColInfo' */
				if(!opts.cellStyles) break;
				while(val.e >= val.s) {
					colinfo[val.e--] = { width: val.w/256, hidden: !!(val.flags & 0x01), level: val.level };
					if(!seencol) { seencol = true; find_mdw_colw(val.w/256); }
					process_col(colinfo[val.e+1]);
				}
				break;

			case 0x00A1: /* 'BrtBeginAFilter' */
				s['!autofilter'] = { ref:encode_range(val) };
				break;

			case 0x01DC: /* 'BrtMargins' */
				s['!margins'] = val;
				break;

			case 0x0093: /* 'BrtWsProp' */
				if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
				if(val.name) wb.Sheets[idx].CodeName = val.name;
				if(val.above || val.left) s['!outline'] = { above: val.above, left: val.left };
				break;

			case 0x0089: /* 'BrtBeginWsView' */
				if(!wb.Views) wb.Views = [{}];
				if(!wb.Views[0]) wb.Views[0] = {};
				if(val.RTL) wb.Views[0].RTL = true;
				break;

			case 0x01E5: /* 'BrtWsFmtInfo' */
				break;

			case 0x0040: /* 'BrtDVal' */
			case 0x041D: /* 'BrtDVal14' */
				break;

			case 0x0097: /* 'BrtPane' */
				break;
			case 0x0098: /* 'BrtSel' */
			case 0x00AF: /* 'BrtAFilterDateGroupItem' */
			case 0x0284: /* 'BrtActiveX' */
			case 0x0271: /* 'BrtBigName' */
			case 0x0232: /* 'BrtBkHim' */
			case 0x018C: /* 'BrtBrk' */
			case 0x0458: /* 'BrtCFIcon' */
			case 0x047A: /* 'BrtCFRuleExt' */
			case 0x01D7: /* 'BrtCFVO' */
			case 0x041A: /* 'BrtCFVO14' */
			case 0x0289: /* 'BrtCellIgnoreEC' */
			case 0x0451: /* 'BrtCellIgnoreEC14' */
			case 0x024D: /* 'BrtCellSmartTagProperty' */
			case 0x025F: /* 'BrtCellWatch' */
			case 0x0234: /* 'BrtColor' */
			case 0x041F: /* 'BrtColor14' */
			case 0x00A8: /* 'BrtColorFilter' */
			case 0x00AE: /* 'BrtCustomFilter' */
			case 0x049C: /* 'BrtCustomFilter14' */
			case 0x01F3: /* 'BrtDRef' */
			case 0x01FB: /* 'BrtDXF' */
			case 0x0226: /* 'BrtDrawing' */
			case 0x00AB: /* 'BrtDynamicFilter' */
			case 0x00A7: /* 'BrtFilter' */
			case 0x0499: /* 'BrtFilter14' */
			case 0x00A9: /* 'BrtIconFilter' */
			case 0x049D: /* 'BrtIconFilter14' */
			case 0x0227: /* 'BrtLegacyDrawing' */
			case 0x0228: /* 'BrtLegacyDrawingHF' */
			case 0x0295: /* 'BrtListPart' */
			case 0x027F: /* 'BrtOleObject' */
			case 0x01DE: /* 'BrtPageSetup' */
			case 0x0219: /* 'BrtPhoneticInfo' */
			case 0x01DD: /* 'BrtPrintOptions' */
			case 0x0218: /* 'BrtRangeProtection' */
			case 0x044F: /* 'BrtRangeProtection14' */
			case 0x02A8: /* 'BrtRangeProtectionIso' */
			case 0x0450: /* 'BrtRangeProtectionIso14' */
			case 0x0400: /* 'BrtRwDescent' */
			case 0x0297: /* 'BrtSheetCalcProp' */
			case 0x0217: /* 'BrtSheetProtection' */
			case 0x02A6: /* 'BrtSheetProtectionIso' */
			case 0x01F8: /* 'BrtSlc' */
			case 0x0413: /* 'BrtSparkline' */
			case 0x01AC: /* 'BrtTable' */
			case 0x00AA: /* 'BrtTop10Filter' */
			case 0x0C00: /* 'BrtUid' */
			case 0x0032: /* 'BrtValueMeta' */
			case 0x0816: /* 'BrtWebExtension' */
			case 0x0415: /* 'BrtWsFmtInfoEx14' */
				break;

			case 0x0023: /* 'BrtFRTBegin' */
				pass = true; break;
			case 0x0024: /* 'BrtFRTEnd' */
				pass = false; break;
			case 0x0025: /* 'BrtACBegin' */
				state.push(RT); pass = true; break;
			case 0x0026: /* 'BrtACEnd' */
				state.pop(); pass = false; break;

			default:
				if(RR.T){/* empty */}
				else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
		}
	}, opts);

	delete opts.supbooks;
	delete opts['!row'];

	if(!s["!ref"] && (refguess.s.r < 2000000 || ref && (ref.e.r > 0 || ref.e.c > 0 || ref.s.r > 0 || ref.s.c > 0))) s["!ref"] = encode_range(ref || refguess);
	if(opts.sheetRows && s["!ref"]) {
		var tmpref = safe_decode_range(s["!ref"]);
		if(opts.sheetRows <= +tmpref.e.r) {
			tmpref.e.r = opts.sheetRows - 1;
			if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
			if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
			if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
			if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
			s["!fullref"] = s["!ref"];
			s["!ref"] = encode_range(tmpref);
		}
	}
	if(merges.length > 0) s["!merges"] = merges;
	if(colinfo.length > 0) s["!cols"] = colinfo;
	if(rowinfo.length > 0) s["!rows"] = rowinfo;
	return s;
}

/* TODO: something useful -- this is a stub */
function write_ws_bin_cell(ba/*:BufArray*/, cell/*:Cell*/, R/*:number*/, C/*:number*/, opts, ws/*:Worksheet*/, last_seen/*:boolean*/)/*:boolean*/ {
	if(cell.v === undefined) return false;
	var vv = "";
	switch(cell.t) {
		case 'b': vv = cell.v ? "1" : "0"; break;
		case 'd': // no BrtCellDate :(
			cell = dup(cell);
			cell.z = cell.z || table_fmt[14];
			cell.v = datenum(parseDate(cell.v)); cell.t = 'n';
			break;
		/* falls through */
		case 'n': case 'e': vv = ''+cell.v; break;
		default: vv = cell.v; break;
	}
	var o/*:any*/ = ({r:R, c:C}/*:any*/);
	/* TODO: cell style */
	o.s = get_cell_style(opts.cellXfs, cell, opts);
	if(cell.l) ws['!links'].push([encode_cell(o), cell.l]);
	if(cell.c) ws['!comments'].push([encode_cell(o), cell.c]);
	switch(cell.t) {
		case 's': case 'str':
			if(opts.bookSST) {
				vv = get_sst_id(opts.Strings, (cell.v/*:any*/), opts.revStrings);
				o.t = "s"; o.v = vv;
				if(last_seen) write_record(ba, 0x0012 /* BrtShortIsst */, write_BrtShortIsst(cell, o));
				else write_record(ba, 0x0007 /* BrtCellIsst */, write_BrtCellIsst(cell, o));
			} else {
				o.t = "str";
				if(last_seen) write_record(ba, 0x0011 /* BrtShortSt */, write_BrtShortSt(cell, o));
				else write_record(ba, 0x0006 /* BrtCellSt */, write_BrtCellSt(cell, o));
			}
			return true;
		case 'n':
			/* TODO: determine threshold for Real vs RK */
			if(cell.v == (cell.v | 0) && cell.v > -1000 && cell.v < 1000) {
				if(last_seen) write_record(ba, 0x000D /* BrtShortRk */, write_BrtShortRk(cell, o));
				else write_record(ba, 0x0002 /* BrtCellRk */, write_BrtCellRk(cell, o));
			} else {
				if(last_seen) write_record(ba, 0x0010 /* BrtShortReal */, write_BrtShortReal(cell, o));
				else write_record(ba, 0x0005 /* BrtCellReal */, write_BrtCellReal(cell, o));
			} return true;
		case 'b':
			o.t = "b";
			if(last_seen) write_record(ba, 0x000F /* BrtShortBool */, write_BrtShortBool(cell, o));
			else write_record(ba, 0x0004 /* BrtCellBool */, write_BrtCellBool(cell, o));
			return true;
		case 'e':
			o.t = "e";
			if(last_seen) write_record(ba, 0x000E /* BrtShortError */, write_BrtShortError(cell, o));
			else write_record(ba, 0x0003 /* BrtCellError */, write_BrtCellError(cell, o));
			return true;
	}
	if(last_seen) write_record(ba, 0x000C /* BrtShortBlank */, write_BrtShortBlank(cell, o));
	else write_record(ba, 0x0001 /* BrtCellBlank */, write_BrtCellBlank(cell, o));
	return true;
}

function write_CELLTABLE(ba, ws/*:Worksheet*/, idx/*:number*/, opts/*::, wb:Workbook*/) {
	var range = safe_decode_range(ws['!ref'] || "A1"), ref, rr = "", cols/*:Array<string>*/ = [];
	write_record(ba, 0x0091 /* BrtBeginSheetData */);
	var dense = Array.isArray(ws);
	var cap = range.e.r;
	if(ws['!rows']) cap = Math.max(range.e.r, ws['!rows'].length - 1);
	for(var R = range.s.r; R <= cap; ++R) {
		rr = encode_row(R);
		/* [ACCELLTABLE] */
		/* BrtRowHdr */
		write_row_header(ba, ws, range, R);
		var last_seen = false;
		if(R <= range.e.r) for(var C = range.s.c; C <= range.e.c; ++C) {
			/* *16384CELL */
			if(R === range.s.r) cols[C] = encode_col(C);
			ref = cols[C] + rr;
			var cell = dense ? (ws[R]||[])[C] : ws[ref];
			if(!cell) { last_seen = false; continue; }
			/* write cell */
			last_seen = write_ws_bin_cell(ba, cell, R, C, opts, ws, last_seen);
		}
	}
	write_record(ba, 0x0092 /* BrtEndSheetData */);
}

function write_MERGECELLS(ba, ws/*:Worksheet*/) {
	if(!ws || !ws['!merges']) return;
	write_record(ba, 0x00B1 /* BrtBeginMergeCells */, write_BrtBeginMergeCells(ws['!merges'].length));
	ws['!merges'].forEach(function(m) { write_record(ba, 0x00B0 /* BrtMergeCell */, write_BrtMergeCell(m)); });
	write_record(ba, 0x00B2 /* BrtEndMergeCells */);
}

function write_COLINFOS(ba, ws/*:Worksheet*//*::, idx:number, opts, wb:Workbook*/) {
	if(!ws || !ws['!cols']) return;
	write_record(ba, 0x0186 /* BrtBeginColInfos */);
	ws['!cols'].forEach(function(m, i) { if(m) write_record(ba, 0x003C /* 'BrtColInfo' */, write_BrtColInfo(i, m)); });
	write_record(ba, 0x0187 /* BrtEndColInfos */);
}

function write_IGNOREECS(ba, ws/*:Worksheet*/) {
	if(!ws || !ws['!ref']) return;
	write_record(ba, 0x0288 /* BrtBeginCellIgnoreECs */);
	write_record(ba, 0x0289 /* BrtCellIgnoreEC */, write_BrtCellIgnoreEC(safe_decode_range(ws['!ref'])));
	write_record(ba, 0x028A /* BrtEndCellIgnoreECs */);
}

function write_HLINKS(ba, ws/*:Worksheet*/, rels) {
	/* *BrtHLink */
	ws['!links'].forEach(function(l) {
		if(!l[1].Target) return;
		var rId = add_rels(rels, -1, l[1].Target.replace(/#.*$/, ""), RELS.HLINK);
		write_record(ba, 0x01EE /* BrtHLink */, write_BrtHLink(l, rId));
	});
	delete ws['!links'];
}
function write_LEGACYDRAWING(ba, ws/*:Worksheet*/, idx/*:number*/, rels) {
	/* [BrtLegacyDrawing] */
	if(ws['!comments'].length > 0) {
		var rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
		write_record(ba, 0x0227 /* BrtLegacyDrawing */, write_RelID("rId" + rId));
		ws['!legacy'] = rId;
	}
}

function write_AUTOFILTER(ba, ws, wb, idx) {
	if(!ws['!autofilter']) return;
	var data = ws['!autofilter'];
	var ref = typeof data.ref === "string" ? data.ref : encode_range(data.ref);

	/* Update FilterDatabase defined name for the worksheet */
	if(!wb.Workbook) wb.Workbook = ({Sheets:[]}/*:any*/);
	if(!wb.Workbook.Names) wb.Workbook.Names = [];
	var names/*: Array<any> */ = wb.Workbook.Names;
	var range = decode_range(ref);
	if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
	for(var i = 0; i < names.length; ++i) {
		var name = names[i];
		if(name.Name != '_xlnm._FilterDatabase') continue;
		if(name.Sheet != idx) continue;
		name.Ref = "'" + wb.SheetNames[idx] + "'!" + ref; break;
	}
	if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref  });

	write_record(ba, 0x00A1 /* BrtBeginAFilter */, write_UncheckedRfX(safe_decode_range(ref)));
	/* *FILTERCOLUMN */
	/* [SORTSTATE] */
	/* BrtEndAFilter */
	write_record(ba, 0x00A2 /* BrtEndAFilter */);
}

function write_WSVIEWS2(ba, ws, Workbook) {
	write_record(ba, 0x0085 /* BrtBeginWsViews */);
	{ /* 1*WSVIEW2 */
		/* [ACUID] */
		write_record(ba, 0x0089 /* BrtBeginWsView */, write_BrtBeginWsView(ws, Workbook));
		/* [BrtPane] */
		/* *4BrtSel */
		/* *4SXSELECT */
		/* *FRT */
		write_record(ba, 0x008A /* BrtEndWsView */);
	}
	/* *FRT */
	write_record(ba, 0x0086 /* BrtEndWsViews */);
}

function write_WSFMTINFO(/*::ba, ws*/) {
	/* [ACWSFMTINFO] */
	// write_record(ba, 0x01E5 /* BrtWsFmtInfo */, write_BrtWsFmtInfo(ws));
}

function write_SHEETPROTECT(ba, ws) {
	if(!ws['!protect']) return;
	/* [BrtSheetProtectionIso] */
	write_record(ba, 0x0217 /* BrtSheetProtection */, write_BrtSheetProtection(ws['!protect']));
}

function write_ws_bin(idx/*:number*/, opts, wb/*:Workbook*/, rels) {
	var ba = buf_array();
	var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
	var c/*:string*/ = s; try { if(wb && wb.Workbook) c = wb.Workbook.Sheets[idx].CodeName || c; } catch(e) {}
	var r = safe_decode_range(ws['!ref'] || "A1");
	if(r.e.c > 0x3FFF || r.e.r > 0xFFFFF) {
		if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:XFD1048576");
		r.e.c = Math.min(r.e.c, 0x3FFF);
		r.e.r = Math.min(r.e.c, 0xFFFFF);
	}
	ws['!links'] = [];
	/* passed back to write_zip and removed there */
	ws['!comments'] = [];
	write_record(ba, 0x0081 /* BrtBeginSheet */);
	if(wb.vbaraw || ws['!outline']) write_record(ba, 0x0093 /* BrtWsProp */, write_BrtWsProp(c, ws['!outline']));
	write_record(ba, 0x0094 /* BrtWsDim */, write_BrtWsDim(r));
	write_WSVIEWS2(ba, ws, wb.Workbook);
	write_WSFMTINFO(ba, ws);
	write_COLINFOS(ba, ws, idx, opts, wb);
	write_CELLTABLE(ba, ws, idx, opts, wb);
	/* [BrtSheetCalcProp] */
	write_SHEETPROTECT(ba, ws);
	/* *([BrtRangeProtectionIso] BrtRangeProtection) */
	/* [SCENMAN] */
	write_AUTOFILTER(ba, ws, wb, idx);
	/* [SORTSTATE] */
	/* [DCON] */
	/* [USERSHVIEWS] */
	write_MERGECELLS(ba, ws);
	/* [BrtPhoneticInfo] */
	/* *CONDITIONALFORMATTING */
	/* [DVALS] */
	write_HLINKS(ba, ws, rels);
	/* [BrtPrintOptions] */
	if(ws['!margins']) write_record(ba, 0x01DC /* BrtMargins */, write_BrtMargins(ws['!margins']));
	/* [BrtPageSetup] */
	/* [HEADERFOOTER] */
	/* [RWBRK] */
	/* [COLBRK] */
	/* *BrtBigName */
	/* [CELLWATCHES] */
	if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) write_IGNOREECS(ba, ws);
	/* [SMARTTAGS] */
	/* [BrtDrawing] */
	write_LEGACYDRAWING(ba, ws, idx, rels);
	/* [BrtLegacyDrawingHF] */
	/* [BrtBkHim] */
	/* [OLEOBJECTS] */
	/* [ACTIVEXCONTROLS] */
	/* [WEBPUBITEMS] */
	/* [LISTPARTS] */
	/* FRTWORKSHEET */
	write_record(ba, 0x0082 /* BrtEndSheet */);
	return ba.end();
}
function parse_Cache(data/*:string*/)/*:[Array<number|string>, string, ?string]*/ {
	var col/*:Array<number|string>*/ = [];
	var num = data.match(/^<c:numCache>/);
	var f;

	/* 21.2.2.150 pt CT_NumVal */
	(data.match(/<c:pt idx="(\d*)">(.*?)<\/c:pt>/mg)||[]).forEach(function(pt) {
		var q = pt.match(/<c:pt idx="(\d*?)"><c:v>(.*)<\/c:v><\/c:pt>/);
		if(!q) return;
		col[+q[1]] = num ? +q[2] : q[2];
	});

	/* 21.2.2.71 formatCode CT_Xstring */
	var nf = unescapexml((data.match(/<c:formatCode>([\s\S]*?)<\/c:formatCode>/) || ["","General"])[1]);

	(data.match(/<c:f>(.*?)<\/c:f>/mg)||[]).forEach(function(F) { f = F.replace(/<.*?>/g,""); });

	return [col, nf, f];
}

/* 21.2 DrawingML - Charts */
function parse_chart(data/*:?string*/, name/*:string*/, opts, rels, wb, csheet) {
	var cs/*:Worksheet*/ = ((csheet || {"!type":"chart"})/*:any*/);
	if(!data) return csheet;
	/* 21.2.2.27 chart CT_Chart */

	var C = 0, R = 0, col = "A";
	var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };

	/* 21.2.2.120 numCache CT_NumData */
	(data.match(/<c:numCache>[\s\S]*?<\/c:numCache>/gm)||[]).forEach(function(nc) {
		var cache = parse_Cache(nc);
		refguess.s.r = refguess.s.c = 0;
		refguess.e.c = C;
		col = encode_col(C);
		cache[0].forEach(function(n,i) {
			cs[col + encode_row(i)] = {t:'n', v:n, z:cache[1] };
			R = i;
		});
		if(refguess.e.r < R) refguess.e.r = R;
		++C;
	});
	if(C > 0) cs["!ref"] = encode_range(refguess);
	return cs;
}
/* 18.3 Worksheets also covers Chartsheets */
function parse_cs_xml(data/*:?string*/, opts, idx/*:number*/, rels, wb/*::, themes, styles*/)/*:Worksheet*/ {
	if(!data) return data;
	/* 18.3.1.12 chartsheet CT_ChartSheet */
	if(!rels) rels = {'!id':{}};
	var s = ({'!type':"chart", '!drawel':null, '!rel':""}/*:any*/);
	var m;

	/* 18.3.1.83 sheetPr CT_ChartsheetPr */
	var sheetPr = data.match(sheetprregex);
	if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);

	/* 18.3.1.36 drawing CT_Drawing */
	if((m = data.match(/drawing r:id="(.*?)"/))) s['!rel'] = m[1];

	if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
	return s;
}
function write_cs_xml(idx/*:number*/, opts, wb/*:Workbook*/, rels)/*:string*/ {
	var o = [XML_HEADER, writextag('chartsheet', null, {
		'xmlns': XMLNS_main[0],
		'xmlns:r': XMLNS.r
	})];
	o[o.length] = writextag("drawing", null, {"r:id": "rId1"});
	add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
	if(o.length>2) { o[o.length] = ('</chartsheet>'); o[1]=o[1].replace("/>",">"); }
	return o.join("");
}

/* [MS-XLSB] 2.4.331 BrtCsProp */
function parse_BrtCsProp(data, length/*:number*/) {
	data.l += 10;
	var name = parse_XLWideString(data, length - 10);
	return { name: name };
}

/* [MS-XLSB] 2.1.7.7 Chart Sheet */
function parse_cs_bin(data, opts, idx/*:number*/, rels, wb/*::, themes, styles*/)/*:Worksheet*/ {
	if(!data) return data;
	if(!rels) rels = {'!id':{}};
	var s = {'!type':"chart", '!drawel':null, '!rel':""};
	var state/*:Array<string>*/ = [];
	var pass = false;
	recordhopper(data, function cs_parse(val, R, RT) {
		switch(RT) {

			case 0x0226: /* 'BrtDrawing' */
				s['!rel'] = val; break;

			case 0x028B: /* 'BrtCsProp' */
				if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
				if(val.name) wb.Sheets[idx].CodeName = val.name;
				break;

			case 0x0232: /* 'BrtBkHim' */
			case 0x028C: /* 'BrtCsPageSetup' */
			case 0x029D: /* 'BrtCsProtection' */
			case 0x02A7: /* 'BrtCsProtectionIso' */
			case 0x0227: /* 'BrtLegacyDrawing' */
			case 0x0228: /* 'BrtLegacyDrawingHF' */
			case 0x01DC: /* 'BrtMargins' */
			case 0x0C00: /* 'BrtUid' */
				break;

			case 0x0023: /* 'BrtFRTBegin' */
				pass = true; break;
			case 0x0024: /* 'BrtFRTEnd' */
				pass = false; break;
			case 0x0025: /* 'BrtACBegin' */
				state.push(RT); break;
			case 0x0026: /* 'BrtACEnd' */
				state.pop(); break;

			default:
				if(R.T > 0) state.push(RT);
				else if(R.T < 0) state.pop();
				else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
		}
	}, opts);

	if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
	return s;
}
function write_cs_bin(/*::idx:number, opts, wb:Workbook, rels*/) {
	var ba = buf_array();
	write_record(ba, 0x0081 /* BrtBeginSheet */);
	/* [BrtCsProp] */
	/* CSVIEWS */
	/* [[BrtCsProtectionIso] BrtCsProtection] */
	/* [USERCSVIEWS] */
	/* [BrtMargins] */
	/* [BrtCsPageSetup] */
	/* [HEADERFOOTER] */
	/* BrtDrawing */
	/* [BrtLegacyDrawing] */
	/* [BrtLegacyDrawingHF] */
	/* [BrtBkHim] */
	/* [WEBPUBITEMS] */
	/* FRTCHARTSHEET */
	write_record(ba, 0x0082 /* BrtEndSheet */);
	return ba.end();
}
/* 18.2.28 (CT_WorkbookProtection) Defaults */
var WBPropsDef = [
	['allowRefreshQuery',           false, "bool"],
	['autoCompressPictures',        true,  "bool"],
	['backupFile',                  false, "bool"],
	['checkCompatibility',          false, "bool"],
	['CodeName',                    ''],
	['date1904',                    false, "bool"],
	['defaultThemeVersion',         0,      "int"],
	['filterPrivacy',               false, "bool"],
	['hidePivotFieldList',          false, "bool"],
	['promptedSolutions',           false, "bool"],
	['publishItems',                false, "bool"],
	['refreshAllConnections',       false, "bool"],
	['saveExternalLinkValues',      true,  "bool"],
	['showBorderUnselectedTables',  true,  "bool"],
	['showInkAnnotation',           true,  "bool"],
	['showObjects',                 'all'],
	['showPivotChartFilter',        false, "bool"],
	['updateLinks', 'userSet']
];

/* 18.2.30 (CT_BookView) Defaults */
var WBViewDef = [
	['activeTab',                   0,      "int"],
	['autoFilterDateGrouping',      true,  "bool"],
	['firstSheet',                  0,      "int"],
	['minimized',                   false, "bool"],
	['showHorizontalScroll',        true,  "bool"],
	['showSheetTabs',               true,  "bool"],
	['showVerticalScroll',          true,  "bool"],
	['tabRatio',                    600,    "int"],
	['visibility',                  'visible']
	//window{Height,Width}, {x,y}Window
];

/* 18.2.19 (CT_Sheet) Defaults */
var SheetDef = [
	//['state', 'visible']
];

/* 18.2.2  (CT_CalcPr) Defaults */
var CalcPrDef = [
	['calcCompleted', 'true'],
	['calcMode', 'auto'],
	['calcOnSave', 'true'],
	['concurrentCalc', 'true'],
	['fullCalcOnLoad', 'false'],
	['fullPrecision', 'true'],
	['iterate', 'false'],
	['iterateCount', '100'],
	['iterateDelta', '0.001'],
	['refMode', 'A1']
];

/* 18.2.3 (CT_CustomWorkbookView) Defaults */
/*var CustomWBViewDef = [
	['autoUpdate', 'false'],
	['changesSavedWin', 'false'],
	['includeHiddenRowCol', 'true'],
	['includePrintSettings', 'true'],
	['maximized', 'false'],
	['minimized', 'false'],
	['onlySync', 'false'],
	['personalView', 'false'],
	['showComments', 'commIndicator'],
	['showFormulaBar', 'true'],
	['showHorizontalScroll', 'true'],
	['showObjects', 'all'],
	['showSheetTabs', 'true'],
	['showStatusbar', 'true'],
	['showVerticalScroll', 'true'],
	['tabRatio', '600'],
	['xWindow', '0'],
	['yWindow', '0']
];*/

function push_defaults_array(target, defaults) {
	for(var j = 0; j != target.length; ++j) { var w = target[j];
		for(var i=0; i != defaults.length; ++i) { var z = defaults[i];
			if(w[z[0]] == null) w[z[0]] = z[1];
			else switch(z[2]) {
			case "bool": if(typeof w[z[0]] == "string") w[z[0]] = parsexmlbool(w[z[0]]); break;
			case "int": if(typeof w[z[0]] == "string") w[z[0]] = parseInt(w[z[0]], 10); break;
			}
		}
	}
}
function push_defaults(target, defaults) {
	for(var i = 0; i != defaults.length; ++i) { var z = defaults[i];
		if(target[z[0]] == null) target[z[0]] = z[1];
		else switch(z[2]) {
			case "bool": if(typeof target[z[0]] == "string") target[z[0]] = parsexmlbool(target[z[0]]); break;
			case "int": if(typeof target[z[0]] == "string") target[z[0]] = parseInt(target[z[0]], 10); break;
		}
	}
}

function parse_wb_defaults(wb) {
	push_defaults(wb.WBProps, WBPropsDef);
	push_defaults(wb.CalcPr, CalcPrDef);

	push_defaults_array(wb.WBView, WBViewDef);
	push_defaults_array(wb.Sheets, SheetDef);

	_ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904);
}

function safe1904(wb/*:Workbook*/)/*:string*/ {
	/* TODO: store date1904 somewhere else */
	if(!wb.Workbook) return "false";
	if(!wb.Workbook.WBProps) return "false";
	return parsexmlbool(wb.Workbook.WBProps.date1904) ? "true" : "false";
}

var badchars = /*#__PURE__*/"][*?\/\\".split("");
function check_ws_name(n/*:string*/, safe/*:?boolean*/)/*:boolean*/ {
	if(n.length > 31) { if(safe) return false; throw new Error("Sheet names cannot exceed 31 chars"); }
	var _good = true;
	badchars.forEach(function(c) {
		if(n.indexOf(c) == -1) return;
		if(!safe) throw new Error("Sheet name cannot contain : \\ / ? * [ ]");
		_good = false;
	});
	return _good;
}
function check_wb_names(N, S, codes) {
	N.forEach(function(n,i) {
		check_ws_name(n);
		for(var j = 0; j < i; ++j) if(n == N[j]) throw new Error("Duplicate Sheet Name: " + n);
		if(codes) {
			var cn = (S && S[i] && S[i].CodeName) || n;
			if(cn.charCodeAt(0) == 95 && cn.length > 22) throw new Error("Bad Code Name: Worksheet" + cn);
		}
	});
}
function check_wb(wb) {
	if(!wb || !wb.SheetNames || !wb.Sheets) throw new Error("Invalid Workbook");
	if(!wb.SheetNames.length) throw new Error("Workbook is empty");
	var Sheets = (wb.Workbook && wb.Workbook.Sheets) || [];
	check_wb_names(wb.SheetNames, Sheets, !!wb.vbaraw);
	for(var i = 0; i < wb.SheetNames.length; ++i) check_ws(wb.Sheets[wb.SheetNames[i]], wb.SheetNames[i], i);
	/* TODO: validate workbook */
}
/* 18.2 Workbook */
var wbnsregex = /<\w+:workbook/;
function parse_wb_xml(data, opts)/*:WorkbookFile*/ {
	if(!data) throw new Error("Could not find file");
	var wb = /*::(*/{ AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, Names:[], xmlns: "" }/*::)*/;
	var pass = false, xmlns = "xmlns";
	var dname = {}, dnstart = 0;
	data.replace(tagregex, function xml_wb(x, idx) {
		var y/*:any*/ = parsexmltag(x);
		switch(strip_ns(y[0])) {
			case '<?xml': break;

			/* 18.2.27 workbook CT_Workbook 1 */
			case '<workbook':
				if(x.match(wbnsregex)) xmlns = "xmlns" + x.match(/<(\w+):/)[1];
				wb.xmlns = y[xmlns];
				break;
			case '</workbook>': break;

			/* 18.2.13 fileVersion CT_FileVersion ? */
			case '<fileVersion': delete y[0]; wb.AppVersion = y; break;
			case '<fileVersion/>': case '</fileVersion>': break;

			/* 18.2.12 fileSharing CT_FileSharing ? */
			case '<fileSharing':
				break;
			case '<fileSharing/>': break;

			/* 18.2.28 workbookPr CT_WorkbookPr ? */
			case '<workbookPr':
			case '<workbookPr/>':
				WBPropsDef.forEach(function(w) {
					if(y[w[0]] == null) return;
					switch(w[2]) {
						case "bool": wb.WBProps[w[0]] = parsexmlbool(y[w[0]]); break;
						case "int": wb.WBProps[w[0]] = parseInt(y[w[0]], 10); break;
						default: wb.WBProps[w[0]] = y[w[0]];
					}
				});
				if(y.codeName) wb.WBProps.CodeName = utf8read(y.codeName);
				break;
			case '</workbookPr>': break;

			/* 18.2.29 workbookProtection CT_WorkbookProtection ? */
			case '<workbookProtection':
				break;
			case '<workbookProtection/>': break;

			/* 18.2.1  bookViews CT_BookViews ? */
			case '<bookViews': case '<bookViews>': case '</bookViews>': break;
			/* 18.2.30   workbookView CT_BookView + */
			case '<workbookView': case '<workbookView/>': delete y[0]; wb.WBView.push(y); break;
			case '</workbookView>': break;

			/* 18.2.20 sheets CT_Sheets 1 */
			case '<sheets': case '<sheets>': case '</sheets>': break; // aggregate sheet
			/* 18.2.19   sheet CT_Sheet + */
			case '<sheet':
				switch(y.state) {
					case "hidden": y.Hidden = 1; break;
					case "veryHidden": y.Hidden = 2; break;
					default: y.Hidden = 0;
				}
				delete y.state;
				y.name = unescapexml(utf8read(y.name));
				delete y[0]; wb.Sheets.push(y); break;
			case '</sheet>': break;

			/* 18.2.15 functionGroups CT_FunctionGroups ? */
			case '<functionGroups': case '<functionGroups/>': break;
			/* 18.2.14   functionGroup CT_FunctionGroup + */
			case '<functionGroup': break;

			/* 18.2.9  externalReferences CT_ExternalReferences ? */
			case '<externalReferences': case '</externalReferences>': case '<externalReferences>': break;
			/* 18.2.8    externalReference CT_ExternalReference + */
			case '<externalReference': break;

			/* 18.2.6  definedNames CT_DefinedNames ? */
			case '<definedNames/>': break;
			case '<definedNames>': case '<definedNames': pass=true; break;
			case '</definedNames>': pass=false; break;
			/* 18.2.5    definedName CT_DefinedName + */
			case '<definedName': {
				dname = {};
				dname.Name = utf8read(y.name);
				if(y.comment) dname.Comment = y.comment;
				if(y.localSheetId) dname.Sheet = +y.localSheetId;
				if(parsexmlbool(y.hidden||"0")) dname.Hidden = true;
				dnstart = idx + x.length;
			}	break;
			case '</definedName>': {
				dname.Ref = unescapexml(utf8read(data.slice(dnstart, idx)));
				wb.Names.push(dname);
			} break;
			case '<definedName/>': break;

			/* 18.2.2  calcPr CT_CalcPr ? */
			case '<calcPr': delete y[0]; wb.CalcPr = y; break;
			case '<calcPr/>': delete y[0]; wb.CalcPr = y; break;
			case '</calcPr>': break;

			/* 18.2.16 oleSize CT_OleSize ? (ref required) */
			case '<oleSize': break;

			/* 18.2.4  customWorkbookViews CT_CustomWorkbookViews ? */
			case '<customWorkbookViews>': case '</customWorkbookViews>': case '<customWorkbookViews': break;
			/* 18.2.3  customWorkbookView CT_CustomWorkbookView + */
			case '<customWorkbookView': case '</customWorkbookView>': break;

			/* 18.2.18 pivotCaches CT_PivotCaches ? */
			case '<pivotCaches>': case '</pivotCaches>': case '<pivotCaches': break;
			/* 18.2.17 pivotCache CT_PivotCache ? */
			case '<pivotCache': break;

			/* 18.2.21 smartTagPr CT_SmartTagPr ? */
			case '<smartTagPr': case '<smartTagPr/>': break;

			/* 18.2.23 smartTagTypes CT_SmartTagTypes ? */
			case '<smartTagTypes': case '<smartTagTypes>': case '</smartTagTypes>': break;
			/* 18.2.22 smartTagType CT_SmartTagType ? */
			case '<smartTagType': break;

			/* 18.2.24 webPublishing CT_WebPublishing ? */
			case '<webPublishing': case '<webPublishing/>': break;

			/* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */
			case '<fileRecoveryPr': case '<fileRecoveryPr/>': break;

			/* 18.2.26 webPublishObjects CT_WebPublishObjects ? */
			case '<webPublishObjects>': case '<webPublishObjects': case '</webPublishObjects>': break;
			/* 18.2.25 webPublishObject CT_WebPublishObject ? */
			case '<webPublishObject': break;

			/* 18.2.10 extLst CT_ExtensionList ? */
			case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
			/* 18.2.7  ext CT_Extension + */
			case '<ext': pass=true; break; //TODO: check with versions of excel
			case '</ext>': pass=false; break;

			/* Others */
			case '<ArchID': break;
			case '<AlternateContent':
			case '<AlternateContent>': pass=true; break;
			case '</AlternateContent>': pass=false; break;

			/* TODO */
			case '<revisionPtr': break;

			default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in workbook');
		}
		return x;
	});
	if(XMLNS_main.indexOf(wb.xmlns) === -1) throw new Error("Unknown Namespace: " + wb.xmlns);

	parse_wb_defaults(wb);

	return wb;
}

function write_wb_xml(wb/*:Workbook*//*::, opts:?WriteOpts*/)/*:string*/ {
	var o = [XML_HEADER];
	o[o.length] = writextag('workbook', null, {
		'xmlns': XMLNS_main[0],
		//'xmlns:mx': XMLNS.mx,
		//'xmlns:s': XMLNS_main[0],
		'xmlns:r': XMLNS.r
	});

	var write_names = (wb.Workbook && (wb.Workbook.Names||[]).length > 0);

	/* fileVersion */
	/* fileSharing */

	var workbookPr/*:any*/ = ({codeName:"ThisWorkbook"}/*:any*/);
	if(wb.Workbook && wb.Workbook.WBProps) {
		WBPropsDef.forEach(function(x) {
			/*:: if(!wb.Workbook || !wb.Workbook.WBProps) throw "unreachable"; */
			if((wb.Workbook.WBProps[x[0]]/*:any*/) == null) return;
			if((wb.Workbook.WBProps[x[0]]/*:any*/) == x[1]) return;
			workbookPr[x[0]] = (wb.Workbook.WBProps[x[0]]/*:any*/);
		});
		/*:: if(!wb.Workbook || !wb.Workbook.WBProps) throw "unreachable"; */
		if(wb.Workbook.WBProps.CodeName) { workbookPr.codeName = wb.Workbook.WBProps.CodeName; delete workbookPr.CodeName; }
	}
	o[o.length] = (writextag('workbookPr', null, workbookPr));

	/* workbookProtection */

	var sheets = wb.Workbook && wb.Workbook.Sheets || [];
	var i = 0;

	/* bookViews only written if first worksheet is hidden */
	if(sheets && sheets[0] && !!sheets[0].Hidden) {
		o[o.length] = "<bookViews>";
		for(i = 0; i != wb.SheetNames.length; ++i) {
			if(!sheets[i]) break;
			if(!sheets[i].Hidden) break;
		}
		if(i == wb.SheetNames.length) i = 0;
		o[o.length] = '<workbookView firstSheet="' + i + '" activeTab="' + i + '"/>';
		o[o.length] = "</bookViews>";
	}

	o[o.length] = "<sheets>";
	for(i = 0; i != wb.SheetNames.length; ++i) {
		var sht = ({name:escapexml(wb.SheetNames[i].slice(0,31))}/*:any*/);
		sht.sheetId = ""+(i+1);
		sht["r:id"] = "rId"+(i+1);
		if(sheets[i]) switch(sheets[i].Hidden) {
			case 1: sht.state = "hidden"; break;
			case 2: sht.state = "veryHidden"; break;
		}
		o[o.length] = (writextag('sheet',null,sht));
	}
	o[o.length] = "</sheets>";

	/* functionGroups */
	/* externalReferences */

	if(write_names) {
		o[o.length] = "<definedNames>";
		if(wb.Workbook && wb.Workbook.Names) wb.Workbook.Names.forEach(function(n) {
			var d/*:any*/ = {name:n.Name};
			if(n.Comment) d.comment = n.Comment;
			if(n.Sheet != null) d.localSheetId = ""+n.Sheet;
			if(n.Hidden) d.hidden = "1";
			if(!n.Ref) return;
			o[o.length] = writextag('definedName', escapexml(n.Ref), d);
		});
		o[o.length] = "</definedNames>";
	}

	/* calcPr */
	/* oleSize */
	/* customWorkbookViews */
	/* pivotCaches */
	/* smartTagPr */
	/* smartTagTypes */
	/* webPublishing */
	/* fileRecoveryPr */
	/* webPublishObjects */
	/* extLst */

	if(o.length>2){ o[o.length] = '</workbook>'; o[1]=o[1].replace("/>",">"); }
	return o.join("");
}
/* [MS-XLSB] 2.4.304 BrtBundleSh */
function parse_BrtBundleSh(data, length/*:number*/) {
	var z = {};
	z.Hidden = data.read_shift(4); //hsState ST_SheetState
	z.iTabID = data.read_shift(4);
	z.strRelID = parse_RelID(data,length-8);
	z.name = parse_XLWideString(data);
	return z;
}
function write_BrtBundleSh(data, o) {
	if(!o) o = new_buf(127);
	o.write_shift(4, data.Hidden);
	o.write_shift(4, data.iTabID);
	write_RelID(data.strRelID, o);
	write_XLWideString(data.name.slice(0,31), o);
	return o.length > o.l ? o.slice(0, o.l) : o;
}

/* [MS-XLSB] 2.4.815 BrtWbProp */
function parse_BrtWbProp(data, length)/*:WBProps*/ {
	var o/*:WBProps*/ = ({}/*:any*/);
	var flags = data.read_shift(4);
	o.defaultThemeVersion = data.read_shift(4);
	var strName = (length > 8) ? parse_XLWideString(data) : "";
	if(strName.length > 0) o.CodeName = strName;
	o.autoCompressPictures = !!(flags & 0x10000);
	o.backupFile = !!(flags & 0x40);
	o.checkCompatibility = !!(flags & 0x1000);
	o.date1904 = !!(flags & 0x01);
	o.filterPrivacy = !!(flags & 0x08);
	o.hidePivotFieldList = !!(flags & 0x400);
	o.promptedSolutions = !!(flags & 0x10);
	o.publishItems = !!(flags & 0x800);
	o.refreshAllConnections = !!(flags & 0x40000);
	o.saveExternalLinkValues = !!(flags & 0x80);
	o.showBorderUnselectedTables = !!(flags & 0x04);
	o.showInkAnnotation = !!(flags & 0x20);
	o.showObjects = ["all", "placeholders", "none"][(flags >> 13) & 0x03];
	o.showPivotChartFilter = !!(flags & 0x8000);
	o.updateLinks = ["userSet", "never", "always"][(flags >> 8) & 0x03];
	return o;
}
function write_BrtWbProp(data/*:?WBProps*/, o) {
	if(!o) o = new_buf(72);
	var flags = 0;
	if(data) {
		/* TODO: mirror parse_BrtWbProp fields */
		if(data.filterPrivacy) flags |= 0x08;
	}
	o.write_shift(4, flags);
	o.write_shift(4, 0);
	write_XLSBCodeName(data && data.CodeName || "ThisWorkbook", o);
	return o.slice(0, o.l);
}

function parse_BrtFRTArchID$(data, length) {
	var o = {};
	data.read_shift(4);
	o.ArchID = data.read_shift(4);
	data.l += length - 8;
	return o;
}

/* [MS-XLSB] 2.4.687 BrtName */
function parse_BrtName(data, length, opts) {
	var end = data.l + length;
	data.l += 4; //var flags = data.read_shift(4);
	data.l += 1; //var chKey = data.read_shift(1);
	var itab = data.read_shift(4);
	var name = parse_XLNameWideString(data);
	var formula = parse_XLSBNameParsedFormula(data, 0, opts);
	var comment = parse_XLNullableWideString(data);
	//if(0 /* fProc */) {
		// unusedstring1: XLNullableWideString
		// description: XLNullableWideString
		// helpTopic: XLNullableWideString
		// unusedstring2: XLNullableWideString
	//}
	data.l = end;
	var out = ({Name:name, Ptg:formula}/*:any*/);
	if(itab < 0xFFFFFFF) out.Sheet = itab;
	if(comment) out.Comment = comment;
	return out;
}

/* [MS-XLSB] 2.1.7.61 Workbook */
function parse_wb_bin(data, opts)/*:WorkbookFile*/ {
	var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, xmlns: "" };
	var state/*:Array<string>*/ = [];
	var pass = false;

	if(!opts) opts = {};
	opts.biff = 12;

	var Names = [];
	var supbooks = ([[]]/*:any*/);
	supbooks.SheetNames = [];
	supbooks.XTI = [];

	XLSBRecordEnum[0x0010] = { n:"BrtFRTArchID$", f:parse_BrtFRTArchID$ };

	recordhopper(data, function hopper_wb(val, R, RT) {
		switch(RT) {
			case 0x009C: /* 'BrtBundleSh' */
				supbooks.SheetNames.push(val.name);
				wb.Sheets.push(val); break;

			case 0x0099: /* 'BrtWbProp' */
				wb.WBProps = val; break;

			case 0x0027: /* 'BrtName' */
				if(val.Sheet != null) opts.SID = val.Sheet;
				val.Ref = stringify_formula(val.Ptg, null, null, supbooks, opts);
				delete opts.SID;
				delete val.Ptg;
				Names.push(val);
				break;
			case 0x040C: /* 'BrtNameExt' */ break;

			case 0x0165: /* 'BrtSupSelf' */
			case 0x0166: /* 'BrtSupSame' */
			case 0x0163: /* 'BrtSupBookSrc' */
			case 0x029B: /* 'BrtSupAddin' */
				if(!supbooks[0].length) supbooks[0] = [RT, val];
				else supbooks.push([RT, val]);
				supbooks[supbooks.length - 1].XTI = [];
				break;
			case 0x016A: /* 'BrtExternSheet' */
				if(supbooks.length === 0) { supbooks[0] = []; supbooks[0].XTI = []; }
				supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val);
				supbooks.XTI = supbooks.XTI.concat(val);
				break;
			case 0x0169: /* 'BrtPlaceholderName' */
				break;

			case 0x0817: /* 'BrtAbsPath15' */
			case 0x009E: /* 'BrtBookView' */
			case 0x008F: /* 'BrtBeginBundleShs' */
			case 0x0298: /* 'BrtBeginFnGroup' */
			case 0x0161: /* 'BrtBeginExternals' */
				break;

			/* case 'BrtModelTimeGroupingCalcCol' */
			case 0x0C00: /* 'BrtUid' */
			case 0x0C01: /* 'BrtRevisionPtr' */
			case 0x0216: /* 'BrtBookProtection' */
			case 0x02A5: /* 'BrtBookProtectionIso' */
			case 0x009D: /* 'BrtCalcProp' */
			case 0x0262: /* 'BrtCrashRecErr' */
			case 0x0802: /* 'BrtDecoupledPivotCacheID' */
			case 0x009B: /* 'BrtFileRecover' */
			case 0x0224: /* 'BrtFileSharing' */
			case 0x02A4: /* 'BrtFileSharingIso' */
			case 0x0080: /* 'BrtFileVersion' */
			case 0x0299: /* 'BrtFnGroup' */
			case 0x0850: /* 'BrtModelRelationship' */
			case 0x084D: /* 'BrtModelTable' */
			case 0x0225: /* 'BrtOleSize' */
			case 0x0805: /* 'BrtPivotTableRef' */
			case 0x0254: /* 'BrtSmartTagType' */
			case 0x081C: /* 'BrtTableSlicerCacheID' */
			case 0x081B: /* 'BrtTableSlicerCacheIDs' */
			case 0x0822: /* 'BrtTimelineCachePivotCacheID' */
			case 0x018D: /* 'BrtUserBookView' */
			case 0x009A: /* 'BrtWbFactoid' */
			case 0x045D: /* 'BrtWbProp14' */
			case 0x0229: /* 'BrtWebOpt' */
			case 0x082B: /* 'BrtWorkBookPr15' */
				break;

			case 0x0023: /* 'BrtFRTBegin' */
				state.push(RT); pass = true; break;
			case 0x0024: /* 'BrtFRTEnd' */
				state.pop(); pass = false; break;
			case 0x0025: /* 'BrtACBegin' */
				state.push(RT); pass = true; break;
			case 0x0026: /* 'BrtACEnd' */
				state.pop(); pass = false; break;

			case 0x0010: /* 'BrtFRTArchID$' */ break;

			default:
				if(R.T){/* empty */}
				else if(!pass || (opts.WTF && state[state.length-1] != 0x0025 /* BrtACBegin */ && state[state.length-1] != 0x0023 /* BrtFRTBegin */)) throw new Error("Unexpected record 0x" + RT.toString(16));
		}
	}, opts);

	parse_wb_defaults(wb);

	// $FlowIgnore
	wb.Names = Names;

	(wb/*:any*/).supbooks = supbooks;
	return wb;
}

function write_BUNDLESHS(ba, wb/*::, opts*/) {
	write_record(ba, 0x008F /* BrtBeginBundleShs */);
	for(var idx = 0; idx != wb.SheetNames.length; ++idx) {
		var viz = wb.Workbook && wb.Workbook.Sheets && wb.Workbook.Sheets[idx] && wb.Workbook.Sheets[idx].Hidden || 0;
		var d = { Hidden: viz, iTabID: idx+1, strRelID: 'rId' + (idx+1), name: wb.SheetNames[idx] };
		write_record(ba, 0x009C /* BrtBundleSh */, write_BrtBundleSh(d));
	}
	write_record(ba, 0x0090 /* BrtEndBundleShs */);
}

/* [MS-XLSB] 2.4.649 BrtFileVersion */
function write_BrtFileVersion(data, o) {
	if(!o) o = new_buf(127);
	for(var i = 0; i != 4; ++i) o.write_shift(4, 0);
	write_XLWideString("SheetJS", o);
	write_XLWideString(XLSX.version, o);
	write_XLWideString(XLSX.version, o);
	write_XLWideString("7262", o);
	return o.length > o.l ? o.slice(0, o.l) : o;
}

/* [MS-XLSB] 2.4.301 BrtBookView */
function write_BrtBookView(idx, o) {
	if(!o) o = new_buf(29);
	o.write_shift(-4, 0);
	o.write_shift(-4, 460);
	o.write_shift(4,  28800);
	o.write_shift(4,  17600);
	o.write_shift(4,  500);
	o.write_shift(4,  idx);
	o.write_shift(4,  idx);
	var flags = 0x78;
	o.write_shift(1,  flags);
	return o.length > o.l ? o.slice(0, o.l) : o;
}

function write_BOOKVIEWS(ba, wb/*::, opts*/) {
	/* required if hidden tab appears before visible tab */
	if(!wb.Workbook || !wb.Workbook.Sheets) return;
	var sheets = wb.Workbook.Sheets;
	var i = 0, vistab = -1, hidden = -1;
	for(; i < sheets.length; ++i) {
		if(!sheets[i] || !sheets[i].Hidden && vistab == -1) vistab = i;
		else if(sheets[i].Hidden == 1 && hidden == -1) hidden = i;
	}
	if(hidden > vistab) return;
	write_record(ba, 0x0087 /* BrtBeginBookViews */);
	write_record(ba, 0x009E /* BrtBookView */, write_BrtBookView(vistab));
	/* 1*(BrtBookView *FRT) */
	write_record(ba, 0x0088 /* BrtEndBookViews */);
}

/* [MS-XLSB] 2.4.305 BrtCalcProp */
/*function write_BrtCalcProp(data, o) {
	if(!o) o = new_buf(26);
	o.write_shift(4,0); // force recalc
	o.write_shift(4,1);
	o.write_shift(4,0);
	write_Xnum(0, o);
	o.write_shift(-4, 1023);
	o.write_shift(1, 0x33);
	o.write_shift(1, 0x00);
	return o;
}*/

/* [MS-XLSB] 2.4.646 BrtFileRecover */
/*function write_BrtFileRecover(data, o) {
	if(!o) o = new_buf(1);
	o.write_shift(1,0);
	return o;
}*/

/* [MS-XLSB] 2.1.7.61 Workbook */
function write_wb_bin(wb, opts) {
	var ba = buf_array();
	write_record(ba, 0x0083 /* BrtBeginBook */);
	write_record(ba, 0x0080 /* BrtFileVersion */, write_BrtFileVersion());
	/* [[BrtFileSharingIso] BrtFileSharing] */
	write_record(ba, 0x0099 /* BrtWbProp */, write_BrtWbProp(wb.Workbook && wb.Workbook.WBProps || null));
	/* [ACABSPATH] */
	/* [[BrtBookProtectionIso] BrtBookProtection] */
	write_BOOKVIEWS(ba, wb, opts);
	write_BUNDLESHS(ba, wb, opts);
	/* [FNGROUP] */
	/* [EXTERNALS] */
	/* *BrtName */
	/* write_record(ba, 0x009D BrtCalcProp, write_BrtCalcProp()); */
	/* [BrtOleSize] */
	/* *(BrtUserBookView *FRT) */
	/* [PIVOTCACHEIDS] */
	/* [BrtWbFactoid] */
	/* [SMARTTAGTYPES] */
	/* [BrtWebOpt] */
	/* write_record(ba, 0x009B BrtFileRecover, write_BrtFileRecover()); */
	/* [WEBPUBITEMS] */
	/* [CRERRS] */
	/* FRTWORKBOOK */
	write_record(ba, 0x0084 /* BrtEndBook */);

	return ba.end();
}
function parse_wb(data, name/*:string*/, opts)/*:WorkbookFile*/ {
	if(name.slice(-4)===".bin") return parse_wb_bin((data/*:any*/), opts);
	return parse_wb_xml((data/*:any*/), opts);
}

function parse_ws(data, name/*:string*/, idx/*:number*/, opts, rels, wb, themes, styles)/*:Worksheet*/ {
	if(name.slice(-4)===".bin") return parse_ws_bin((data/*:any*/), opts, idx, rels, wb, themes, styles);
	return parse_ws_xml((data/*:any*/), opts, idx, rels, wb, themes, styles);
}

function parse_cs(data, name/*:string*/, idx/*:number*/, opts, rels, wb, themes, styles)/*:Worksheet*/ {
	if(name.slice(-4)===".bin") return parse_cs_bin((data/*:any*/), opts, idx, rels, wb, themes, styles);
	return parse_cs_xml((data/*:any*/), opts, idx, rels, wb, themes, styles);
}

function parse_ms(data, name/*:string*/, idx/*:number*/, opts, rels, wb, themes, styles)/*:Worksheet*/ {
	if(name.slice(-4)===".bin") return parse_ms_bin((data/*:any*/), opts, idx, rels, wb, themes, styles);
	return parse_ms_xml((data/*:any*/), opts, idx, rels, wb, themes, styles);
}

function parse_ds(data, name/*:string*/, idx/*:number*/, opts, rels, wb, themes, styles)/*:Worksheet*/ {
	if(name.slice(-4)===".bin") return parse_ds_bin((data/*:any*/), opts, idx, rels, wb, themes, styles);
	return parse_ds_xml((data/*:any*/), opts, idx, rels, wb, themes, styles);
}

function parse_sty(data, name/*:string*/, themes, opts) {
	if(name.slice(-4)===".bin") return parse_sty_bin((data/*:any*/), themes, opts);
	return parse_sty_xml((data/*:any*/), themes, opts);
}

function parse_theme(data/*:string*/, name/*:string*/, opts) {
	return parse_theme_xml(data, opts);
}

function parse_sst(data, name/*:string*/, opts)/*:SST*/ {
	if(name.slice(-4)===".bin") return parse_sst_bin((data/*:any*/), opts);
	return parse_sst_xml((data/*:any*/), opts);
}

function parse_cmnt(data, name/*:string*/, opts)/*:Array<RawComment>*/ {
	if(name.slice(-4)===".bin") return parse_comments_bin((data/*:any*/), opts);
	return parse_comments_xml((data/*:any*/), opts);
}

function parse_cc(data, name/*:string*/, opts) {
	if(name.slice(-4)===".bin") return parse_cc_bin((data/*:any*/), name, opts);
	return parse_cc_xml((data/*:any*/), name, opts);
}

function parse_xlink(data, rel, name/*:string*/, opts) {
	if(name.slice(-4)===".bin") return parse_xlink_bin((data/*:any*/), rel, name, opts);
	return parse_xlink_xml((data/*:any*/), rel, name, opts);
}

function parse_xlmeta(data, name/*:string*/, opts) {
	if(name.slice(-4)===".bin") return parse_xlmeta_bin((data/*:any*/), name, opts);
	return parse_xlmeta_xml((data/*:any*/), name, opts);
}

function write_wb(wb, name/*:string*/, opts) {
	return (name.slice(-4)===".bin" ? write_wb_bin : write_wb_xml)(wb, opts);
}

function write_ws(data/*:number*/, name/*:string*/, opts, wb/*:Workbook*/, rels) {
	return (name.slice(-4)===".bin" ? write_ws_bin : write_ws_xml)(data, opts, wb, rels);
}

// eslint-disable-next-line no-unused-vars
function write_cs(data/*:number*/, name/*:string*/, opts, wb/*:Workbook*/, rels) {
	return (name.slice(-4)===".bin" ? write_cs_bin : write_cs_xml)(data, opts, wb, rels);
}

function write_sty(data, name/*:string*/, opts) {
	return (name.slice(-4)===".bin" ? write_sty_bin : write_sty_xml)(data, opts);
}

function write_sst(data/*:SST*/, name/*:string*/, opts) {
	return (name.slice(-4)===".bin" ? write_sst_bin : write_sst_xml)(data, opts);
}

function write_cmnt(data/*:Array<any>*/, name/*:string*/, opts) {
	return (name.slice(-4)===".bin" ? write_comments_bin : write_comments_xml)(data, opts);
}
/*
function write_cc(data, name:string, opts) {
	return (name.slice(-4)===".bin" ? write_cc_bin : write_cc_xml)(data, opts);
}
*/

function write_xlmeta(name/*:string*/) {
	return (name.slice(-4)===".bin" ? write_xlmeta_bin : write_xlmeta_xml)();
}
var attregexg2=/([\w:]+)=((?:")([^"]*)(?:")|(?:')([^']*)(?:'))/g;
var attregex2=/([\w:]+)=((?:")(?:[^"]*)(?:")|(?:')(?:[^']*)(?:'))/;
function xlml_parsexmltag(tag/*:string*/, skip_root/*:?boolean*/) {
	var words = tag.split(/\s+/);
	var z/*:any*/ = ([]/*:any*/); if(!skip_root) z[0] = words[0];
	if(words.length === 1) return z;
	var m = tag.match(attregexg2), y, j, w, i;
	if(m) for(i = 0; i != m.length; ++i) {
		y = m[i].match(attregex2);
/*:: if(!y || !y[2]) continue; */
		if((j=y[1].indexOf(":")) === -1) z[y[1]] = y[2].slice(1,y[2].length-1);
		else {
			if(y[1].slice(0,6) === "xmlns:") w = "xmlns"+y[1].slice(6);
			else w = y[1].slice(j+1);
			z[w] = y[2].slice(1,y[2].length-1);
		}
	}
	return z;
}
function xlml_parsexmltagobj(tag/*:string*/) {
	var words = tag.split(/\s+/);
	var z = {};
	if(words.length === 1) return z;
	var m = tag.match(attregexg2), y, j, w, i;
	if(m) for(i = 0; i != m.length; ++i) {
		y = m[i].match(attregex2);
/*:: if(!y || !y[2]) continue; */
		if((j=y[1].indexOf(":")) === -1) z[y[1]] = y[2].slice(1,y[2].length-1);
		else {
			if(y[1].slice(0,6) === "xmlns:") w = "xmlns"+y[1].slice(6);
			else w = y[1].slice(j+1);
			z[w] = y[2].slice(1,y[2].length-1);
		}
	}
	return z;
}

// ----

/* map from xlml named formats to SSF TODO: localize */
var XLMLFormatMap/*: {[string]:string}*/;

function xlml_format(format, value)/*:string*/ {
	var fmt = XLMLFormatMap[format] || unescapexml(format);
	if(fmt === "General") return SSF_general(value);
	return SSF_format(fmt, value);
}

function xlml_set_custprop(Custprops, key, cp, val/*:string*/) {
	var oval/*:any*/ = val;
	switch((cp[0].match(/dt:dt="([\w.]+)"/)||["",""])[1]) {
		case "boolean": oval = parsexmlbool(val); break;
		case "i2": case "int": oval = parseInt(val, 10); break;
		case "r4": case "float": oval = parseFloat(val); break;
		case "date": case "dateTime.tz": oval = parseDate(val); break;
		case "i8": case "string": case "fixed": case "uuid": case "bin.base64": break;
		default: throw new Error("bad custprop:" + cp[0]);
	}
	Custprops[unescapexml(key)] = oval;
}

function safe_format_xlml(cell/*:Cell*/, nf, o) {
	if(cell.t === 'z') return;
	if(!o || o.cellText !== false) try {
		if(cell.t === 'e') { cell.w = cell.w || BErr[cell.v]; }
		else if(nf === "General") {
			if(cell.t === 'n') {
				if((cell.v|0) === cell.v) cell.w = cell.v.toString(10);
				else cell.w = SSF_general_num(cell.v);
			}
			else cell.w = SSF_general(cell.v);
		}
		else cell.w = xlml_format(nf||"General", cell.v);
	} catch(e) { if(o.WTF) throw e; }
	try {
		var z = XLMLFormatMap[nf]||nf||"General";
		if(o.cellNF) cell.z = z;
		if(o.cellDates && cell.t == 'n' && fmt_is_date(z)) {
			var _d = SSF_parse_date_code(cell.v); if(_d) { cell.t = 'd'; cell.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
		}
	} catch(e) { if(o.WTF) throw e; }
}

function process_style_xlml(styles, stag, opts) {
	if(opts.cellStyles) {
		if(stag.Interior) {
			var I = stag.Interior;
			if(I.Pattern) I.patternType = XLMLPatternTypeMap[I.Pattern] || I.Pattern;
		}
	}
	styles[stag.ID] = stag;
}

/* TODO: there must exist some form of OSP-blessed spec */
function parse_xlml_data(xml, ss, data, cell/*:any*/, base, styles, csty, row, arrayf, o) {
	var nf = "General", sid = cell.StyleID, S = {}; o = o || {};
	var interiors = [];
	var i = 0;
	if(sid === undefined && row) sid = row.StyleID;
	if(sid === undefined && csty) sid = csty.StyleID;
	while(styles[sid] !== undefined) {
		if(styles[sid].nf) nf = styles[sid].nf;
		if(styles[sid].Interior) interiors.push(styles[sid].Interior);
		if(!styles[sid].Parent) break;
		sid = styles[sid].Parent;
	}
	switch(data.Type) {
		case 'Boolean':
			cell.t = 'b';
			cell.v = parsexmlbool(xml);
			break;
		case 'String':
			cell.t = 's'; cell.r = xlml_fixstr(unescapexml(xml));
			cell.v = (xml.indexOf("<") > -1 ? unescapexml(ss||xml).replace(/<.*?>/g, "") : cell.r); // todo: BR etc
			break;
		case 'DateTime':
			if(xml.slice(-1) != "Z") xml += "Z";
			cell.v = (parseDate(xml) - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
			if(cell.v !== cell.v) cell.v = unescapexml(xml);
			else if(cell.v<60) cell.v = cell.v -1;
			if(!nf || nf == "General") nf = "yyyy-mm-dd";
			/* falls through */
		case 'Number':
			if(cell.v === undefined) cell.v=+xml;
			if(!cell.t) cell.t = 'n';
			break;
		case 'Error': cell.t = 'e'; cell.v = RBErr[xml]; if(o.cellText !== false) cell.w = xml; break;
		default:
			if(xml == "" && ss == "") { cell.t = 'z'; }
			else { cell.t = 's'; cell.v = xlml_fixstr(ss||xml); }
			break;
	}
	safe_format_xlml(cell, nf, o);
	if(o.cellFormula !== false) {
		if(cell.Formula) {
			var fstr = unescapexml(cell.Formula);
			/* strictly speaking, the leading = is required but some writers omit */
			if(fstr.charCodeAt(0) == 61 /* = */) fstr = fstr.slice(1);
			cell.f = rc_to_a1(fstr, base);
			delete cell.Formula;
			if(cell.ArrayRange == "RC") cell.F = rc_to_a1("RC:RC", base);
			else if(cell.ArrayRange) {
				cell.F = rc_to_a1(cell.ArrayRange, base);
				arrayf.push([safe_decode_range(cell.F), cell.F]);
			}
		} else {
			for(i = 0; i < arrayf.length; ++i)
				if(base.r >= arrayf[i][0].s.r && base.r <= arrayf[i][0].e.r)
					if(base.c >= arrayf[i][0].s.c && base.c <= arrayf[i][0].e.c)
						cell.F = arrayf[i][1];
		}
	}
	if(o.cellStyles) {
		interiors.forEach(function(x) {
			if(!S.patternType && x.patternType) S.patternType = x.patternType;
		});
		cell.s = S;
	}
	if(cell.StyleID !== undefined) cell.ixfe = cell.StyleID;
}

function xlml_clean_comment(comment/*:any*/) {
	comment.t = comment.v || "";
	comment.t = comment.t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");
	comment.v = comment.w = comment.ixfe = undefined;
}

/* TODO: Everything */
function parse_xlml_xml(d, _opts)/*:Workbook*/ {
	var opts = _opts || {};
	make_ssf();
	var str = debom(xlml_normalize(d));
	if(opts.type == 'binary' || opts.type == 'array' || opts.type == 'base64') {
		if(typeof $cptable !== 'undefined') str = $cptable.utils.decode(65001, char_codes(str));
		else str = utf8read(str);
	}
	var opening = str.slice(0, 1024).toLowerCase(), ishtml = false;
	opening = opening.replace(/".*?"/g, "");
	if((opening.indexOf(">") & 1023) > Math.min((opening.indexOf(",") & 1023), (opening.indexOf(";")&1023))) { var _o = dup(opts); _o.type = "string"; return PRN.to_workbook(str, _o); }
	if(opening.indexOf("<?xml") == -1) ["html", "table", "head", "meta", "script", "style", "div"].forEach(function(tag) { if(opening.indexOf("<" + tag) >= 0) ishtml = true; });
	if(ishtml) return html_to_workbook(str, opts);

	XLMLFormatMap = ({
		"General Number": "General",
		"General Date": table_fmt[22],
		"Long Date": "dddd, mmmm dd, yyyy",
		"Medium Date": table_fmt[15],
		"Short Date": table_fmt[14],
		"Long Time": table_fmt[19],
		"Medium Time": table_fmt[18],
		"Short Time": table_fmt[20],
		"Currency": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
		"Fixed": table_fmt[2],
		"Standard": table_fmt[4],
		"Percent": table_fmt[10],
		"Scientific": table_fmt[11],
		"Yes/No": '"Yes";"Yes";"No";@',
		"True/False": '"True";"True";"False";@',
		"On/Off": '"Yes";"Yes";"No";@'
	}/*:any*/);


	var Rn;
	var state = [], tmp;
	if(DENSE != null && opts.dense == null) opts.dense = DENSE;
	var sheets = {}, sheetnames/*:Array<string>*/ = [], cursheet/*:Worksheet*/ = (opts.dense ? [] : {}), sheetname = "";
	var cell = ({}/*:any*/), row = {};// eslint-disable-line no-unused-vars
	var dtag = xlml_parsexmltag('<Data ss:Type="String">'), didx = 0;
	var c = 0, r = 0;
	var refguess/*:Range*/ = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
	var styles = {}, stag = {};
	var ss = "", fidx = 0;
	var merges/*:Array<Range>*/ = [];
	var Props = {}, Custprops = {}, pidx = 0, cp = [];
	var comments/*:Array<Comment>*/ = [], comment/*:Comment*/ = ({}/*:any*/);
	var cstys = [], csty, seencol = false;
	var arrayf/*:Array<[Range, string]>*/ = [];
	var rowinfo/*:Array<RowInfo>*/ = [], rowobj = {}, cc = 0, rr = 0;
	var Workbook/*:WBWBProps*/ = ({ Sheets:[], WBProps:{date1904:false} }/*:any*/), wsprops = {};
	xlmlregex.lastIndex = 0;
	str = str.replace(/<!--([\s\S]*?)-->/mg,"");
	var raw_Rn3 = "";
	while((Rn = xlmlregex.exec(str))) switch((Rn[3] = (raw_Rn3 = Rn[3]).toLowerCase())) {
		case 'data' /*case 'Data'*/:
			if(raw_Rn3 == "data") {
				if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
				else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
				break;
			}
			if(state[state.length-1][1]) break;
			if(Rn[1]==='/') parse_xlml_data(str.slice(didx, Rn.index), ss, dtag, state[state.length-1][0]==/*"Comment"*/"comment"?comment:cell, {c:c,r:r}, styles, cstys[c], row, arrayf, opts);
			else { ss = ""; dtag = xlml_parsexmltag(Rn[0]); didx = Rn.index + Rn[0].length; }
			break;
		case 'cell' /*case 'Cell'*/:
			if(Rn[1]==='/'){
				if(comments.length > 0) cell.c = comments;
				if((!opts.sheetRows || opts.sheetRows > r) && cell.v !== undefined) {
					if(opts.dense) {
						if(!cursheet[r]) cursheet[r] = [];
						cursheet[r][c] = cell;
					} else cursheet[encode_col(c) + encode_row(r)] = cell;
				}
				if(cell.HRef) {
					cell.l = ({Target:unescapexml(cell.HRef)}/*:any*/);
					if(cell.HRefScreenTip) cell.l.Tooltip = cell.HRefScreenTip;
					delete cell.HRef; delete cell.HRefScreenTip;
				}
				if(cell.MergeAcross || cell.MergeDown) {
					cc = c + (parseInt(cell.MergeAcross,10)|0);
					rr = r + (parseInt(cell.MergeDown,10)|0);
					merges.push({s:{c:c,r:r},e:{c:cc,r:rr}});
				}
				if(!opts.sheetStubs) { if(cell.MergeAcross) c = cc + 1; else ++c; }
				else if(cell.MergeAcross || cell.MergeDown) {
					/*:: if(!cc) cc = 0; if(!rr) rr = 0; */
					for(var cma = c; cma <= cc; ++cma) {
						for(var cmd = r; cmd <= rr; ++cmd) {
							if(cma > c || cmd > r) {
								if(opts.dense) {
									if(!cursheet[cmd]) cursheet[cmd] = [];
									cursheet[cmd][cma] = {t:'z'};
								} else cursheet[encode_col(cma) + encode_row(cmd)] = {t:'z'};
							}
						}
					}
					c = cc + 1;
				}
				else ++c;
			} else {
				cell = xlml_parsexmltagobj(Rn[0]);
				if(cell.Index) c = +cell.Index - 1;
				if(c < refguess.s.c) refguess.s.c = c;
				if(c > refguess.e.c) refguess.e.c = c;
				if(Rn[0].slice(-2) === "/>") ++c;
				comments = [];
			}
			break;
		case 'row' /*case 'Row'*/:
			if(Rn[1]==='/' || Rn[0].slice(-2) === "/>") {
				if(r < refguess.s.r) refguess.s.r = r;
				if(r > refguess.e.r) refguess.e.r = r;
				if(Rn[0].slice(-2) === "/>") {
					row = xlml_parsexmltag(Rn[0]);
					if(row.Index) r = +row.Index - 1;
				}
				c = 0; ++r;
			} else {
				row = xlml_parsexmltag(Rn[0]);
				if(row.Index) r = +row.Index - 1;
				rowobj = {};
				if(row.AutoFitHeight == "0" || row.Height) {
					rowobj.hpx = parseInt(row.Height, 10); rowobj.hpt = px2pt(rowobj.hpx);
					rowinfo[r] = rowobj;
				}
				if(row.Hidden == "1") { rowobj.hidden = true; rowinfo[r] = rowobj; }
			}
			break;
		case 'worksheet' /*case 'Worksheet'*/: /* TODO: read range from FullRows/FullColumns */
			if(Rn[1]==='/'){
				if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
				sheetnames.push(sheetname);
				if(refguess.s.r <= refguess.e.r && refguess.s.c <= refguess.e.c) {
					cursheet["!ref"] = encode_range(refguess);
					if(opts.sheetRows && opts.sheetRows <= refguess.e.r) {
						cursheet["!fullref"] = cursheet["!ref"];
						refguess.e.r = opts.sheetRows - 1;
						cursheet["!ref"] = encode_range(refguess);
					}
				}
				if(merges.length) cursheet["!merges"] = merges;
				if(cstys.length > 0) cursheet["!cols"] = cstys;
				if(rowinfo.length > 0) cursheet["!rows"] = rowinfo;
				sheets[sheetname] = cursheet;
			} else {
				refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
				r = c = 0;
				state.push([Rn[3], false]);
				tmp = xlml_parsexmltag(Rn[0]);
				sheetname = unescapexml(tmp.Name);
				cursheet = (opts.dense ? [] : {});
				merges = [];
				arrayf = [];
				rowinfo = [];
				wsprops = {name:sheetname, Hidden:0};
				Workbook.Sheets.push(wsprops);
			}
			break;
		case 'table' /*case 'Table'*/:
			if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
			else if(Rn[0].slice(-2) == "/>") break;
			else {
				state.push([Rn[3], false]);
				cstys = []; seencol = false;
			}
			break;

		case 'style' /*case 'Style'*/:
			if(Rn[1]==='/') process_style_xlml(styles, stag, opts);
			else stag = xlml_parsexmltag(Rn[0]);
			break;

		case 'numberformat' /*case 'NumberFormat'*/:
			stag.nf = unescapexml(xlml_parsexmltag(Rn[0]).Format || "General");
			if(XLMLFormatMap[stag.nf]) stag.nf = XLMLFormatMap[stag.nf];
			for(var ssfidx = 0; ssfidx != 0x188; ++ssfidx) if(table_fmt[ssfidx] == stag.nf) break;
			if(ssfidx == 0x188) for(ssfidx = 0x39; ssfidx != 0x188; ++ssfidx) if(table_fmt[ssfidx] == null) { SSF_load(stag.nf, ssfidx); break; }
			break;

		case 'column' /*case 'Column'*/:
			if(state[state.length-1][0] !== /*'Table'*/'table') break;
			csty = xlml_parsexmltag(Rn[0]);
			if(csty.Hidden) { csty.hidden = true; delete csty.Hidden; }
			if(csty.Width) csty.wpx = parseInt(csty.Width, 10);
			if(!seencol && csty.wpx > 10) {
				seencol = true; MDW = DEF_MDW; //find_mdw_wpx(csty.wpx);
				for(var _col = 0; _col < cstys.length; ++_col) if(cstys[_col]) process_col(cstys[_col]);
			}
			if(seencol) process_col(csty);
			cstys[(csty.Index-1||cstys.length)] = csty;
			for(var i = 0; i < +csty.Span; ++i) cstys[cstys.length] = dup(csty);
			break;

		case 'namedrange' /*case 'NamedRange'*/:
			if(Rn[1]==='/') break;
			if(!Workbook.Names) Workbook.Names = [];
			var _NamedRange = parsexmltag(Rn[0]);
			var _DefinedName/*:DefinedName*/ = ({
				Name: _NamedRange.Name,
				Ref: rc_to_a1(_NamedRange.RefersTo.slice(1), {r:0, c:0})
			}/*:any*/);
			if(Workbook.Sheets.length>0) _DefinedName.Sheet=Workbook.Sheets.length-1;
			/*:: if(Workbook.Names) */Workbook.Names.push(_DefinedName);
			break;

		case 'namedcell' /*case 'NamedCell'*/: break;
		case 'b' /*case 'B'*/: break;
		case 'i' /*case 'I'*/: break;
		case 'u' /*case 'U'*/: break;
		case 's' /*case 'S'*/: break;
		case 'em' /*case 'EM'*/: break;
		case 'h2' /*case 'H2'*/: break;
		case 'h3' /*case 'H3'*/: break;
		case 'sub' /*case 'Sub'*/: break;
		case 'sup' /*case 'Sup'*/: break;
		case 'span' /*case 'Span'*/: break;
		case 'alignment' /*case 'Alignment'*/:
			break;
		case 'borders' /*case 'Borders'*/: break;
		case 'border' /*case 'Border'*/: break;
		case 'font' /*case 'Font'*/:
			if(Rn[0].slice(-2) === "/>") break;
			else if(Rn[1]==="/") ss += str.slice(fidx, Rn.index);
			else fidx = Rn.index + Rn[0].length;
			break;
		case 'interior' /*case 'Interior'*/:
			if(!opts.cellStyles) break;
			stag.Interior = xlml_parsexmltag(Rn[0]);
			break;
		case 'protection' /*case 'Protection'*/: break;

		case 'author' /*case 'Author'*/:
		case 'title' /*case 'Title'*/:
		case 'description' /*case 'Description'*/:
		case 'created' /*case 'Created'*/:
		case 'keywords' /*case 'Keywords'*/:
		case 'subject' /*case 'Subject'*/:
		case 'category' /*case 'Category'*/:
		case 'company' /*case 'Company'*/:
		case 'lastauthor' /*case 'LastAuthor'*/:
		case 'lastsaved' /*case 'LastSaved'*/:
		case 'lastprinted' /*case 'LastPrinted'*/:
		case 'version' /*case 'Version'*/:
		case 'revision' /*case 'Revision'*/:
		case 'totaltime' /*case 'TotalTime'*/:
		case 'hyperlinkbase' /*case 'HyperlinkBase'*/:
		case 'manager' /*case 'Manager'*/:
		case 'contentstatus' /*case 'ContentStatus'*/:
		case 'identifier' /*case 'Identifier'*/:
		case 'language' /*case 'Language'*/:
		case 'appname' /*case 'AppName'*/:
			if(Rn[0].slice(-2) === "/>") break;
			else if(Rn[1]==="/") xlml_set_prop(Props, raw_Rn3, str.slice(pidx, Rn.index));
			else pidx = Rn.index + Rn[0].length;
			break;
		case 'paragraphs' /*case 'Paragraphs'*/: break;

		case 'styles' /*case 'Styles'*/:
		case 'workbook' /*case 'Workbook'*/:
			if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
			else state.push([Rn[3], false]);
			break;

		case 'comment' /*case 'Comment'*/:
			if(Rn[1]==='/'){
				if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
				xlml_clean_comment(comment);
				comments.push(comment);
			} else {
				state.push([Rn[3], false]);
				tmp = xlml_parsexmltag(Rn[0]);
				comment = ({a:tmp.Author}/*:any*/);
			}
			break;

		case 'autofilter' /*case 'AutoFilter'*/:
			if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
			else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
				var AutoFilter = xlml_parsexmltag(Rn[0]);
				cursheet['!autofilter'] = { ref:rc_to_a1(AutoFilter.Range).replace(/\$/g,"") };
				state.push([Rn[3], true]);
			}
			break;

		case 'name' /*case 'Name'*/: break;

		case 'datavalidation' /*case 'DataValidation'*/:
			if(Rn[1]==='/'){
				if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
			} else {
				if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
			}
			break;

		case 'pixelsperinch' /*case 'PixelsPerInch'*/:
			break;
		case 'componentoptions' /*case 'ComponentOptions'*/:
		case 'documentproperties' /*case 'DocumentProperties'*/:
		case 'customdocumentproperties' /*case 'CustomDocumentProperties'*/:
		case 'officedocumentsettings' /*case 'OfficeDocumentSettings'*/:
		case 'pivottable' /*case 'PivotTable'*/:
		case 'pivotcache' /*case 'PivotCache'*/:
		case 'names' /*case 'Names'*/:
		case 'mapinfo' /*case 'MapInfo'*/:
		case 'pagebreaks' /*case 'PageBreaks'*/:
		case 'querytable' /*case 'QueryTable'*/:
		case 'sorting' /*case 'Sorting'*/:
		case 'schema' /*case 'Schema'*/: //case 'data' /*case 'data'*/:
		case 'conditionalformatting' /*case 'ConditionalFormatting'*/:
		case 'smarttagtype' /*case 'SmartTagType'*/:
		case 'smarttags' /*case 'SmartTags'*/:
		case 'excelworkbook' /*case 'ExcelWorkbook'*/:
		case 'workbookoptions' /*case 'WorkbookOptions'*/:
		case 'worksheetoptions' /*case 'WorksheetOptions'*/:
			if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
			else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
			break;

		case 'null' /*case 'Null'*/: break;

		default:
			/* FODS file root is <office:document> */
			if(state.length == 0 && Rn[3] == "document") return parse_fods(str, opts);
			/* UOS file root is <uof:UOF> */
			if(state.length == 0 && Rn[3] == "uof"/*"UOF"*/) return parse_fods(str, opts);

			var seen = true;
			switch(state[state.length-1][0]) {
				/* OfficeDocumentSettings */
				case 'officedocumentsettings' /*case 'OfficeDocumentSettings'*/: switch(Rn[3]) {
					case 'allowpng' /*case 'AllowPNG'*/: break;
					case 'removepersonalinformation' /*case 'RemovePersonalInformation'*/: break;
					case 'downloadcomponents' /*case 'DownloadComponents'*/: break;
					case 'locationofcomponents' /*case 'LocationOfComponents'*/: break;
					case 'colors' /*case 'Colors'*/: break;
					case 'color' /*case 'Color'*/: break;
					case 'index' /*case 'Index'*/: break;
					case 'rgb' /*case 'RGB'*/: break;
					case 'targetscreensize' /*case 'TargetScreenSize'*/: break;
					case 'readonlyrecommended' /*case 'ReadOnlyRecommended'*/: break;
					default: seen = false;
				} break;

				/* ComponentOptions */
				case 'componentoptions' /*case 'ComponentOptions'*/: switch(Rn[3]) {
					case 'toolbar' /*case 'Toolbar'*/: break;
					case 'hideofficelogo' /*case 'HideOfficeLogo'*/: break;
					case 'spreadsheetautofit' /*case 'SpreadsheetAutoFit'*/: break;
					case 'label' /*case 'Label'*/: break;
					case 'caption' /*case 'Caption'*/: break;
					case 'maxheight' /*case 'MaxHeight'*/: break;
					case 'maxwidth' /*case 'MaxWidth'*/: break;
					case 'nextsheetnumber' /*case 'NextSheetNumber'*/: break;
					default: seen = false;
				} break;

				/* ExcelWorkbook */
				case 'excelworkbook' /*case 'ExcelWorkbook'*/: switch(Rn[3]) {
					case 'date1904' /*case 'Date1904'*/:
						/*:: if(!Workbook.WBProps) Workbook.WBProps = {}; */
						Workbook.WBProps.date1904 = true;
						break;
					case 'windowheight' /*case 'WindowHeight'*/: break;
					case 'windowwidth' /*case 'WindowWidth'*/: break;
					case 'windowtopx' /*case 'WindowTopX'*/: break;
					case 'windowtopy' /*case 'WindowTopY'*/: break;
					case 'tabratio' /*case 'TabRatio'*/: break;
					case 'protectstructure' /*case 'ProtectStructure'*/: break;
					case 'protectwindow' /*case 'ProtectWindow'*/: break;
					case 'protectwindows' /*case 'ProtectWindows'*/: break;
					case 'activesheet' /*case 'ActiveSheet'*/: break;
					case 'displayinknotes' /*case 'DisplayInkNotes'*/: break;
					case 'firstvisiblesheet' /*case 'FirstVisibleSheet'*/: break;
					case 'supbook' /*case 'SupBook'*/: break;
					case 'sheetname' /*case 'SheetName'*/: break;
					case 'sheetindex' /*case 'SheetIndex'*/: break;
					case 'sheetindexfirst' /*case 'SheetIndexFirst'*/: break;
					case 'sheetindexlast' /*case 'SheetIndexLast'*/: break;
					case 'dll' /*case 'Dll'*/: break;
					case 'acceptlabelsinformulas' /*case 'AcceptLabelsInFormulas'*/: break;
					case 'donotsavelinkvalues' /*case 'DoNotSaveLinkValues'*/: break;
					case 'iteration' /*case 'Iteration'*/: break;
					case 'maxiterations' /*case 'MaxIterations'*/: break;
					case 'maxchange' /*case 'MaxChange'*/: break;
					case 'path' /*case 'Path'*/: break;
					case 'xct' /*case 'Xct'*/: break;
					case 'count' /*case 'Count'*/: break;
					case 'selectedsheets' /*case 'SelectedSheets'*/: break;
					case 'calculation' /*case 'Calculation'*/: break;
					case 'uncalced' /*case 'Uncalced'*/: break;
					case 'startupprompt' /*case 'StartupPrompt'*/: break;
					case 'crn' /*case 'Crn'*/: break;
					case 'externname' /*case 'ExternName'*/: break;
					case 'formula' /*case 'Formula'*/: break;
					case 'colfirst' /*case 'ColFirst'*/: break;
					case 'collast' /*case 'ColLast'*/: break;
					case 'wantadvise' /*case 'WantAdvise'*/: break;
					case 'boolean' /*case 'Boolean'*/: break;
					case 'error' /*case 'Error'*/: break;
					case 'text' /*case 'Text'*/: break;
					case 'ole' /*case 'OLE'*/: break;
					case 'noautorecover' /*case 'NoAutoRecover'*/: break;
					case 'publishobjects' /*case 'PublishObjects'*/: break;
					case 'donotcalculatebeforesave' /*case 'DoNotCalculateBeforeSave'*/: break;
					case 'number' /*case 'Number'*/: break;
					case 'refmoder1c1' /*case 'RefModeR1C1'*/: break;
					case 'embedsavesmarttags' /*case 'EmbedSaveSmartTags'*/: break;
					default: seen = false;
				} break;

				/* WorkbookOptions */
				case 'workbookoptions' /*case 'WorkbookOptions'*/: switch(Rn[3]) {
					case 'owcversion' /*case 'OWCVersion'*/: break;
					case 'height' /*case 'Height'*/: break;
					case 'width' /*case 'Width'*/: break;
					default: seen = false;
				} break;

				/* WorksheetOptions */
				case 'worksheetoptions' /*case 'WorksheetOptions'*/: switch(Rn[3]) {
					case 'visible' /*case 'Visible'*/:
						if(Rn[0].slice(-2) === "/>"){/* empty */}
						else if(Rn[1]==="/") switch(str.slice(pidx, Rn.index)) {
							case "SheetHidden": wsprops.Hidden = 1; break;
							case "SheetVeryHidden": wsprops.Hidden = 2; break;
						}
						else pidx = Rn.index + Rn[0].length;
						break;
					case 'header' /*case 'Header'*/:
						if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
						if(!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet['!margins'].header = +parsexmltag(Rn[0]).Margin;
						break;
					case 'footer' /*case 'Footer'*/:
						if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
						if(!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet['!margins'].footer = +parsexmltag(Rn[0]).Margin;
						break;
					case 'pagemargins' /*case 'PageMargins'*/:
						var pagemargins = parsexmltag(Rn[0]);
						if(!cursheet['!margins']) default_margins(cursheet['!margins']={},'xlml');
						if(!isNaN(+pagemargins.Top)) cursheet['!margins'].top = +pagemargins.Top;
						if(!isNaN(+pagemargins.Left)) cursheet['!margins'].left = +pagemargins.Left;
						if(!isNaN(+pagemargins.Right)) cursheet['!margins'].right = +pagemargins.Right;
						if(!isNaN(+pagemargins.Bottom)) cursheet['!margins'].bottom = +pagemargins.Bottom;
						break;
					case 'displayrighttoleft' /*case 'DisplayRightToLeft'*/:
						if(!Workbook.Views) Workbook.Views = [];
						if(!Workbook.Views[0]) Workbook.Views[0] = {};
						Workbook.Views[0].RTL = true;
						break;

					case 'freezepanes' /*case 'FreezePanes'*/: break;
					case 'frozennosplit' /*case 'FrozenNoSplit'*/: break;

					case 'splithorizontal' /*case 'SplitHorizontal'*/:
					case 'splitvertical' /*case 'SplitVertical'*/:
						break;

					case 'donotdisplaygridlines' /*case 'DoNotDisplayGridlines'*/:
						break;

					case 'activerow' /*case 'ActiveRow'*/: break;
					case 'activecol' /*case 'ActiveCol'*/: break;
					case 'toprowbottompane' /*case 'TopRowBottomPane'*/: break;
					case 'leftcolumnrightpane' /*case 'LeftColumnRightPane'*/: break;

					case 'unsynced' /*case 'Unsynced'*/: break;
					case 'print' /*case 'Print'*/: break;
					case 'printerrors' /*case 'PrintErrors'*/: break;
					case 'panes' /*case 'Panes'*/: break;
					case 'scale' /*case 'Scale'*/: break;
					case 'pane' /*case 'Pane'*/: break;
					case 'number' /*case 'Number'*/: break;
					case 'layout' /*case 'Layout'*/: break;
					case 'pagesetup' /*case 'PageSetup'*/: break;
					case 'selected' /*case 'Selected'*/: break;
					case 'protectobjects' /*case 'ProtectObjects'*/: break;
					case 'enableselection' /*case 'EnableSelection'*/: break;
					case 'protectscenarios' /*case 'ProtectScenarios'*/: break;
					case 'validprinterinfo' /*case 'ValidPrinterInfo'*/: break;
					case 'horizontalresolution' /*case 'HorizontalResolution'*/: break;
					case 'verticalresolution' /*case 'VerticalResolution'*/: break;
					case 'numberofcopies' /*case 'NumberofCopies'*/: break;
					case 'activepane' /*case 'ActivePane'*/: break;
					case 'toprowvisible' /*case 'TopRowVisible'*/: break;
					case 'leftcolumnvisible' /*case 'LeftColumnVisible'*/: break;
					case 'fittopage' /*case 'FitToPage'*/: break;
					case 'rangeselection' /*case 'RangeSelection'*/: break;
					case 'papersizeindex' /*case 'PaperSizeIndex'*/: break;
					case 'pagelayoutzoom' /*case 'PageLayoutZoom'*/: break;
					case 'pagebreakzoom' /*case 'PageBreakZoom'*/: break;
					case 'filteron' /*case 'FilterOn'*/: break;
					case 'fitwidth' /*case 'FitWidth'*/: break;
					case 'fitheight' /*case 'FitHeight'*/: break;
					case 'commentslayout' /*case 'CommentsLayout'*/: break;
					case 'zoom' /*case 'Zoom'*/: break;
					case 'lefttoright' /*case 'LeftToRight'*/: break;
					case 'gridlines' /*case 'Gridlines'*/: break;
					case 'allowsort' /*case 'AllowSort'*/: break;
					case 'allowfilter' /*case 'AllowFilter'*/: break;
					case 'allowinsertrows' /*case 'AllowInsertRows'*/: break;
					case 'allowdeleterows' /*case 'AllowDeleteRows'*/: break;
					case 'allowinsertcols' /*case 'AllowInsertCols'*/: break;
					case 'allowdeletecols' /*case 'AllowDeleteCols'*/: break;
					case 'allowinserthyperlinks' /*case 'AllowInsertHyperlinks'*/: break;
					case 'allowformatcells' /*case 'AllowFormatCells'*/: break;
					case 'allowsizecols' /*case 'AllowSizeCols'*/: break;
					case 'allowsizerows' /*case 'AllowSizeRows'*/: break;
					case 'nosummaryrowsbelowdetail' /*case 'NoSummaryRowsBelowDetail'*/:
						if(!cursheet["!outline"]) cursheet["!outline"] = {};
						cursheet["!outline"].above = true;
						break;
					case 'tabcolorindex' /*case 'TabColorIndex'*/: break;
					case 'donotdisplayheadings' /*case 'DoNotDisplayHeadings'*/: break;
					case 'showpagelayoutzoom' /*case 'ShowPageLayoutZoom'*/: break;
					case 'nosummarycolumnsrightdetail' /*case 'NoSummaryColumnsRightDetail'*/:
						if(!cursheet["!outline"]) cursheet["!outline"] = {};
						cursheet["!outline"].left = true;
						break;
					case 'blackandwhite' /*case 'BlackAndWhite'*/: break;
					case 'donotdisplayzeros' /*case 'DoNotDisplayZeros'*/: break;
					case 'displaypagebreak' /*case 'DisplayPageBreak'*/: break;
					case 'rowcolheadings' /*case 'RowColHeadings'*/: break;
					case 'donotdisplayoutline' /*case 'DoNotDisplayOutline'*/: break;
					case 'noorientation' /*case 'NoOrientation'*/: break;
					case 'allowusepivottables' /*case 'AllowUsePivotTables'*/: break;
					case 'zeroheight' /*case 'ZeroHeight'*/: break;
					case 'viewablerange' /*case 'ViewableRange'*/: break;
					case 'selection' /*case 'Selection'*/: break;
					case 'protectcontents' /*case 'ProtectContents'*/: break;
					default: seen = false;
				} break;

				/* PivotTable */
				case 'pivottable' /*case 'PivotTable'*/: case 'pivotcache' /*case 'PivotCache'*/: switch(Rn[3]) {
					case 'immediateitemsondrop' /*case 'ImmediateItemsOnDrop'*/: break;
					case 'showpagemultipleitemlabel' /*case 'ShowPageMultipleItemLabel'*/: break;
					case 'compactrowindent' /*case 'CompactRowIndent'*/: break;
					case 'location' /*case 'Location'*/: break;
					case 'pivotfield' /*case 'PivotField'*/: break;
					case 'orientation' /*case 'Orientation'*/: break;
					case 'layoutform' /*case 'LayoutForm'*/: break;
					case 'layoutsubtotallocation' /*case 'LayoutSubtotalLocation'*/: break;
					case 'layoutcompactrow' /*case 'LayoutCompactRow'*/: break;
					case 'position' /*case 'Position'*/: break;
					case 'pivotitem' /*case 'PivotItem'*/: break;
					case 'datatype' /*case 'DataType'*/: break;
					case 'datafield' /*case 'DataField'*/: break;
					case 'sourcename' /*case 'SourceName'*/: break;
					case 'parentfield' /*case 'ParentField'*/: break;
					case 'ptlineitems' /*case 'PTLineItems'*/: break;
					case 'ptlineitem' /*case 'PTLineItem'*/: break;
					case 'countofsameitems' /*case 'CountOfSameItems'*/: break;
					case 'item' /*case 'Item'*/: break;
					case 'itemtype' /*case 'ItemType'*/: break;
					case 'ptsource' /*case 'PTSource'*/: break;
					case 'cacheindex' /*case 'CacheIndex'*/: break;
					case 'consolidationreference' /*case 'ConsolidationReference'*/: break;
					case 'filename' /*case 'FileName'*/: break;
					case 'reference' /*case 'Reference'*/: break;
					case 'nocolumngrand' /*case 'NoColumnGrand'*/: break;
					case 'norowgrand' /*case 'NoRowGrand'*/: break;
					case 'blanklineafteritems' /*case 'BlankLineAfterItems'*/: break;
					case 'hidden' /*case 'Hidden'*/: break;
					case 'subtotal' /*case 'Subtotal'*/: break;
					case 'basefield' /*case 'BaseField'*/: break;
					case 'mapchilditems' /*case 'MapChildItems'*/: break;
					case 'function' /*case 'Function'*/: break;
					case 'refreshonfileopen' /*case 'RefreshOnFileOpen'*/: break;
					case 'printsettitles' /*case 'PrintSetTitles'*/: break;
					case 'mergelabels' /*case 'MergeLabels'*/: break;
					case 'defaultversion' /*case 'DefaultVersion'*/: break;
					case 'refreshname' /*case 'RefreshName'*/: break;
					case 'refreshdate' /*case 'RefreshDate'*/: break;
					case 'refreshdatecopy' /*case 'RefreshDateCopy'*/: break;
					case 'versionlastrefresh' /*case 'VersionLastRefresh'*/: break;
					case 'versionlastupdate' /*case 'VersionLastUpdate'*/: break;
					case 'versionupdateablemin' /*case 'VersionUpdateableMin'*/: break;
					case 'versionrefreshablemin' /*case 'VersionRefreshableMin'*/: break;
					case 'calculation' /*case 'Calculation'*/: break;
					default: seen = false;
				} break;

				/* PageBreaks */
				case 'pagebreaks' /*case 'PageBreaks'*/: switch(Rn[3]) {
					case 'colbreaks' /*case 'ColBreaks'*/: break;
					case 'colbreak' /*case 'ColBreak'*/: break;
					case 'rowbreaks' /*case 'RowBreaks'*/: break;
					case 'rowbreak' /*case 'RowBreak'*/: break;
					case 'colstart' /*case 'ColStart'*/: break;
					case 'colend' /*case 'ColEnd'*/: break;
					case 'rowend' /*case 'RowEnd'*/: break;
					default: seen = false;
				} break;

				/* AutoFilter */
				case 'autofilter' /*case 'AutoFilter'*/: switch(Rn[3]) {
					case 'autofiltercolumn' /*case 'AutoFilterColumn'*/: break;
					case 'autofiltercondition' /*case 'AutoFilterCondition'*/: break;
					case 'autofilterand' /*case 'AutoFilterAnd'*/: break;
					case 'autofilteror' /*case 'AutoFilterOr'*/: break;
					default: seen = false;
				} break;

				/* QueryTable */
				case 'querytable' /*case 'QueryTable'*/: switch(Rn[3]) {
					case 'id' /*case 'Id'*/: break;
					case 'autoformatfont' /*case 'AutoFormatFont'*/: break;
					case 'autoformatpattern' /*case 'AutoFormatPattern'*/: break;
					case 'querysource' /*case 'QuerySource'*/: break;
					case 'querytype' /*case 'QueryType'*/: break;
					case 'enableredirections' /*case 'EnableRedirections'*/: break;
					case 'refreshedinxl9' /*case 'RefreshedInXl9'*/: break;
					case 'urlstring' /*case 'URLString'*/: break;
					case 'htmltables' /*case 'HTMLTables'*/: break;
					case 'connection' /*case 'Connection'*/: break;
					case 'commandtext' /*case 'CommandText'*/: break;
					case 'refreshinfo' /*case 'RefreshInfo'*/: break;
					case 'notitles' /*case 'NoTitles'*/: break;
					case 'nextid' /*case 'NextId'*/: break;
					case 'columninfo' /*case 'ColumnInfo'*/: break;
					case 'overwritecells' /*case 'OverwriteCells'*/: break;
					case 'donotpromptforfile' /*case 'DoNotPromptForFile'*/: break;
					case 'textwizardsettings' /*case 'TextWizardSettings'*/: break;
					case 'source' /*case 'Source'*/: break;
					case 'number' /*case 'Number'*/: break;
					case 'decimal' /*case 'Decimal'*/: break;
					case 'thousandseparator' /*case 'ThousandSeparator'*/: break;
					case 'trailingminusnumbers' /*case 'TrailingMinusNumbers'*/: break;
					case 'formatsettings' /*case 'FormatSettings'*/: break;
					case 'fieldtype' /*case 'FieldType'*/: break;
					case 'delimiters' /*case 'Delimiters'*/: break;
					case 'tab' /*case 'Tab'*/: break;
					case 'comma' /*case 'Comma'*/: break;
					case 'autoformatname' /*case 'AutoFormatName'*/: break;
					case 'versionlastedit' /*case 'VersionLastEdit'*/: break;
					case 'versionlastrefresh' /*case 'VersionLastRefresh'*/: break;
					default: seen = false;
				} break;

				case 'datavalidation' /*case 'DataValidation'*/:
				switch(Rn[3]) {
					case 'range' /*case 'Range'*/: break;

					case 'type' /*case 'Type'*/: break;
					case 'min' /*case 'Min'*/: break;
					case 'max' /*case 'Max'*/: break;
					case 'sort' /*case 'Sort'*/: break;
					case 'descending' /*case 'Descending'*/: break;
					case 'order' /*case 'Order'*/: break;
					case 'casesensitive' /*case 'CaseSensitive'*/: break;
					case 'value' /*case 'Value'*/: break;
					case 'errorstyle' /*case 'ErrorStyle'*/: break;
					case 'errormessage' /*case 'ErrorMessage'*/: break;
					case 'errortitle' /*case 'ErrorTitle'*/: break;
					case 'inputmessage' /*case 'InputMessage'*/: break;
					case 'inputtitle' /*case 'InputTitle'*/: break;
					case 'combohide' /*case 'ComboHide'*/: break;
					case 'inputhide' /*case 'InputHide'*/: break;
					case 'condition' /*case 'Condition'*/: break;
					case 'qualifier' /*case 'Qualifier'*/: break;
					case 'useblank' /*case 'UseBlank'*/: break;
					case 'value1' /*case 'Value1'*/: break;
					case 'value2' /*case 'Value2'*/: break;
					case 'format' /*case 'Format'*/: break;

					case 'cellrangelist' /*case 'CellRangeList'*/: break;
					default: seen = false;
				} break;

				case 'sorting' /*case 'Sorting'*/:
				case 'conditionalformatting' /*case 'ConditionalFormatting'*/:
				switch(Rn[3]) {
					case 'range' /*case 'Range'*/: break;
					case 'type' /*case 'Type'*/: break;
					case 'min' /*case 'Min'*/: break;
					case 'max' /*case 'Max'*/: break;
					case 'sort' /*case 'Sort'*/: break;
					case 'descending' /*case 'Descending'*/: break;
					case 'order' /*case 'Order'*/: break;
					case 'casesensitive' /*case 'CaseSensitive'*/: break;
					case 'value' /*case 'Value'*/: break;
					case 'errorstyle' /*case 'ErrorStyle'*/: break;
					case 'errormessage' /*case 'ErrorMessage'*/: break;
					case 'errortitle' /*case 'ErrorTitle'*/: break;
					case 'cellrangelist' /*case 'CellRangeList'*/: break;
					case 'inputmessage' /*case 'InputMessage'*/: break;
					case 'inputtitle' /*case 'InputTitle'*/: break;
					case 'combohide' /*case 'ComboHide'*/: break;
					case 'inputhide' /*case 'InputHide'*/: break;
					case 'condition' /*case 'Condition'*/: break;
					case 'qualifier' /*case 'Qualifier'*/: break;
					case 'useblank' /*case 'UseBlank'*/: break;
					case 'value1' /*case 'Value1'*/: break;
					case 'value2' /*case 'Value2'*/: break;
					case 'format' /*case 'Format'*/: break;
					default: seen = false;
				} break;

				/* MapInfo (schema) */
				case 'mapinfo' /*case 'MapInfo'*/: case 'schema' /*case 'Schema'*/: case 'data' /*case 'data'*/: switch(Rn[3]) {
					case 'map' /*case 'Map'*/: break;
					case 'entry' /*case 'Entry'*/: break;
					case 'range' /*case 'Range'*/: break;
					case 'xpath' /*case 'XPath'*/: break;
					case 'field' /*case 'Field'*/: break;
					case 'xsdtype' /*case 'XSDType'*/: break;
					case 'filteron' /*case 'FilterOn'*/: break;
					case 'aggregate' /*case 'Aggregate'*/: break;
					case 'elementtype' /*case 'ElementType'*/: break;
					case 'attributetype' /*case 'AttributeType'*/: break;
				/* These are from xsd (XML Schema Definition) */
					case 'schema' /*case 'schema'*/:
					case 'element' /*case 'element'*/:
					case 'complextype' /*case 'complexType'*/:
					case 'datatype' /*case 'datatype'*/:
					case 'all' /*case 'all'*/:
					case 'attribute' /*case 'attribute'*/:
					case 'extends' /*case 'extends'*/: break;

					case 'row' /*case 'row'*/: break;
					default: seen = false;
				} break;

				/* SmartTags (can be anything) */
				case 'smarttags' /*case 'SmartTags'*/: break;

				default: seen = false; break;
			}
			if(seen) break;
			/* CustomDocumentProperties */
			if(Rn[3].match(/!\[CDATA/)) break;
			if(!state[state.length-1][1]) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
			if(state[state.length-1][0]===/*'CustomDocumentProperties'*/'customdocumentproperties') {
				if(Rn[0].slice(-2) === "/>") break;
				else if(Rn[1]==="/") xlml_set_custprop(Custprops, raw_Rn3, cp, str.slice(pidx, Rn.index));
				else { cp = Rn; pidx = Rn.index + Rn[0].length; }
				break;
			}
			if(opts.WTF) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
	}
	var out = ({}/*:any*/);
	if(!opts.bookSheets && !opts.bookProps) out.Sheets = sheets;
	out.SheetNames = sheetnames;
	out.Workbook = Workbook;
	out.SSF = dup(table_fmt);
	out.Props = Props;
	out.Custprops = Custprops;
	return out;
}

function parse_xlml(data/*:RawBytes|string*/, opts)/*:Workbook*/ {
	fix_read_opts(opts=opts||{});
	switch(opts.type||"base64") {
		case "base64": return parse_xlml_xml(Base64_decode(data), opts);
		case "binary": case "buffer": case "file": return parse_xlml_xml(data, opts);
		case "array": return parse_xlml_xml(a2s(data), opts);
	}
	/*:: throw new Error("unsupported type " + opts.type); */
}

/* TODO */
function write_props_xlml(wb/*:Workbook*/, opts)/*:string*/ {
	var o/*:Array<string>*/ = [];
	/* DocumentProperties */
	if(wb.Props) o.push(xlml_write_docprops(wb.Props, opts));
	/* CustomDocumentProperties */
	if(wb.Custprops) o.push(xlml_write_custprops(wb.Props, wb.Custprops, opts));
	return o.join("");
}
/* TODO */
function write_wb_xlml(/*::wb, opts*/)/*:string*/ {
	/* OfficeDocumentSettings */
	/* ExcelWorkbook */
	return "";
}
/* TODO */
function write_sty_xlml(wb, opts)/*:string*/ {
	/* Styles */
	var styles/*:Array<string>*/ = ['<Style ss:ID="Default" ss:Name="Normal"><NumberFormat/></Style>'];
	opts.cellXfs.forEach(function(xf, id) {
		var payload/*:Array<string>*/ = [];
		payload.push(writextag('NumberFormat', null, {"ss:Format": escapexml(table_fmt[xf.numFmtId])}));

		var o = /*::(*/{"ss:ID": "s" + (21+id)}/*:: :any)*/;
		styles.push(writextag('Style', payload.join(""), o));
	});
	return writextag("Styles", styles.join(""));
}
function write_name_xlml(n) { return writextag("NamedRange", null, {"ss:Name": n.Name, "ss:RefersTo":"=" + a1_to_rc(n.Ref, {r:0,c:0})}); }
function write_names_xlml(wb/*::, opts*/)/*:string*/ {
	if(!((wb||{}).Workbook||{}).Names) return "";
	/*:: if(!wb || !wb.Workbook || !wb.Workbook.Names) throw new Error("unreachable"); */
	var names/*:Array<any>*/ = wb.Workbook.Names;
	var out/*:Array<string>*/ = [];
	for(var i = 0; i < names.length; ++i) {
		var n = names[i];
		if(n.Sheet != null) continue;
		if(n.Name.match(/^_xlfn\./)) continue;
		out.push(write_name_xlml(n));
	}
	return writextag("Names", out.join(""));
}
function write_ws_xlml_names(ws/*:Worksheet*/, opts, idx/*:number*/, wb/*:Workbook*/)/*:string*/ {
	if(!ws) return "";
	if(!((wb||{}).Workbook||{}).Names) return "";
	/*:: if(!wb || !wb.Workbook || !wb.Workbook.Names) throw new Error("unreachable"); */
	var names/*:Array<any>*/ = wb.Workbook.Names;
	var out/*:Array<string>*/ = [];
	for(var i = 0; i < names.length; ++i) {
		var n = names[i];
		if(n.Sheet != idx) continue;
		/*switch(n.Name) {
			case "_": continue;
		}*/
		if(n.Name.match(/^_xlfn\./)) continue;
		out.push(write_name_xlml(n));
	}
	return out.join("");
}
/* WorksheetOptions */
function write_ws_xlml_wsopts(ws/*:Worksheet*/, opts, idx/*:number*/, wb/*:Workbook*/)/*:string*/ {
	if(!ws) return "";
	var o/*:Array<string>*/ = [];
	/* NOTE: spec technically allows any order, but stick with implied order */

	/* FitToPage */
	/* DoNotDisplayColHeaders */
	/* DoNotDisplayRowHeaders */
	/* ViewableRange */
	/* Selection */
	/* GridlineColor */
	/* Name */
	/* ExcelWorksheetType */
	/* IntlMacro */
	/* Unsynced */
	/* Selected */
	/* CodeName */

	if(ws['!margins']) {
		o.push("<PageSetup>");
		if(ws['!margins'].header) o.push(writextag("Header", null, {'x:Margin':ws['!margins'].header}));
		if(ws['!margins'].footer) o.push(writextag("Footer", null, {'x:Margin':ws['!margins'].footer}));
		o.push(writextag("PageMargins", null, {
			'x:Bottom': ws['!margins'].bottom || "0.75",
			'x:Left': ws['!margins'].left || "0.7",
			'x:Right': ws['!margins'].right || "0.7",
			'x:Top': ws['!margins'].top || "0.75"
		}));
		o.push("</PageSetup>");
	}

	/* PageSetup */
	/* DisplayPageBreak */
	/* TransitionExpressionEvaluation */
	/* TransitionFormulaEntry */
	/* Print */
	/* Zoom */
	/* PageLayoutZoom */
	/* PageBreakZoom */
	/* ShowPageBreakZoom */
	/* DefaultRowHeight */
	/* DefaultColumnWidth */
	/* StandardWidth */

	if(wb && wb.Workbook && wb.Workbook.Sheets && wb.Workbook.Sheets[idx]) {
		/* Visible */
		if(wb.Workbook.Sheets[idx].Hidden) o.push(writextag("Visible", (wb.Workbook.Sheets[idx].Hidden == 1 ? "SheetHidden" : "SheetVeryHidden"), {}));
		else {
			/* Selected */
			for(var i = 0; i < idx; ++i) if(wb.Workbook.Sheets[i] && !wb.Workbook.Sheets[i].Hidden) break;
			if(i == idx) o.push("<Selected/>");
		}
	}

	/* LeftColumnVisible */

	if(((((wb||{}).Workbook||{}).Views||[])[0]||{}).RTL) o.push("<DisplayRightToLeft/>");

	/* GridlineColorIndex */
	/* DisplayFormulas */
	/* DoNotDisplayGridlines */
	/* DoNotDisplayHeadings */
	/* DoNotDisplayOutline */
	/* ApplyAutomaticOutlineStyles */
	/* NoSummaryRowsBelowDetail */
	/* NoSummaryColumnsRightDetail */
	/* DoNotDisplayZeros */
	/* ActiveRow */
	/* ActiveColumn */
	/* FilterOn */
	/* RangeSelection */
	/* TopRowVisible */
	/* TopRowBottomPane */
	/* LeftColumnRightPane */
	/* ActivePane */
	/* SplitHorizontal */
	/* SplitVertical */
	/* FreezePanes */
	/* FrozenNoSplit */
	/* TabColorIndex */
	/* Panes */

	/* NOTE: Password not supported in XLML Format */
	if(ws['!protect']) {
		o.push(writetag("ProtectContents", "True"));
		if(ws['!protect'].objects) o.push(writetag("ProtectObjects", "True"));
		if(ws['!protect'].scenarios) o.push(writetag("ProtectScenarios", "True"));
		if(ws['!protect'].selectLockedCells != null && !ws['!protect'].selectLockedCells) o.push(writetag("EnableSelection", "NoSelection"));
		else if(ws['!protect'].selectUnlockedCells != null && !ws['!protect'].selectUnlockedCells) o.push(writetag("EnableSelection", "UnlockedCells"));
	[
		[ "formatCells", "AllowFormatCells" ],
		[ "formatColumns", "AllowSizeCols" ],
		[ "formatRows", "AllowSizeRows" ],
		[ "insertColumns", "AllowInsertCols" ],
		[ "insertRows", "AllowInsertRows" ],
		[ "insertHyperlinks", "AllowInsertHyperlinks" ],
		[ "deleteColumns", "AllowDeleteCols" ],
		[ "deleteRows", "AllowDeleteRows" ],
		[ "sort", "AllowSort" ],
		[ "autoFilter", "AllowFilter" ],
		[ "pivotTables", "AllowUsePivotTables" ]
	].forEach(function(x) { if(ws['!protect'][x[0]]) o.push("<"+x[1]+"/>"); });
	}

	if(o.length == 0) return "";
	return writextag("WorksheetOptions", o.join(""), {xmlns:XLMLNS.x});
}
function write_ws_xlml_comment(comments/*:Array<any>*/)/*:string*/ {
	return comments.map(function(c) {
		// TODO: formatted text
		var t = xlml_unfixstr(c.t||"");
		var d =writextag("ss:Data", t, {"xmlns":"http://www.w3.org/TR/REC-html40"});
		return writextag("Comment", d, {"ss:Author":c.a});
	}).join("");
}
function write_ws_xlml_cell(cell, ref/*:string*/, ws, opts, idx/*:number*/, wb, addr)/*:string*/{
	if(!cell || (cell.v == undefined && cell.f == undefined)) return "";

	var attr = {};
	if(cell.f) attr["ss:Formula"] = "=" + escapexml(a1_to_rc(cell.f, addr));
	if(cell.F && cell.F.slice(0, ref.length) == ref) {
		var end = decode_cell(cell.F.slice(ref.length + 1));
		attr["ss:ArrayRange"] = "RC:R" + (end.r == addr.r ? "" : "[" + (end.r - addr.r) + "]") + "C" + (end.c == addr.c ? "" : "[" + (end.c - addr.c) + "]");
	}

	if(cell.l && cell.l.Target) {
		attr["ss:HRef"] = escapexml(cell.l.Target);
		if(cell.l.Tooltip) attr["x:HRefScreenTip"] = escapexml(cell.l.Tooltip);
	}

	if(ws['!merges']) {
		var marr = ws['!merges'];
		for(var mi = 0; mi != marr.length; ++mi) {
			if(marr[mi].s.c != addr.c || marr[mi].s.r != addr.r) continue;
			if(marr[mi].e.c > marr[mi].s.c) attr['ss:MergeAcross'] = marr[mi].e.c - marr[mi].s.c;
			if(marr[mi].e.r > marr[mi].s.r) attr['ss:MergeDown'] = marr[mi].e.r - marr[mi].s.r;
		}
	}

	var t = "", p = "";
	switch(cell.t) {
		case 'z': if(!opts.sheetStubs) return ""; break;
		case 'n': t = 'Number'; p = String(cell.v); break;
		case 'b': t = 'Boolean'; p = (cell.v ? "1" : "0"); break;
		case 'e': t = 'Error'; p = BErr[cell.v]; break;
		case 'd': t = 'DateTime'; p = new Date(cell.v).toISOString(); if(cell.z == null) cell.z = cell.z || table_fmt[14]; break;
		case 's': t = 'String'; p = escapexlml(cell.v||""); break;
	}
	/* TODO: cell style */
	var os = get_cell_style(opts.cellXfs, cell, opts);
	attr["ss:StyleID"] = "s" + (21+os);
	attr["ss:Index"] = addr.c + 1;
	var _v = (cell.v != null ? p : "");
	var m = cell.t == 'z' ? "" : ('<Data ss:Type="' + t + '">' + _v + '</Data>');

	if((cell.c||[]).length > 0) m += write_ws_xlml_comment(cell.c);

	return writextag("Cell", m, attr);
}
function write_ws_xlml_row(R/*:number*/, row)/*:string*/ {
	var o = '<Row ss:Index="' + (R+1) + '"';
	if(row) {
		if(row.hpt && !row.hpx) row.hpx = pt2px(row.hpt);
		if(row.hpx) o += ' ss:AutoFitHeight="0" ss:Height="' + row.hpx + '"';
		if(row.hidden) o += ' ss:Hidden="1"';
	}
	return o + '>';
}
/* TODO */
function write_ws_xlml_table(ws/*:Worksheet*/, opts, idx/*:number*/, wb/*:Workbook*/)/*:string*/ {
	if(!ws['!ref']) return "";
	var range/*:Range*/ = safe_decode_range(ws['!ref']);
	var marr/*:Array<Range>*/ = ws['!merges'] || [], mi = 0;
	var o/*:Array<string>*/ = [];
	if(ws['!cols']) ws['!cols'].forEach(function(n, i) {
		process_col(n);
		var w = !!n.width;
		var p = col_obj_w(i, n);
		var k/*:any*/ = {"ss:Index":i+1};
		if(w) k['ss:Width'] = width2px(p.width);
		if(n.hidden) k['ss:Hidden']="1";
		o.push(writextag("Column",null,k));
	});
	var dense = Array.isArray(ws);
	for(var R = range.s.r; R <= range.e.r; ++R) {
		var row = [write_ws_xlml_row(R, (ws['!rows']||[])[R])];
		for(var C = range.s.c; C <= range.e.c; ++C) {
			var skip = false;
			for(mi = 0; mi != marr.length; ++mi) {
				if(marr[mi].s.c > C) continue;
				if(marr[mi].s.r > R) continue;
				if(marr[mi].e.c < C) continue;
				if(marr[mi].e.r < R) continue;
				if(marr[mi].s.c != C || marr[mi].s.r != R) skip = true;
				break;
			}
			if(skip) continue;
			var addr = {r:R,c:C};
			var ref = encode_cell(addr), cell = dense ? (ws[R]||[])[C] : ws[ref];
			row.push(write_ws_xlml_cell(cell, ref, ws, opts, idx, wb, addr));
		}
		row.push("</Row>");
		if(row.length > 2) o.push(row.join(""));
	}
	return o.join("");
}
function write_ws_xlml(idx/*:number*/, opts, wb/*:Workbook*/)/*:string*/ {
	var o/*:Array<string>*/ = [];
	var s = wb.SheetNames[idx];
	var ws = wb.Sheets[s];

	var t/*:string*/ = ws ? write_ws_xlml_names(ws, opts, idx, wb) : "";
	if(t.length > 0) o.push("<Names>" + t + "</Names>");

	/* Table */
	t = ws ? write_ws_xlml_table(ws, opts, idx, wb) : "";
	if(t.length > 0) o.push("<Table>" + t + "</Table>");

	/* WorksheetOptions */
	o.push(write_ws_xlml_wsopts(ws, opts, idx, wb));

	return o.join("");
}
function write_xlml(wb, opts)/*:string*/ {
	if(!opts) opts = {};
	if(!wb.SSF) wb.SSF = dup(table_fmt);
	if(wb.SSF) {
		make_ssf(); SSF_load_table(wb.SSF);
		// $FlowIgnore
		opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
		opts.ssf = wb.SSF;
		opts.cellXfs = [];
		get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
	}
	var d/*:Array<string>*/ = [];
	d.push(write_props_xlml(wb, opts));
	d.push(write_wb_xlml(wb, opts));
	d.push("");
	d.push("");
	for(var i = 0; i < wb.SheetNames.length; ++i)
		d.push(writextag("Worksheet", write_ws_xlml(i, opts, wb), {"ss:Name":escapexml(wb.SheetNames[i])}));
	d[2] = write_sty_xlml(wb, opts);
	d[3] = write_names_xlml(wb, opts);
	return XML_HEADER + writextag("Workbook", d.join(""), {
		'xmlns':      XLMLNS.ss,
		'xmlns:o':    XLMLNS.o,
		'xmlns:x':    XLMLNS.x,
		'xmlns:ss':   XLMLNS.ss,
		'xmlns:dt':   XLMLNS.dt,
		'xmlns:html': XLMLNS.html
	});
}
/* [MS-OLEDS] 2.3.8 CompObjStream */
function parse_compobj(obj/*:CFBEntry*/) {
	var v = {};
	var o = obj.content;
	/*:: if(o == null) return; */

	/* [MS-OLEDS] 2.3.7 CompObjHeader -- All fields MUST be ignored */
	o.l = 28;

	v.AnsiUserType = o.read_shift(0, "lpstr-ansi");
	v.AnsiClipboardFormat = parse_ClipboardFormatOrAnsiString(o);

	if(o.length - o.l <= 4) return v;

	var m/*:number*/ = o.read_shift(4);
	if(m == 0 || m > 40) return v;
	o.l-=4; v.Reserved1 = o.read_shift(0, "lpstr-ansi");

	if(o.length - o.l <= 4) return v;
	m = o.read_shift(4);
	if(m !== 0x71b239f4) return v;
	v.UnicodeClipboardFormat = parse_ClipboardFormatOrUnicodeString(o);

	m = o.read_shift(4);
	if(m == 0 || m > 40) return v;
	o.l-=4; v.Reserved2 = o.read_shift(0, "lpwstr");
}

/*
	Continue logic for:
	- 2.4.58 Continue          0x003c
	- 2.4.59 ContinueBigName   0x043c
	- 2.4.60 ContinueFrt       0x0812
	- 2.4.61 ContinueFrt11     0x0875
	- 2.4.62 ContinueFrt12     0x087f
*/
var CONTINUE_RT = [ 0x003c, 0x043c, 0x0812, 0x0875, 0x087f ];
function slurp(RecordType, R, blob, length/*:number*/, opts)/*:any*/ {
	var l = length;
	var bufs = [];
	var d = blob.slice(blob.l,blob.l+l);
	if(opts && opts.enc && opts.enc.insitu && d.length > 0) switch(RecordType) {
	case 0x0009: case 0x0209: case 0x0409: case 0x0809/* BOF */: case 0x002f /* FilePass */: case 0x0195 /* FileLock */: case 0x00e1 /* InterfaceHdr */: case 0x0196 /* RRDInfo */: case 0x0138 /* RRDHead */: case 0x0194 /* UsrExcl */: case 0x000a /* EOF */:
		break;
	case 0x0085 /* BoundSheet8 */:
		break;
	default:
		opts.enc.insitu(d);
	}
	bufs.push(d);
	blob.l += l;
	var nextrt = __readUInt16LE(blob,blob.l), next = XLSRecordEnum[nextrt];
	var start = 0;
	while(next != null && CONTINUE_RT.indexOf(nextrt) > -1) {
		l = __readUInt16LE(blob,blob.l+2);
		start = blob.l + 4;
		if(nextrt == 0x0812 /* ContinueFrt */) start += 4;
		else if(nextrt == 0x0875 || nextrt == 0x087f) {
			start += 12;
		}
		d = blob.slice(start,blob.l+4+l);
		bufs.push(d);
		blob.l += 4+l;
		next = (XLSRecordEnum[nextrt = __readUInt16LE(blob, blob.l)]);
	}
	var b = (bconcat(bufs)/*:any*/);
	prep_blob(b, 0);
	var ll = 0; b.lens = [];
	for(var j = 0; j < bufs.length; ++j) { b.lens.push(ll); ll += bufs[j].length; }
	if(b.length < length) throw "XLS Record 0x" + RecordType.toString(16) + " Truncated: " + b.length + " < " + length;
	return R.f(b, b.length, opts);
}

function safe_format_xf(p/*:any*/, opts/*:ParseOpts*/, date1904/*:?boolean*/) {
	if(p.t === 'z') return;
	if(!p.XF) return;
	var fmtid = 0;
	try {
		fmtid = p.z || p.XF.numFmtId || 0;
		if(opts.cellNF) p.z = table_fmt[fmtid];
	} catch(e) { if(opts.WTF) throw e; }
	if(!opts || opts.cellText !== false) try {
		if(p.t === 'e') { p.w = p.w || BErr[p.v]; }
		else if(fmtid === 0 || fmtid == "General") {
			if(p.t === 'n') {
				if((p.v|0) === p.v) p.w = p.v.toString(10);
				else p.w = SSF_general_num(p.v);
			}
			else p.w = SSF_general(p.v);
		}
		else p.w = SSF_format(fmtid,p.v, {date1904:!!date1904, dateNF: opts && opts.dateNF});
	} catch(e) { if(opts.WTF) throw e; }
	if(opts.cellDates && fmtid && p.t == 'n' && fmt_is_date(table_fmt[fmtid] || String(fmtid))) {
		var _d = SSF_parse_date_code(p.v); if(_d) { p.t = 'd'; p.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
	}
}

function make_cell(val, ixfe, t)/*:Cell*/ {
	return ({v:val, ixfe:ixfe, t:t}/*:any*/);
}

// 2.3.2
function parse_workbook(blob, options/*:ParseOpts*/)/*:Workbook*/ {
	var wb = ({opts:{}}/*:any*/);
	var Sheets = {};
	if(DENSE != null && options.dense == null) options.dense = DENSE;
	var out/*:Worksheet*/ = ((options.dense ? [] : {})/*:any*/);
	var Directory = {};
	var range/*:Range*/ = ({}/*:any*/);
	var last_formula = null;
	var sst/*:SST*/ = ([]/*:any*/);
	var cur_sheet = "";
	var Preamble = {};
	var lastcell, last_cell = "", cc/*:Cell*/, cmnt, rngC, rngR;
	var sharedf = {};
	var arrayf/*:Array<[Range, string]>*/ = [];
	var temp_val/*:Cell*/;
	var country;
	var XFs = []; /* XF records */
	var palette/*:Array<[number, number, number]>*/ = [];
	var Workbook/*:WBWBProps*/ = ({ Sheets:[], WBProps:{date1904:false}, Views:[{}] }/*:any*/), wsprops = {};
	var get_rgb = function getrgb(icv/*:number*/)/*:[number, number, number]*/ {
		if(icv < 8) return XLSIcv[icv];
		if(icv < 64) return palette[icv-8] || XLSIcv[icv];
		return XLSIcv[icv];
	};
	var process_cell_style = function pcs(cell, line/*:any*/, options) {
		var xfd = line.XF.data;
		if(!xfd || !xfd.patternType || !options || !options.cellStyles) return;
		line.s = ({}/*:any*/);
		line.s.patternType = xfd.patternType;
		var t;
		if((t = rgb2Hex(get_rgb(xfd.icvFore)))) { line.s.fgColor = {rgb:t}; }
		if((t = rgb2Hex(get_rgb(xfd.icvBack)))) { line.s.bgColor = {rgb:t}; }
	};
	var addcell = function addcell(cell/*:any*/, line/*:any*/, options/*:any*/) {
		if(file_depth > 1) return;
		if(options.sheetRows && cell.r >= options.sheetRows) return;
		if(options.cellStyles && line.XF && line.XF.data) process_cell_style(cell, line, options);
		delete line.ixfe; delete line.XF;
		lastcell = cell;
		last_cell = encode_cell(cell);
		if(!range || !range.s || !range.e) range = {s:{r:0,c:0},e:{r:0,c:0}};
		if(cell.r < range.s.r) range.s.r = cell.r;
		if(cell.c < range.s.c) range.s.c = cell.c;
		if(cell.r + 1 > range.e.r) range.e.r = cell.r + 1;
		if(cell.c + 1 > range.e.c) range.e.c = cell.c + 1;
		if(options.cellFormula && line.f) {
			for(var afi = 0; afi < arrayf.length; ++afi) {
				if(arrayf[afi][0].s.c > cell.c || arrayf[afi][0].s.r > cell.r) continue;
				if(arrayf[afi][0].e.c < cell.c || arrayf[afi][0].e.r < cell.r) continue;
				line.F = encode_range(arrayf[afi][0]);
				if(arrayf[afi][0].s.c != cell.c || arrayf[afi][0].s.r != cell.r) delete line.f;
				if(line.f) line.f = "" + stringify_formula(arrayf[afi][1], range, cell, supbooks, opts);
				break;
			}
		}
		{
			if(options.dense) {
				if(!out[cell.r]) out[cell.r] = [];
				out[cell.r][cell.c] = line;
			} else out[last_cell] = line;
		}
	};
	var opts = ({
		enc: false, // encrypted
		sbcch: 0, // cch in the preceding SupBook
		snames: [], // sheetnames
		sharedf: sharedf, // shared formulae by address
		arrayf: arrayf, // array formulae array
		rrtabid: [], // RRTabId
		lastuser: "", // Last User from WriteAccess
		biff: 8, // BIFF version
		codepage: 0, // CP from CodePage record
		winlocked: 0, // fLockWn from WinProtect
		cellStyles: !!options && !!options.cellStyles,
		WTF: !!options && !!options.wtf
	}/*:any*/);
	if(options.password) opts.password = options.password;
	var themes;
	var merges/*:Array<Range>*/ = [];
	var objects = [];
	var colinfo/*:Array<ColInfo>*/ = [], rowinfo/*:Array<RowInfo>*/ = [];
	var seencol = false;
	var supbooks = ([]/*:any*/); // 1-indexed, will hold extern names
	supbooks.SheetNames = opts.snames;
	supbooks.sharedf = opts.sharedf;
	supbooks.arrayf = opts.arrayf;
	supbooks.names = [];
	supbooks.XTI = [];
	var last_RT = 0;
	var file_depth = 0; /* TODO: make a real stack */
	var BIFF2Fmt = 0, BIFF2FmtTable/*:Array<string>*/ = [];
	var FilterDatabases = []; /* TODO: sort out supbooks and process elsewhere */
	var last_lbl/*:?DefinedName*/;

	/* explicit override for some broken writers */
	opts.codepage = 1200;
	set_cp(1200);
	var seen_codepage = false;
	while(blob.l < blob.length - 1) {
		var s = blob.l;
		var RecordType = blob.read_shift(2);
		if(RecordType === 0 && last_RT === 0x000a /* EOF */) break;
		var length = (blob.l === blob.length ? 0 : blob.read_shift(2));
		var R = XLSRecordEnum[RecordType];
		//console.log(RecordType.toString(16), RecordType, R, blob.l, length, blob.length);
		//if(!R) console.log(blob.slice(blob.l, blob.l + length));
		if(R && R.f) {
			if(options.bookSheets) {
				if(last_RT === 0x0085 /* BoundSheet8 */ && RecordType !== 0x0085 /* R.n !== 'BoundSheet8' */) break;
			}
			last_RT = RecordType;
			if(R.r === 2 || R.r == 12) {
				var rt = blob.read_shift(2); length -= 2;
				if(!opts.enc && rt !== RecordType && (((rt&0xFF)<<8)|(rt>>8)) !== RecordType) throw new Error("rt mismatch: " + rt + "!=" + RecordType);
				if(R.r == 12){
					blob.l += 10; length -= 10;
				} // skip FRT
			}
			//console.error(R,blob.l,length,blob.length);
			var val/*:any*/ = ({}/*:any*/);
			if(RecordType === 0x000a /* EOF */) val = /*::(*/R.f(blob, length, opts)/*:: :any)*/;
			else val = /*::(*/slurp(RecordType, R, blob, length, opts)/*:: :any)*/;
			/*:: val = (val:any); */
			if(file_depth == 0 && [0x0009, 0x0209, 0x0409, 0x0809].indexOf(last_RT) === -1 /* 'BOF' */) continue;
			switch(RecordType) {
				case 0x0022 /* Date1904 */:
					/*:: if(!Workbook.WBProps) Workbook.WBProps = {}; */
					wb.opts.Date1904 = Workbook.WBProps.date1904 = val; break;
				case 0x0086 /* WriteProtect */: wb.opts.WriteProtect = true; break;
				case 0x002f /* FilePass */:
					if(!opts.enc) blob.l = 0;
					opts.enc = val;
					if(!options.password) throw new Error("File is password-protected");
					if(val.valid == null) throw new Error("Encryption scheme unsupported");
					if(!val.valid) throw new Error("Password is incorrect");
					break;
				case 0x005c /* WriteAccess */: opts.lastuser = val; break;
				case 0x0042 /* CodePage */:
					var cpval = Number(val);
					/* overrides based on test cases */
					switch(cpval) {
						case 0x5212: cpval =  1200; break;
						case 0x8000: cpval = 10000; break;
						case 0x8001: cpval =  1252; break;
					}
					set_cp(opts.codepage = cpval);
					seen_codepage = true;
					break;
				case 0x013d /* RRTabId */: opts.rrtabid = val; break;
				case 0x0019 /* WinProtect */: opts.winlocked = val; break;
				case 0x01b7 /* RefreshAll */: wb.opts["RefreshAll"] = val; break;
				case 0x000c /* CalcCount */: wb.opts["CalcCount"] = val; break;
				case 0x0010 /* CalcDelta */: wb.opts["CalcDelta"] = val; break;
				case 0x0011 /* CalcIter */: wb.opts["CalcIter"] = val; break;
				case 0x000d /* CalcMode */: wb.opts["CalcMode"] = val; break;
				case 0x000e /* CalcPrecision */: wb.opts["CalcPrecision"] = val; break;
				case 0x005f /* CalcSaveRecalc */: wb.opts["CalcSaveRecalc"] = val; break;
				case 0x000f /* CalcRefMode */: opts.CalcRefMode = val; break; // TODO: implement R1C1
				case 0x08a3 /* ForceFullCalculation */: wb.opts.FullCalc = val; break;
				case 0x0081 /* WsBool */:
					if(val.fDialog) out["!type"] = "dialog";
					if(!val.fBelow) (out["!outline"] || (out["!outline"] = {})).above = true;
					if(!val.fRight) (out["!outline"] || (out["!outline"] = {})).left = true;
					break; // TODO
				case 0x00e0 /* XF */:
					XFs.push(val); break;
				case 0x01ae /* SupBook */:
					supbooks.push([val]);
					supbooks[supbooks.length-1].XTI = [];
					break;
				case 0x0023: case 0x0223 /* ExternName */:
					supbooks[supbooks.length-1].push(val);
					break;
				case 0x0018: case 0x0218 /* Lbl */:
					last_lbl = ({
						Name: val.Name,
						Ref: stringify_formula(val.rgce,range,null,supbooks,opts)
					}/*:DefinedName*/);
					if(val.itab > 0) last_lbl.Sheet = val.itab - 1;
					supbooks.names.push(last_lbl);
					if(!supbooks[0]) { supbooks[0] = []; supbooks[0].XTI = []; }
					supbooks[supbooks.length-1].push(val);
					if(val.Name == "_xlnm._FilterDatabase" && val.itab > 0)
						if(val.rgce && val.rgce[0] && val.rgce[0][0] && val.rgce[0][0][0] == 'PtgArea3d')
							FilterDatabases[val.itab - 1] = { ref: encode_range(val.rgce[0][0][1][2]) };
					break;
				case 0x0016 /* ExternCount */: opts.ExternCount = val; break;
				case 0x0017 /* ExternSheet */:
					if(supbooks.length == 0) { supbooks[0] = []; supbooks[0].XTI = []; }
					supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val); supbooks.XTI = supbooks.XTI.concat(val); break;
				case 0x0894 /* NameCmt */:
					/* TODO: search for correct name */
					if(opts.biff < 8) break;
					if(last_lbl != null) last_lbl.Comment = val[1];
					break;
				case 0x0012 /* Protect */: out["!protect"] = val; break; /* for sheet or book */
				case 0x0013 /* Password */: if(val !== 0 && opts.WTF) console.error("Password verifier: " + val); break;
				case 0x0085 /* BoundSheet8 */: {
					Directory[val.pos] = val;
					opts.snames.push(val.name);
				} break;
				case 0x000a /* EOF */: {
					if(--file_depth) break;
					if(range.e) {
						if(range.e.r > 0 && range.e.c > 0) {
							range.e.r--; range.e.c--;
							out["!ref"] = encode_range(range);
							if(options.sheetRows && options.sheetRows <= range.e.r) {
								var tmpri = range.e.r;
								range.e.r = options.sheetRows - 1;
								out["!fullref"] = out["!ref"];
								out["!ref"] = encode_range(range);
								range.e.r = tmpri;
							}
							range.e.r++; range.e.c++;
						}
						if(merges.length > 0) out["!merges"] = merges;
						if(objects.length > 0) out["!objects"] = objects;
						if(colinfo.length > 0) out["!cols"] = colinfo;
						if(rowinfo.length > 0) out["!rows"] = rowinfo;
						Workbook.Sheets.push(wsprops);
					}
					if(cur_sheet === "") Preamble = out; else Sheets[cur_sheet] = out;
					out = ((options.dense ? [] : {})/*:any*/);
				} break;
				case 0x0009: case 0x0209: case 0x0409: case 0x0809 /* BOF */: {
					if(opts.biff === 8) opts.biff = {
						/*::[*/0x0009/*::]*/:2,
						/*::[*/0x0209/*::]*/:3,
						/*::[*/0x0409/*::]*/:4
					}[RecordType] || {
						/*::[*/0x0200/*::]*/:2,
						/*::[*/0x0300/*::]*/:3,
						/*::[*/0x0400/*::]*/:4,
						/*::[*/0x0500/*::]*/:5,
						/*::[*/0x0600/*::]*/:8,
						/*::[*/0x0002/*::]*/:2,
						/*::[*/0x0007/*::]*/:2
					}[val.BIFFVer] || 8;
					opts.biffguess = val.BIFFVer == 0;
					if(val.BIFFVer == 0 && val.dt == 0x1000) { opts.biff = 5; seen_codepage = true; set_cp(opts.codepage = 28591); }
					if(opts.biff == 8 && val.BIFFVer == 0 && val.dt == 16) opts.biff = 2;
					if(file_depth++) break;
					out = ((options.dense ? [] : {})/*:any*/);

					if(opts.biff < 8 && !seen_codepage) { seen_codepage = true; set_cp(opts.codepage = options.codepage || 1252); }

					if(opts.biff < 5 || val.BIFFVer == 0 && val.dt == 0x1000) {
						if(cur_sheet === "") cur_sheet = "Sheet1";
						range = {s:{r:0,c:0},e:{r:0,c:0}};
						/* fake BoundSheet8 */
						var fakebs8 = {pos: blob.l - length, name:cur_sheet};
						Directory[fakebs8.pos] = fakebs8;
						opts.snames.push(cur_sheet);
					}
					else cur_sheet = (Directory[s] || {name:""}).name;
					if(val.dt == 0x20) out["!type"] = "chart";
					if(val.dt == 0x40) out["!type"] = "macro";
					merges = [];
					objects = [];
					opts.arrayf = arrayf = [];
					colinfo = []; rowinfo = [];
					seencol = false;
					wsprops = {Hidden:(Directory[s]||{hs:0}).hs, name:cur_sheet };
				} break;
				case 0x0203 /* Number */: case 0x0003 /* BIFF2NUM */: case 0x0002 /* BIFF2INT */: {
					if(out["!type"] == "chart") if(options.dense ? (out[val.r]||[])[val.c]: out[encode_cell({c:val.c, r:val.r})]) ++val.c;
					temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe]||{}, v:val.val, t:'n'}/*:any*/);
					if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
					safe_format_xf(temp_val, options, wb.opts.Date1904);
					addcell({c:val.c, r:val.r}, temp_val, options);
				} break;
				case 0x0005: case 0x0205 /* BoolErr */: {
					temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.val, t:val.t}/*:any*/);
					if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
					safe_format_xf(temp_val, options, wb.opts.Date1904);
					addcell({c:val.c, r:val.r}, temp_val, options);
				} break;
				case 0x027e /* RK */: {
					temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.rknum, t:'n'}/*:any*/);
					if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
					safe_format_xf(temp_val, options, wb.opts.Date1904);
					addcell({c:val.c, r:val.r}, temp_val, options);
				} break;
				case 0x00bd /* MulRk */: {
					for(var j = val.c; j <= val.C; ++j) {
						var ixfe = val.rkrec[j-val.c][0];
						temp_val= ({ixfe:ixfe, XF:XFs[ixfe], v:val.rkrec[j-val.c][1], t:'n'}/*:any*/);
						if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
						safe_format_xf(temp_val, options, wb.opts.Date1904);
						addcell({c:j, r:val.r}, temp_val, options);
					}
				} break;
				case 0x0006: case 0x0206: case 0x0406 /* Formula */: {
					if(val.val == 'String') { last_formula = val; break; }
					temp_val = make_cell(val.val, val.cell.ixfe, val.tt);
					temp_val.XF = XFs[temp_val.ixfe];
					if(options.cellFormula) {
						var _f = val.formula;
						if(_f && _f[0] && _f[0][0] && _f[0][0][0] == 'PtgExp') {
							var _fr = _f[0][0][1][0], _fc = _f[0][0][1][1];
							var _fe = encode_cell({r:_fr, c:_fc});
							if(sharedf[_fe]) temp_val.f = ""+stringify_formula(val.formula,range,val.cell,supbooks, opts);
							else temp_val.F = ((options.dense ? (out[_fr]||[])[_fc]: out[_fe]) || {}).F;
						} else temp_val.f = ""+stringify_formula(val.formula,range,val.cell,supbooks, opts);
					}
					if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
					safe_format_xf(temp_val, options, wb.opts.Date1904);
					addcell(val.cell, temp_val, options);
					last_formula = val;
				} break;
				case 0x0007: case 0x0207 /* String */: {
					if(last_formula) { /* technically always true */
						last_formula.val = val;
						temp_val = make_cell(val, last_formula.cell.ixfe, 's');
						temp_val.XF = XFs[temp_val.ixfe];
						if(options.cellFormula) {
							temp_val.f = ""+stringify_formula(last_formula.formula, range, last_formula.cell, supbooks, opts);
						}
						if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
						safe_format_xf(temp_val, options, wb.opts.Date1904);
						addcell(last_formula.cell, temp_val, options);
						last_formula = null;
					} else throw new Error("String record expects Formula");
				} break;
				case 0x0021: case 0x0221 /* Array */: {
					arrayf.push(val);
					var _arraystart = encode_cell(val[0].s);
					cc = options.dense ? (out[val[0].s.r]||[])[val[0].s.c] : out[_arraystart];
					if(options.cellFormula && cc) {
						if(!last_formula) break; /* technically unreachable */
						if(!_arraystart || !cc) break;
						cc.f = ""+stringify_formula(val[1], range, val[0], supbooks, opts);
						cc.F = encode_range(val[0]);
					}
				} break;
				case 0x04bc /* ShrFmla */: {
					if(!options.cellFormula) break;
					if(last_cell) {
						/* TODO: capture range */
						if(!last_formula) break; /* technically unreachable */
						sharedf[encode_cell(last_formula.cell)]= val[0];
						cc = options.dense ? (out[last_formula.cell.r]||[])[last_formula.cell.c] : out[encode_cell(last_formula.cell)];
						(cc||{}).f = ""+stringify_formula(val[0], range, lastcell, supbooks, opts);
					}
				} break;
				case 0x00fd /* LabelSst */:
					temp_val=make_cell(sst[val.isst].t, val.ixfe, 's');
					if(sst[val.isst].h) temp_val.h = sst[val.isst].h;
					temp_val.XF = XFs[temp_val.ixfe];
					if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
					safe_format_xf(temp_val, options, wb.opts.Date1904);
					addcell({c:val.c, r:val.r}, temp_val, options);
					break;
				case 0x0201 /* Blank */: if(options.sheetStubs) {
					temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], t:'z'}/*:any*/);
					if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
					safe_format_xf(temp_val, options, wb.opts.Date1904);
					addcell({c:val.c, r:val.r}, temp_val, options);
				} break;
				case 0x00be /* MulBlank */: if(options.sheetStubs) {
					for(var _j = val.c; _j <= val.C; ++_j) {
						var _ixfe = val.ixfe[_j-val.c];
						temp_val= ({ixfe:_ixfe, XF:XFs[_ixfe], t:'z'}/*:any*/);
						if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
						safe_format_xf(temp_val, options, wb.opts.Date1904);
						addcell({c:_j, r:val.r}, temp_val, options);
					}
				} break;
				case 0x00d6 /* RString */:
				case 0x0204 /* Label */: case 0x0004 /* BIFF2STR */:
					temp_val=make_cell(val.val, val.ixfe, 's');
					temp_val.XF = XFs[temp_val.ixfe];
					if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
					safe_format_xf(temp_val, options, wb.opts.Date1904);
					addcell({c:val.c, r:val.r}, temp_val, options);
					break;

				case 0x0000: case 0x0200 /* Dimensions */: {
					if(file_depth === 1) range = val; /* TODO: stack */
				} break;
				case 0x00fc /* SST */: {
					sst = val;
				} break;
				case 0x041e /* Format */: { /* val = [id, fmt] */
					if(opts.biff == 4) {
						BIFF2FmtTable[BIFF2Fmt++] = val[1];
						for(var b4idx = 0; b4idx < BIFF2Fmt + 163; ++b4idx) if(table_fmt[b4idx] == val[1]) break;
						if(b4idx >= 163) SSF_load(val[1], BIFF2Fmt + 163);
					}
					else SSF_load(val[1], val[0]);
				} break;
				case 0x001e /* BIFF2FORMAT */: {
					BIFF2FmtTable[BIFF2Fmt++] = val;
					for(var b2idx = 0; b2idx < BIFF2Fmt + 163; ++b2idx) if(table_fmt[b2idx] == val) break;
					if(b2idx >= 163) SSF_load(val, BIFF2Fmt + 163);
				} break;

				case 0x00e5 /* MergeCells */: merges = merges.concat(val); break;

				case 0x005d /* Obj */: objects[val.cmo[0]] = opts.lastobj = val; break;
				case 0x01b6 /* TxO */: opts.lastobj.TxO = val; break;
				case 0x007f /* ImData */: opts.lastobj.ImData = val; break;

				case 0x01b8 /* HLink */: {
					for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR)
						for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) {
							cc = options.dense ? (out[rngR]||[])[rngC] : out[encode_cell({c:rngC,r:rngR})];
							if(cc) cc.l = val[1];
						}
				} break;
				case 0x0800 /* HLinkTooltip */: {
					for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR)
						for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) {
							cc = options.dense ? (out[rngR]||[])[rngC] : out[encode_cell({c:rngC,r:rngR})];
							if(cc && cc.l) cc.l.Tooltip = val[1];
							}
				} break;
				case 0x001c /* Note */: {
					if(opts.biff <= 5 && opts.biff >= 2) break; /* TODO: BIFF5 */
					cc = options.dense ? (out[val[0].r]||[])[val[0].c] : out[encode_cell(val[0])];
					var noteobj = objects[val[2]];
					if(!cc) {
						if(options.dense) {
							if(!out[val[0].r]) out[val[0].r] = [];
							cc = out[val[0].r][val[0].c] = ({t:"z"}/*:any*/);
						} else {
							cc = out[encode_cell(val[0])] = ({t:"z"}/*:any*/);
						}
						range.e.r = Math.max(range.e.r, val[0].r);
						range.s.r = Math.min(range.s.r, val[0].r);
						range.e.c = Math.max(range.e.c, val[0].c);
						range.s.c = Math.min(range.s.c, val[0].c);
					}
					if(!cc.c) cc.c = [];
					cmnt = {a:val[1],t:noteobj.TxO.t};
					cc.c.push(cmnt);
				} break;
				case 0x087d /* XFExt */: update_xfext(XFs[val.ixfe], val.ext); break;
				case 0x007d /* ColInfo */: {
					if(!opts.cellStyles) break;
					while(val.e >= val.s) {
						colinfo[val.e--] = { width: val.w/256, level: (val.level || 0), hidden: !!(val.flags & 1) };
						if(!seencol) { seencol = true; find_mdw_colw(val.w/256); }
						process_col(colinfo[val.e+1]);
					}
				} break;
				case 0x0208 /* Row */: {
					var rowobj = {};
					if(val.level != null) { rowinfo[val.r] = rowobj; rowobj.level = val.level; }
					if(val.hidden) { rowinfo[val.r] = rowobj; rowobj.hidden = true; }
					if(val.hpt) {
						rowinfo[val.r] = rowobj;
						rowobj.hpt = val.hpt; rowobj.hpx = pt2px(val.hpt);
					}
				} break;
				case 0x0026 /* LeftMargin */:
				case 0x0027 /* RightMargin */:
				case 0x0028 /* TopMargin */:
				case 0x0029 /* BottomMargin */:
					if(!out['!margins']) default_margins(out['!margins'] = {});
					out['!margins'][({0x26: "left", 0x27:"right", 0x28:"top", 0x29:"bottom"})[RecordType]] = val;
					break;
				case 0x00a1 /* Setup */: // TODO
					if(!out['!margins']) default_margins(out['!margins'] = {});
					out['!margins'].header = val.header;
					out['!margins'].footer = val.footer;
					break;
				case 0x023e /* Window2 */: // TODO
					// $FlowIgnore
					if(val.RTL) Workbook.Views[0].RTL = true;
					break;
				case 0x0092 /* Palette */: palette = val; break;
				case 0x0896 /* Theme */: themes = val; break;
				case 0x008c /* Country */: country = val; break;
				case 0x01ba /* CodeName */: {
					/*:: if(!Workbook.WBProps) Workbook.WBProps = {}; */
					if(!cur_sheet) Workbook.WBProps.CodeName = val || "ThisWorkbook";
					else wsprops.CodeName = val || wsprops.name;
				} break;
			}
		} else {
			if(!R) console.error("Missing Info for XLS Record 0x" + RecordType.toString(16));
			blob.l += length;
		}
	}
	wb.SheetNames=keys(Directory).sort(function(a,b) { return Number(a) - Number(b); }).map(function(x){return Directory[x].name;});
	if(!options.bookSheets) wb.Sheets=Sheets;
	if(!wb.SheetNames.length && Preamble["!ref"]) {
		wb.SheetNames.push("Sheet1");
		/*jshint -W069 */
		if(wb.Sheets) wb.Sheets["Sheet1"] = Preamble;
		/*jshint +W069 */
	} else wb.Preamble=Preamble;
	if(wb.Sheets) FilterDatabases.forEach(function(r,i) { wb.Sheets[wb.SheetNames[i]]['!autofilter'] = r; });
	wb.Strings = sst;
	wb.SSF = dup(table_fmt);
	if(opts.enc) wb.Encryption = opts.enc;
	if(themes) wb.Themes = themes;
	wb.Metadata = {};
	if(country !== undefined) wb.Metadata.Country = country;
	if(supbooks.names.length > 0) Workbook.Names = supbooks.names;
	wb.Workbook = Workbook;
	return wb;
}

/* TODO: split props*/
var PSCLSID = {
	SI: "e0859ff2f94f6810ab9108002b27b3d9",
	DSI: "02d5cdd59c2e1b10939708002b2cf9ae",
	UDI: "05d5cdd59c2e1b10939708002b2cf9ae"
};
function parse_xls_props(cfb/*:CFBContainer*/, props, o) {
	/* [MS-OSHARED] 2.3.3.2.2 Document Summary Information Property Set */
	var DSI = CFB.find(cfb, '/!DocumentSummaryInformation');
	if(DSI && DSI.size > 0) try {
		var DocSummary = parse_PropertySetStream(DSI, DocSummaryPIDDSI, PSCLSID.DSI);
		for(var d in DocSummary) props[d] = DocSummary[d];
	} catch(e) {if(o.WTF) throw e;/* empty */}

	/* [MS-OSHARED] 2.3.3.2.1 Summary Information Property Set*/
	var SI = CFB.find(cfb, '/!SummaryInformation');
	if(SI && SI.size > 0) try {
		var Summary = parse_PropertySetStream(SI, SummaryPIDSI, PSCLSID.SI);
		for(var s in Summary) if(props[s] == null) props[s] = Summary[s];
	} catch(e) {if(o.WTF) throw e;/* empty */}

	if(props.HeadingPairs && props.TitlesOfParts) {
		load_props_pairs(props.HeadingPairs, props.TitlesOfParts, props, o);
		delete props.HeadingPairs; delete props.TitlesOfParts;
	}
}
function write_xls_props(wb/*:Workbook*/, cfb/*:CFBContainer*/) {
	var DSEntries = [], SEntries = [], CEntries = [];
	var i = 0, Keys;
	var DocSummaryRE/*:{[key:string]:string}*/ = evert_key(DocSummaryPIDDSI, "n");
	var SummaryRE/*:{[key:string]:string}*/ = evert_key(SummaryPIDSI, "n");
	if(wb.Props) {
		Keys = keys(wb.Props);
		// $FlowIgnore
		for(i = 0; i < Keys.length; ++i) (Object.prototype.hasOwnProperty.call(DocSummaryRE, Keys[i]) ? DSEntries : Object.prototype.hasOwnProperty.call(SummaryRE, Keys[i]) ? SEntries : CEntries).push([Keys[i], wb.Props[Keys[i]]]);
	}
	if(wb.Custprops) {
		Keys = keys(wb.Custprops);
		// $FlowIgnore
		for(i = 0; i < Keys.length; ++i) if(!Object.prototype.hasOwnProperty.call((wb.Props||{}), Keys[i])) (Object.prototype.hasOwnProperty.call(DocSummaryRE, Keys[i]) ? DSEntries : Object.prototype.hasOwnProperty.call(SummaryRE, Keys[i]) ? SEntries : CEntries).push([Keys[i], wb.Custprops[Keys[i]]]);
	}
	var CEntries2 = [];
	for(i = 0; i < CEntries.length; ++i) {
		if(XLSPSSkip.indexOf(CEntries[i][0]) > -1 || PseudoPropsPairs.indexOf(CEntries[i][0]) > -1) continue;
		if(CEntries[i][1] == null) continue;
		CEntries2.push(CEntries[i]);
	}
	if(SEntries.length) CFB.utils.cfb_add(cfb, "/\u0005SummaryInformation", write_PropertySetStream(SEntries, PSCLSID.SI, SummaryRE, SummaryPIDSI));
	if(DSEntries.length || CEntries2.length) CFB.utils.cfb_add(cfb, "/\u0005DocumentSummaryInformation", write_PropertySetStream(DSEntries, PSCLSID.DSI, DocSummaryRE, DocSummaryPIDDSI, CEntries2.length ? CEntries2 : null, PSCLSID.UDI));
}

function parse_xlscfb(cfb/*:any*/, options/*:?ParseOpts*/)/*:Workbook*/ {
if(!options) options = {};
fix_read_opts(options);
reset_cp();
if(options.codepage) set_ansi(options.codepage);
var CompObj/*:?CFBEntry*/, WB/*:?any*/;
if(cfb.FullPaths) {
	if(CFB.find(cfb, '/encryption')) throw new Error("File is password-protected");
	CompObj = CFB.find(cfb, '!CompObj');
	WB = CFB.find(cfb, '/Workbook') || CFB.find(cfb, '/Book');
} else {
	switch(options.type) {
		case 'base64': cfb = s2a(Base64_decode(cfb)); break;
		case 'binary': cfb = s2a(cfb); break;
		case 'buffer': break;
		case 'array': if(!Array.isArray(cfb)) cfb = Array.prototype.slice.call(cfb); break;
	}
	prep_blob(cfb, 0);
	WB = ({content: cfb}/*:any*/);
}
var /*::CompObjP, */WorkbookP/*:: :Workbook = XLSX.utils.book_new(); */;

var _data/*:?any*/;
if(CompObj) /*::CompObjP = */parse_compobj(CompObj);
if(options.bookProps && !options.bookSheets) WorkbookP = ({}/*:any*/);
else/*:: if(cfb instanceof CFBContainer) */ {
	var T = has_buf ? 'buffer' : 'array';
	if(WB && WB.content) WorkbookP = parse_workbook(WB.content, options);
	/* Quattro Pro 7-8 */
	else if((_data=CFB.find(cfb, 'PerfectOffice_MAIN')) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T, options));
	/* Quattro Pro 9 */
	else if((_data=CFB.find(cfb, 'NativeContent_MAIN')) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T, options));
	/* Works 4 for Mac */
	else if((_data=CFB.find(cfb, 'MN0')) && _data.content) throw new Error("Unsupported Works 4 for Mac file");
	else throw new Error("Cannot find Workbook stream");
	if(options.bookVBA && cfb.FullPaths && CFB.find(cfb, '/_VBA_PROJECT_CUR/VBA/dir')) WorkbookP.vbaraw = make_vba_xls(cfb);
}

var props = {};
if(cfb.FullPaths) parse_xls_props(/*::((*/cfb/*:: :any):CFBContainer)*/, props, options);

WorkbookP.Props = WorkbookP.Custprops = props; /* TODO: split up properties */
if(options.bookFiles) WorkbookP.cfb = cfb;
/*WorkbookP.CompObjP = CompObjP; // TODO: storage? */
return WorkbookP;
}


function write_xlscfb(wb/*:Workbook*/, opts/*:WriteOpts*/)/*:CFBContainer*/ {
	var o = opts || {};
	var cfb = CFB.utils.cfb_new({root:"R"});
	var wbpath = "/Workbook";
	switch(o.bookType || "xls") {
		case "xls": o.bookType = "biff8";
		/* falls through */
		case "xla": if(!o.bookType) o.bookType = "xla";
		/* falls through */
		case "biff8": wbpath = "/Workbook"; o.biff = 8; break;
		case "biff5": wbpath = "/Book"; o.biff = 5; break;
		default: throw new Error("invalid type " + o.bookType + " for XLS CFB");
	}
	CFB.utils.cfb_add(cfb, wbpath, write_biff_buf(wb, o));
	if(o.biff == 8 && (wb.Props || wb.Custprops)) write_xls_props(wb, cfb);
	// TODO: SI, DSI, CO
	if(o.biff == 8 && wb.vbaraw) fill_vba_xls(cfb, CFB.read(wb.vbaraw, {type: typeof wb.vbaraw == "string" ? "binary" : "buffer"}));
	return cfb;
}
/* [MS-XLSB] 2.3 Record Enumeration */
var XLSBRecordEnum = {
	/*::[*/0x0000/*::]*/: { /* n:"BrtRowHdr", */ f:parse_BrtRowHdr },
	/*::[*/0x0001/*::]*/: { /* n:"BrtCellBlank", */ f:parse_BrtCellBlank },
	/*::[*/0x0002/*::]*/: { /* n:"BrtCellRk", */ f:parse_BrtCellRk },
	/*::[*/0x0003/*::]*/: { /* n:"BrtCellError", */ f:parse_BrtCellError },
	/*::[*/0x0004/*::]*/: { /* n:"BrtCellBool", */ f:parse_BrtCellBool },
	/*::[*/0x0005/*::]*/: { /* n:"BrtCellReal", */ f:parse_BrtCellReal },
	/*::[*/0x0006/*::]*/: { /* n:"BrtCellSt", */ f:parse_BrtCellSt },
	/*::[*/0x0007/*::]*/: { /* n:"BrtCellIsst", */ f:parse_BrtCellIsst },
	/*::[*/0x0008/*::]*/: { /* n:"BrtFmlaString", */ f:parse_BrtFmlaString },
	/*::[*/0x0009/*::]*/: { /* n:"BrtFmlaNum", */ f:parse_BrtFmlaNum },
	/*::[*/0x000A/*::]*/: { /* n:"BrtFmlaBool", */ f:parse_BrtFmlaBool },
	/*::[*/0x000B/*::]*/: { /* n:"BrtFmlaError", */ f:parse_BrtFmlaError },
	/*::[*/0x000C/*::]*/: { /* n:"BrtShortBlank", */ f:parse_BrtShortBlank },
	/*::[*/0x000D/*::]*/: { /* n:"BrtShortRk", */ f:parse_BrtShortRk },
	/*::[*/0x000E/*::]*/: { /* n:"BrtShortError", */ f:parse_BrtShortError },
	/*::[*/0x000F/*::]*/: { /* n:"BrtShortBool", */ f:parse_BrtShortBool },
	/*::[*/0x0010/*::]*/: { /* n:"BrtShortReal", */ f:parse_BrtShortReal },
	/*::[*/0x0011/*::]*/: { /* n:"BrtShortSt", */ f:parse_BrtShortSt },
	/*::[*/0x0012/*::]*/: { /* n:"BrtShortIsst", */ f:parse_BrtShortIsst },
	/*::[*/0x0013/*::]*/: { /* n:"BrtSSTItem", */ f:parse_RichStr },
	/*::[*/0x0014/*::]*/: { /* n:"BrtPCDIMissing" */ },
	/*::[*/0x0015/*::]*/: { /* n:"BrtPCDINumber" */ },
	/*::[*/0x0016/*::]*/: { /* n:"BrtPCDIBoolean" */ },
	/*::[*/0x0017/*::]*/: { /* n:"BrtPCDIError" */ },
	/*::[*/0x0018/*::]*/: { /* n:"BrtPCDIString" */ },
	/*::[*/0x0019/*::]*/: { /* n:"BrtPCDIDatetime" */ },
	/*::[*/0x001A/*::]*/: { /* n:"BrtPCDIIndex" */ },
	/*::[*/0x001B/*::]*/: { /* n:"BrtPCDIAMissing" */ },
	/*::[*/0x001C/*::]*/: { /* n:"BrtPCDIANumber" */ },
	/*::[*/0x001D/*::]*/: { /* n:"BrtPCDIABoolean" */ },
	/*::[*/0x001E/*::]*/: { /* n:"BrtPCDIAError" */ },
	/*::[*/0x001F/*::]*/: { /* n:"BrtPCDIAString" */ },
	/*::[*/0x0020/*::]*/: { /* n:"BrtPCDIADatetime" */ },
	/*::[*/0x0021/*::]*/: { /* n:"BrtPCRRecord" */ },
	/*::[*/0x0022/*::]*/: { /* n:"BrtPCRRecordDt" */ },
	/*::[*/0x0023/*::]*/: { /* n:"BrtFRTBegin", */ T:1 },
	/*::[*/0x0024/*::]*/: { /* n:"BrtFRTEnd", */ T:-1 },
	/*::[*/0x0025/*::]*/: { /* n:"BrtACBegin", */ T:1 },
	/*::[*/0x0026/*::]*/: { /* n:"BrtACEnd", */ T:-1 },
	/*::[*/0x0027/*::]*/: { /* n:"BrtName", */ f:parse_BrtName },
	/*::[*/0x0028/*::]*/: { /* n:"BrtIndexRowBlock" */ },
	/*::[*/0x002A/*::]*/: { /* n:"BrtIndexBlock" */ },
	/*::[*/0x002B/*::]*/: { /* n:"BrtFont", */ f:parse_BrtFont },
	/*::[*/0x002C/*::]*/: { /* n:"BrtFmt", */ f:parse_BrtFmt },
	/*::[*/0x002D/*::]*/: { /* n:"BrtFill", */ f:parse_BrtFill },
	/*::[*/0x002E/*::]*/: { /* n:"BrtBorder", */ f:parse_BrtBorder },
	/*::[*/0x002F/*::]*/: { /* n:"BrtXF", */ f:parse_BrtXF },
	/*::[*/0x0030/*::]*/: { /* n:"BrtStyle" */ },
	/*::[*/0x0031/*::]*/: { /* n:"BrtCellMeta", */ f:parse_Int32LE },
	/*::[*/0x0032/*::]*/: { /* n:"BrtValueMeta" */ },
	/*::[*/0x0033/*::]*/: { /* n:"BrtMdb" */ f:parse_BrtMdb },
	/*::[*/0x0034/*::]*/: { /* n:"BrtBeginFmd", */ T:1 },
	/*::[*/0x0035/*::]*/: { /* n:"BrtEndFmd", */ T:-1 },
	/*::[*/0x0036/*::]*/: { /* n:"BrtBeginMdx", */ T:1 },
	/*::[*/0x0037/*::]*/: { /* n:"BrtEndMdx", */ T:-1 },
	/*::[*/0x0038/*::]*/: { /* n:"BrtBeginMdxTuple", */ T:1 },
	/*::[*/0x0039/*::]*/: { /* n:"BrtEndMdxTuple", */ T:-1 },
	/*::[*/0x003A/*::]*/: { /* n:"BrtMdxMbrIstr" */ },
	/*::[*/0x003B/*::]*/: { /* n:"BrtStr" */ },
	/*::[*/0x003C/*::]*/: { /* n:"BrtColInfo", */ f:parse_ColInfo },
	/*::[*/0x003E/*::]*/: { /* n:"BrtCellRString", */ f:parse_BrtCellRString },
	/*::[*/0x003F/*::]*/: { /* n:"BrtCalcChainItem$", */ f:parse_BrtCalcChainItem$ },
	/*::[*/0x0040/*::]*/: { /* n:"BrtDVal", */ f:parse_BrtDVal },
	/*::[*/0x0041/*::]*/: { /* n:"BrtSxvcellNum" */ },
	/*::[*/0x0042/*::]*/: { /* n:"BrtSxvcellStr" */ },
	/*::[*/0x0043/*::]*/: { /* n:"BrtSxvcellBool" */ },
	/*::[*/0x0044/*::]*/: { /* n:"BrtSxvcellErr" */ },
	/*::[*/0x0045/*::]*/: { /* n:"BrtSxvcellDate" */ },
	/*::[*/0x0046/*::]*/: { /* n:"BrtSxvcellNil" */ },
	/*::[*/0x0080/*::]*/: { /* n:"BrtFileVersion" */ },
	/*::[*/0x0081/*::]*/: { /* n:"BrtBeginSheet", */ T:1 },
	/*::[*/0x0082/*::]*/: { /* n:"BrtEndSheet", */ T:-1 },
	/*::[*/0x0083/*::]*/: { /* n:"BrtBeginBook", */ T:1, f:parsenoop, p:0 },
	/*::[*/0x0084/*::]*/: { /* n:"BrtEndBook", */ T:-1 },
	/*::[*/0x0085/*::]*/: { /* n:"BrtBeginWsViews", */ T:1 },
	/*::[*/0x0086/*::]*/: { /* n:"BrtEndWsViews", */ T:-1 },
	/*::[*/0x0087/*::]*/: { /* n:"BrtBeginBookViews", */ T:1 },
	/*::[*/0x0088/*::]*/: { /* n:"BrtEndBookViews", */ T:-1 },
	/*::[*/0x0089/*::]*/: { /* n:"BrtBeginWsView", */ T:1, f:parse_BrtBeginWsView },
	/*::[*/0x008A/*::]*/: { /* n:"BrtEndWsView", */ T:-1 },
	/*::[*/0x008B/*::]*/: { /* n:"BrtBeginCsViews", */ T:1 },
	/*::[*/0x008C/*::]*/: { /* n:"BrtEndCsViews", */ T:-1 },
	/*::[*/0x008D/*::]*/: { /* n:"BrtBeginCsView", */ T:1 },
	/*::[*/0x008E/*::]*/: { /* n:"BrtEndCsView", */ T:-1 },
	/*::[*/0x008F/*::]*/: { /* n:"BrtBeginBundleShs", */ T:1 },
	/*::[*/0x0090/*::]*/: { /* n:"BrtEndBundleShs", */ T:-1 },
	/*::[*/0x0091/*::]*/: { /* n:"BrtBeginSheetData", */ T:1 },
	/*::[*/0x0092/*::]*/: { /* n:"BrtEndSheetData", */ T:-1 },
	/*::[*/0x0093/*::]*/: { /* n:"BrtWsProp", */ f:parse_BrtWsProp },
	/*::[*/0x0094/*::]*/: { /* n:"BrtWsDim", */ f:parse_BrtWsDim, p:16 },
	/*::[*/0x0097/*::]*/: { /* n:"BrtPane", */ f:parse_BrtPane },
	/*::[*/0x0098/*::]*/: { /* n:"BrtSel" */ },
	/*::[*/0x0099/*::]*/: { /* n:"BrtWbProp", */ f:parse_BrtWbProp },
	/*::[*/0x009A/*::]*/: { /* n:"BrtWbFactoid" */ },
	/*::[*/0x009B/*::]*/: { /* n:"BrtFileRecover" */ },
	/*::[*/0x009C/*::]*/: { /* n:"BrtBundleSh", */ f:parse_BrtBundleSh },
	/*::[*/0x009D/*::]*/: { /* n:"BrtCalcProp" */ },
	/*::[*/0x009E/*::]*/: { /* n:"BrtBookView" */ },
	/*::[*/0x009F/*::]*/: { /* n:"BrtBeginSst", */ T:1, f:parse_BrtBeginSst },
	/*::[*/0x00A0/*::]*/: { /* n:"BrtEndSst", */ T:-1 },
	/*::[*/0x00A1/*::]*/: { /* n:"BrtBeginAFilter", */ T:1, f:parse_UncheckedRfX },
	/*::[*/0x00A2/*::]*/: { /* n:"BrtEndAFilter", */ T:-1 },
	/*::[*/0x00A3/*::]*/: { /* n:"BrtBeginFilterColumn", */ T:1 },
	/*::[*/0x00A4/*::]*/: { /* n:"BrtEndFilterColumn", */ T:-1 },
	/*::[*/0x00A5/*::]*/: { /* n:"BrtBeginFilters", */ T:1 },
	/*::[*/0x00A6/*::]*/: { /* n:"BrtEndFilters", */ T:-1 },
	/*::[*/0x00A7/*::]*/: { /* n:"BrtFilter" */ },
	/*::[*/0x00A8/*::]*/: { /* n:"BrtColorFilter" */ },
	/*::[*/0x00A9/*::]*/: { /* n:"BrtIconFilter" */ },
	/*::[*/0x00AA/*::]*/: { /* n:"BrtTop10Filter" */ },
	/*::[*/0x00AB/*::]*/: { /* n:"BrtDynamicFilter" */ },
	/*::[*/0x00AC/*::]*/: { /* n:"BrtBeginCustomFilters", */ T:1 },
	/*::[*/0x00AD/*::]*/: { /* n:"BrtEndCustomFilters", */ T:-1 },
	/*::[*/0x00AE/*::]*/: { /* n:"BrtCustomFilter" */ },
	/*::[*/0x00AF/*::]*/: { /* n:"BrtAFilterDateGroupItem" */ },
	/*::[*/0x00B0/*::]*/: { /* n:"BrtMergeCell", */ f:parse_BrtMergeCell },
	/*::[*/0x00B1/*::]*/: { /* n:"BrtBeginMergeCells", */ T:1 },
	/*::[*/0x00B2/*::]*/: { /* n:"BrtEndMergeCells", */ T:-1 },
	/*::[*/0x00B3/*::]*/: { /* n:"BrtBeginPivotCacheDef", */ T:1 },
	/*::[*/0x00B4/*::]*/: { /* n:"BrtEndPivotCacheDef", */ T:-1 },
	/*::[*/0x00B5/*::]*/: { /* n:"BrtBeginPCDFields", */ T:1 },
	/*::[*/0x00B6/*::]*/: { /* n:"BrtEndPCDFields", */ T:-1 },
	/*::[*/0x00B7/*::]*/: { /* n:"BrtBeginPCDField", */ T:1 },
	/*::[*/0x00B8/*::]*/: { /* n:"BrtEndPCDField", */ T:-1 },
	/*::[*/0x00B9/*::]*/: { /* n:"BrtBeginPCDSource", */ T:1 },
	/*::[*/0x00BA/*::]*/: { /* n:"BrtEndPCDSource", */ T:-1 },
	/*::[*/0x00BB/*::]*/: { /* n:"BrtBeginPCDSRange", */ T:1 },
	/*::[*/0x00BC/*::]*/: { /* n:"BrtEndPCDSRange", */ T:-1 },
	/*::[*/0x00BD/*::]*/: { /* n:"BrtBeginPCDFAtbl", */ T:1 },
	/*::[*/0x00BE/*::]*/: { /* n:"BrtEndPCDFAtbl", */ T:-1 },
	/*::[*/0x00BF/*::]*/: { /* n:"BrtBeginPCDIRun", */ T:1 },
	/*::[*/0x00C0/*::]*/: { /* n:"BrtEndPCDIRun", */ T:-1 },
	/*::[*/0x00C1/*::]*/: { /* n:"BrtBeginPivotCacheRecords", */ T:1 },
	/*::[*/0x00C2/*::]*/: { /* n:"BrtEndPivotCacheRecords", */ T:-1 },
	/*::[*/0x00C3/*::]*/: { /* n:"BrtBeginPCDHierarchies", */ T:1 },
	/*::[*/0x00C4/*::]*/: { /* n:"BrtEndPCDHierarchies", */ T:-1 },
	/*::[*/0x00C5/*::]*/: { /* n:"BrtBeginPCDHierarchy", */ T:1 },
	/*::[*/0x00C6/*::]*/: { /* n:"BrtEndPCDHierarchy", */ T:-1 },
	/*::[*/0x00C7/*::]*/: { /* n:"BrtBeginPCDHFieldsUsage", */ T:1 },
	/*::[*/0x00C8/*::]*/: { /* n:"BrtEndPCDHFieldsUsage", */ T:-1 },
	/*::[*/0x00C9/*::]*/: { /* n:"BrtBeginExtConnection", */ T:1 },
	/*::[*/0x00CA/*::]*/: { /* n:"BrtEndExtConnection", */ T:-1 },
	/*::[*/0x00CB/*::]*/: { /* n:"BrtBeginECDbProps", */ T:1 },
	/*::[*/0x00CC/*::]*/: { /* n:"BrtEndECDbProps", */ T:-1 },
	/*::[*/0x00CD/*::]*/: { /* n:"BrtBeginECOlapProps", */ T:1 },
	/*::[*/0x00CE/*::]*/: { /* n:"BrtEndECOlapProps", */ T:-1 },
	/*::[*/0x00CF/*::]*/: { /* n:"BrtBeginPCDSConsol", */ T:1 },
	/*::[*/0x00D0/*::]*/: { /* n:"BrtEndPCDSConsol", */ T:-1 },
	/*::[*/0x00D1/*::]*/: { /* n:"BrtBeginPCDSCPages", */ T:1 },
	/*::[*/0x00D2/*::]*/: { /* n:"BrtEndPCDSCPages", */ T:-1 },
	/*::[*/0x00D3/*::]*/: { /* n:"BrtBeginPCDSCPage", */ T:1 },
	/*::[*/0x00D4/*::]*/: { /* n:"BrtEndPCDSCPage", */ T:-1 },
	/*::[*/0x00D5/*::]*/: { /* n:"BrtBeginPCDSCPItem", */ T:1 },
	/*::[*/0x00D6/*::]*/: { /* n:"BrtEndPCDSCPItem", */ T:-1 },
	/*::[*/0x00D7/*::]*/: { /* n:"BrtBeginPCDSCSets", */ T:1 },
	/*::[*/0x00D8/*::]*/: { /* n:"BrtEndPCDSCSets", */ T:-1 },
	/*::[*/0x00D9/*::]*/: { /* n:"BrtBeginPCDSCSet", */ T:1 },
	/*::[*/0x00DA/*::]*/: { /* n:"BrtEndPCDSCSet", */ T:-1 },
	/*::[*/0x00DB/*::]*/: { /* n:"BrtBeginPCDFGroup", */ T:1 },
	/*::[*/0x00DC/*::]*/: { /* n:"BrtEndPCDFGroup", */ T:-1 },
	/*::[*/0x00DD/*::]*/: { /* n:"BrtBeginPCDFGItems", */ T:1 },
	/*::[*/0x00DE/*::]*/: { /* n:"BrtEndPCDFGItems", */ T:-1 },
	/*::[*/0x00DF/*::]*/: { /* n:"BrtBeginPCDFGRange", */ T:1 },
	/*::[*/0x00E0/*::]*/: { /* n:"BrtEndPCDFGRange", */ T:-1 },
	/*::[*/0x00E1/*::]*/: { /* n:"BrtBeginPCDFGDiscrete", */ T:1 },
	/*::[*/0x00E2/*::]*/: { /* n:"BrtEndPCDFGDiscrete", */ T:-1 },
	/*::[*/0x00E3/*::]*/: { /* n:"BrtBeginPCDSDTupleCache", */ T:1 },
	/*::[*/0x00E4/*::]*/: { /* n:"BrtEndPCDSDTupleCache", */ T:-1 },
	/*::[*/0x00E5/*::]*/: { /* n:"BrtBeginPCDSDTCEntries", */ T:1 },
	/*::[*/0x00E6/*::]*/: { /* n:"BrtEndPCDSDTCEntries", */ T:-1 },
	/*::[*/0x00E7/*::]*/: { /* n:"BrtBeginPCDSDTCEMembers", */ T:1 },
	/*::[*/0x00E8/*::]*/: { /* n:"BrtEndPCDSDTCEMembers", */ T:-1 },
	/*::[*/0x00E9/*::]*/: { /* n:"BrtBeginPCDSDTCEMember", */ T:1 },
	/*::[*/0x00EA/*::]*/: { /* n:"BrtEndPCDSDTCEMember", */ T:-1 },
	/*::[*/0x00EB/*::]*/: { /* n:"BrtBeginPCDSDTCQueries", */ T:1 },
	/*::[*/0x00EC/*::]*/: { /* n:"BrtEndPCDSDTCQueries", */ T:-1 },
	/*::[*/0x00ED/*::]*/: { /* n:"BrtBeginPCDSDTCQuery", */ T:1 },
	/*::[*/0x00EE/*::]*/: { /* n:"BrtEndPCDSDTCQuery", */ T:-1 },
	/*::[*/0x00EF/*::]*/: { /* n:"BrtBeginPCDSDTCSets", */ T:1 },
	/*::[*/0x00F0/*::]*/: { /* n:"BrtEndPCDSDTCSets", */ T:-1 },
	/*::[*/0x00F1/*::]*/: { /* n:"BrtBeginPCDSDTCSet", */ T:1 },
	/*::[*/0x00F2/*::]*/: { /* n:"BrtEndPCDSDTCSet", */ T:-1 },
	/*::[*/0x00F3/*::]*/: { /* n:"BrtBeginPCDCalcItems", */ T:1 },
	/*::[*/0x00F4/*::]*/: { /* n:"BrtEndPCDCalcItems", */ T:-1 },
	/*::[*/0x00F5/*::]*/: { /* n:"BrtBeginPCDCalcItem", */ T:1 },
	/*::[*/0x00F6/*::]*/: { /* n:"BrtEndPCDCalcItem", */ T:-1 },
	/*::[*/0x00F7/*::]*/: { /* n:"BrtBeginPRule", */ T:1 },
	/*::[*/0x00F8/*::]*/: { /* n:"BrtEndPRule", */ T:-1 },
	/*::[*/0x00F9/*::]*/: { /* n:"BrtBeginPRFilters", */ T:1 },
	/*::[*/0x00FA/*::]*/: { /* n:"BrtEndPRFilters", */ T:-1 },
	/*::[*/0x00FB/*::]*/: { /* n:"BrtBeginPRFilter", */ T:1 },
	/*::[*/0x00FC/*::]*/: { /* n:"BrtEndPRFilter", */ T:-1 },
	/*::[*/0x00FD/*::]*/: { /* n:"BrtBeginPNames", */ T:1 },
	/*::[*/0x00FE/*::]*/: { /* n:"BrtEndPNames", */ T:-1 },
	/*::[*/0x00FF/*::]*/: { /* n:"BrtBeginPName", */ T:1 },
	/*::[*/0x0100/*::]*/: { /* n:"BrtEndPName", */ T:-1 },
	/*::[*/0x0101/*::]*/: { /* n:"BrtBeginPNPairs", */ T:1 },
	/*::[*/0x0102/*::]*/: { /* n:"BrtEndPNPairs", */ T:-1 },
	/*::[*/0x0103/*::]*/: { /* n:"BrtBeginPNPair", */ T:1 },
	/*::[*/0x0104/*::]*/: { /* n:"BrtEndPNPair", */ T:-1 },
	/*::[*/0x0105/*::]*/: { /* n:"BrtBeginECWebProps", */ T:1 },
	/*::[*/0x0106/*::]*/: { /* n:"BrtEndECWebProps", */ T:-1 },
	/*::[*/0x0107/*::]*/: { /* n:"BrtBeginEcWpTables", */ T:1 },
	/*::[*/0x0108/*::]*/: { /* n:"BrtEndECWPTables", */ T:-1 },
	/*::[*/0x0109/*::]*/: { /* n:"BrtBeginECParams", */ T:1 },
	/*::[*/0x010A/*::]*/: { /* n:"BrtEndECParams", */ T:-1 },
	/*::[*/0x010B/*::]*/: { /* n:"BrtBeginECParam", */ T:1 },
	/*::[*/0x010C/*::]*/: { /* n:"BrtEndECParam", */ T:-1 },
	/*::[*/0x010D/*::]*/: { /* n:"BrtBeginPCDKPIs", */ T:1 },
	/*::[*/0x010E/*::]*/: { /* n:"BrtEndPCDKPIs", */ T:-1 },
	/*::[*/0x010F/*::]*/: { /* n:"BrtBeginPCDKPI", */ T:1 },
	/*::[*/0x0110/*::]*/: { /* n:"BrtEndPCDKPI", */ T:-1 },
	/*::[*/0x0111/*::]*/: { /* n:"BrtBeginDims", */ T:1 },
	/*::[*/0x0112/*::]*/: { /* n:"BrtEndDims", */ T:-1 },
	/*::[*/0x0113/*::]*/: { /* n:"BrtBeginDim", */ T:1 },
	/*::[*/0x0114/*::]*/: { /* n:"BrtEndDim", */ T:-1 },
	/*::[*/0x0115/*::]*/: { /* n:"BrtIndexPartEnd" */ },
	/*::[*/0x0116/*::]*/: { /* n:"BrtBeginStyleSheet", */ T:1 },
	/*::[*/0x0117/*::]*/: { /* n:"BrtEndStyleSheet", */ T:-1 },
	/*::[*/0x0118/*::]*/: { /* n:"BrtBeginSXView", */ T:1 },
	/*::[*/0x0119/*::]*/: { /* n:"BrtEndSXVI", */ T:-1 },
	/*::[*/0x011A/*::]*/: { /* n:"BrtBeginSXVI", */ T:1 },
	/*::[*/0x011B/*::]*/: { /* n:"BrtBeginSXVIs", */ T:1 },
	/*::[*/0x011C/*::]*/: { /* n:"BrtEndSXVIs", */ T:-1 },
	/*::[*/0x011D/*::]*/: { /* n:"BrtBeginSXVD", */ T:1 },
	/*::[*/0x011E/*::]*/: { /* n:"BrtEndSXVD", */ T:-1 },
	/*::[*/0x011F/*::]*/: { /* n:"BrtBeginSXVDs", */ T:1 },
	/*::[*/0x0120/*::]*/: { /* n:"BrtEndSXVDs", */ T:-1 },
	/*::[*/0x0121/*::]*/: { /* n:"BrtBeginSXPI", */ T:1 },
	/*::[*/0x0122/*::]*/: { /* n:"BrtEndSXPI", */ T:-1 },
	/*::[*/0x0123/*::]*/: { /* n:"BrtBeginSXPIs", */ T:1 },
	/*::[*/0x0124/*::]*/: { /* n:"BrtEndSXPIs", */ T:-1 },
	/*::[*/0x0125/*::]*/: { /* n:"BrtBeginSXDI", */ T:1 },
	/*::[*/0x0126/*::]*/: { /* n:"BrtEndSXDI", */ T:-1 },
	/*::[*/0x0127/*::]*/: { /* n:"BrtBeginSXDIs", */ T:1 },
	/*::[*/0x0128/*::]*/: { /* n:"BrtEndSXDIs", */ T:-1 },
	/*::[*/0x0129/*::]*/: { /* n:"BrtBeginSXLI", */ T:1 },
	/*::[*/0x012A/*::]*/: { /* n:"BrtEndSXLI", */ T:-1 },
	/*::[*/0x012B/*::]*/: { /* n:"BrtBeginSXLIRws", */ T:1 },
	/*::[*/0x012C/*::]*/: { /* n:"BrtEndSXLIRws", */ T:-1 },
	/*::[*/0x012D/*::]*/: { /* n:"BrtBeginSXLICols", */ T:1 },
	/*::[*/0x012E/*::]*/: { /* n:"BrtEndSXLICols", */ T:-1 },
	/*::[*/0x012F/*::]*/: { /* n:"BrtBeginSXFormat", */ T:1 },
	/*::[*/0x0130/*::]*/: { /* n:"BrtEndSXFormat", */ T:-1 },
	/*::[*/0x0131/*::]*/: { /* n:"BrtBeginSXFormats", */ T:1 },
	/*::[*/0x0132/*::]*/: { /* n:"BrtEndSxFormats", */ T:-1 },
	/*::[*/0x0133/*::]*/: { /* n:"BrtBeginSxSelect", */ T:1 },
	/*::[*/0x0134/*::]*/: { /* n:"BrtEndSxSelect", */ T:-1 },
	/*::[*/0x0135/*::]*/: { /* n:"BrtBeginISXVDRws", */ T:1 },
	/*::[*/0x0136/*::]*/: { /* n:"BrtEndISXVDRws", */ T:-1 },
	/*::[*/0x0137/*::]*/: { /* n:"BrtBeginISXVDCols", */ T:1 },
	/*::[*/0x0138/*::]*/: { /* n:"BrtEndISXVDCols", */ T:-1 },
	/*::[*/0x0139/*::]*/: { /* n:"BrtEndSXLocation", */ T:-1 },
	/*::[*/0x013A/*::]*/: { /* n:"BrtBeginSXLocation", */ T:1 },
	/*::[*/0x013B/*::]*/: { /* n:"BrtEndSXView", */ T:-1 },
	/*::[*/0x013C/*::]*/: { /* n:"BrtBeginSXTHs", */ T:1 },
	/*::[*/0x013D/*::]*/: { /* n:"BrtEndSXTHs", */ T:-1 },
	/*::[*/0x013E/*::]*/: { /* n:"BrtBeginSXTH", */ T:1 },
	/*::[*/0x013F/*::]*/: { /* n:"BrtEndSXTH", */ T:-1 },
	/*::[*/0x0140/*::]*/: { /* n:"BrtBeginISXTHRws", */ T:1 },
	/*::[*/0x0141/*::]*/: { /* n:"BrtEndISXTHRws", */ T:-1 },
	/*::[*/0x0142/*::]*/: { /* n:"BrtBeginISXTHCols", */ T:1 },
	/*::[*/0x0143/*::]*/: { /* n:"BrtEndISXTHCols", */ T:-1 },
	/*::[*/0x0144/*::]*/: { /* n:"BrtBeginSXTDMPS", */ T:1 },
	/*::[*/0x0145/*::]*/: { /* n:"BrtEndSXTDMPs", */ T:-1 },
	/*::[*/0x0146/*::]*/: { /* n:"BrtBeginSXTDMP", */ T:1 },
	/*::[*/0x0147/*::]*/: { /* n:"BrtEndSXTDMP", */ T:-1 },
	/*::[*/0x0148/*::]*/: { /* n:"BrtBeginSXTHItems", */ T:1 },
	/*::[*/0x0149/*::]*/: { /* n:"BrtEndSXTHItems", */ T:-1 },
	/*::[*/0x014A/*::]*/: { /* n:"BrtBeginSXTHItem", */ T:1 },
	/*::[*/0x014B/*::]*/: { /* n:"BrtEndSXTHItem", */ T:-1 },
	/*::[*/0x014C/*::]*/: { /* n:"BrtBeginMetadata", */ T:1 },
	/*::[*/0x014D/*::]*/: { /* n:"BrtEndMetadata", */ T:-1 },
	/*::[*/0x014E/*::]*/: { /* n:"BrtBeginEsmdtinfo", */ T:1 },
	/*::[*/0x014F/*::]*/: { /* n:"BrtMdtinfo", */ f:parse_BrtMdtinfo },
	/*::[*/0x0150/*::]*/: { /* n:"BrtEndEsmdtinfo", */ T:-1 },
	/*::[*/0x0151/*::]*/: { /* n:"BrtBeginEsmdb", */ f:parse_BrtBeginEsmdb, T:1 },
	/*::[*/0x0152/*::]*/: { /* n:"BrtEndEsmdb", */ T:-1 },
	/*::[*/0x0153/*::]*/: { /* n:"BrtBeginEsfmd", */ T:1 },
	/*::[*/0x0154/*::]*/: { /* n:"BrtEndEsfmd", */ T:-1 },
	/*::[*/0x0155/*::]*/: { /* n:"BrtBeginSingleCells", */ T:1 },
	/*::[*/0x0156/*::]*/: { /* n:"BrtEndSingleCells", */ T:-1 },
	/*::[*/0x0157/*::]*/: { /* n:"BrtBeginList", */ T:1 },
	/*::[*/0x0158/*::]*/: { /* n:"BrtEndList", */ T:-1 },
	/*::[*/0x0159/*::]*/: { /* n:"BrtBeginListCols", */ T:1 },
	/*::[*/0x015A/*::]*/: { /* n:"BrtEndListCols", */ T:-1 },
	/*::[*/0x015B/*::]*/: { /* n:"BrtBeginListCol", */ T:1 },
	/*::[*/0x015C/*::]*/: { /* n:"BrtEndListCol", */ T:-1 },
	/*::[*/0x015D/*::]*/: { /* n:"BrtBeginListXmlCPr", */ T:1 },
	/*::[*/0x015E/*::]*/: { /* n:"BrtEndListXmlCPr", */ T:-1 },
	/*::[*/0x015F/*::]*/: { /* n:"BrtListCCFmla" */ },
	/*::[*/0x0160/*::]*/: { /* n:"BrtListTrFmla" */ },
	/*::[*/0x0161/*::]*/: { /* n:"BrtBeginExternals", */ T:1 },
	/*::[*/0x0162/*::]*/: { /* n:"BrtEndExternals", */ T:-1 },
	/*::[*/0x0163/*::]*/: { /* n:"BrtSupBookSrc", */ f:parse_RelID},
	/*::[*/0x0165/*::]*/: { /* n:"BrtSupSelf" */ },
	/*::[*/0x0166/*::]*/: { /* n:"BrtSupSame" */ },
	/*::[*/0x0167/*::]*/: { /* n:"BrtSupTabs" */ },
	/*::[*/0x0168/*::]*/: { /* n:"BrtBeginSupBook", */ T:1 },
	/*::[*/0x0169/*::]*/: { /* n:"BrtPlaceholderName" */ },
	/*::[*/0x016A/*::]*/: { /* n:"BrtExternSheet", */ f:parse_ExternSheet },
	/*::[*/0x016B/*::]*/: { /* n:"BrtExternTableStart" */ },
	/*::[*/0x016C/*::]*/: { /* n:"BrtExternTableEnd" */ },
	/*::[*/0x016E/*::]*/: { /* n:"BrtExternRowHdr" */ },
	/*::[*/0x016F/*::]*/: { /* n:"BrtExternCellBlank" */ },
	/*::[*/0x0170/*::]*/: { /* n:"BrtExternCellReal" */ },
	/*::[*/0x0171/*::]*/: { /* n:"BrtExternCellBool" */ },
	/*::[*/0x0172/*::]*/: { /* n:"BrtExternCellError" */ },
	/*::[*/0x0173/*::]*/: { /* n:"BrtExternCellString" */ },
	/*::[*/0x0174/*::]*/: { /* n:"BrtBeginEsmdx", */ T:1 },
	/*::[*/0x0175/*::]*/: { /* n:"BrtEndEsmdx", */ T:-1 },
	/*::[*/0x0176/*::]*/: { /* n:"BrtBeginMdxSet", */ T:1 },
	/*::[*/0x0177/*::]*/: { /* n:"BrtEndMdxSet", */ T:-1 },
	/*::[*/0x0178/*::]*/: { /* n:"BrtBeginMdxMbrProp", */ T:1 },
	/*::[*/0x0179/*::]*/: { /* n:"BrtEndMdxMbrProp", */ T:-1 },
	/*::[*/0x017A/*::]*/: { /* n:"BrtBeginMdxKPI", */ T:1 },
	/*::[*/0x017B/*::]*/: { /* n:"BrtEndMdxKPI", */ T:-1 },
	/*::[*/0x017C/*::]*/: { /* n:"BrtBeginEsstr", */ T:1 },
	/*::[*/0x017D/*::]*/: { /* n:"BrtEndEsstr", */ T:-1 },
	/*::[*/0x017E/*::]*/: { /* n:"BrtBeginPRFItem", */ T:1 },
	/*::[*/0x017F/*::]*/: { /* n:"BrtEndPRFItem", */ T:-1 },
	/*::[*/0x0180/*::]*/: { /* n:"BrtBeginPivotCacheIDs", */ T:1 },
	/*::[*/0x0181/*::]*/: { /* n:"BrtEndPivotCacheIDs", */ T:-1 },
	/*::[*/0x0182/*::]*/: { /* n:"BrtBeginPivotCacheID", */ T:1 },
	/*::[*/0x0183/*::]*/: { /* n:"BrtEndPivotCacheID", */ T:-1 },
	/*::[*/0x0184/*::]*/: { /* n:"BrtBeginISXVIs", */ T:1 },
	/*::[*/0x0185/*::]*/: { /* n:"BrtEndISXVIs", */ T:-1 },
	/*::[*/0x0186/*::]*/: { /* n:"BrtBeginColInfos", */ T:1 },
	/*::[*/0x0187/*::]*/: { /* n:"BrtEndColInfos", */ T:-1 },
	/*::[*/0x0188/*::]*/: { /* n:"BrtBeginRwBrk", */ T:1 },
	/*::[*/0x0189/*::]*/: { /* n:"BrtEndRwBrk", */ T:-1 },
	/*::[*/0x018A/*::]*/: { /* n:"BrtBeginColBrk", */ T:1 },
	/*::[*/0x018B/*::]*/: { /* n:"BrtEndColBrk", */ T:-1 },
	/*::[*/0x018C/*::]*/: { /* n:"BrtBrk" */ },
	/*::[*/0x018D/*::]*/: { /* n:"BrtUserBookView" */ },
	/*::[*/0x018E/*::]*/: { /* n:"BrtInfo" */ },
	/*::[*/0x018F/*::]*/: { /* n:"BrtCUsr" */ },
	/*::[*/0x0190/*::]*/: { /* n:"BrtUsr" */ },
	/*::[*/0x0191/*::]*/: { /* n:"BrtBeginUsers", */ T:1 },
	/*::[*/0x0193/*::]*/: { /* n:"BrtEOF" */ },
	/*::[*/0x0194/*::]*/: { /* n:"BrtUCR" */ },
	/*::[*/0x0195/*::]*/: { /* n:"BrtRRInsDel" */ },
	/*::[*/0x0196/*::]*/: { /* n:"BrtRREndInsDel" */ },
	/*::[*/0x0197/*::]*/: { /* n:"BrtRRMove" */ },
	/*::[*/0x0198/*::]*/: { /* n:"BrtRREndMove" */ },
	/*::[*/0x0199/*::]*/: { /* n:"BrtRRChgCell" */ },
	/*::[*/0x019A/*::]*/: { /* n:"BrtRREndChgCell" */ },
	/*::[*/0x019B/*::]*/: { /* n:"BrtRRHeader" */ },
	/*::[*/0x019C/*::]*/: { /* n:"BrtRRUserView" */ },
	/*::[*/0x019D/*::]*/: { /* n:"BrtRRRenSheet" */ },
	/*::[*/0x019E/*::]*/: { /* n:"BrtRRInsertSh" */ },
	/*::[*/0x019F/*::]*/: { /* n:"BrtRRDefName" */ },
	/*::[*/0x01A0/*::]*/: { /* n:"BrtRRNote" */ },
	/*::[*/0x01A1/*::]*/: { /* n:"BrtRRConflict" */ },
	/*::[*/0x01A2/*::]*/: { /* n:"BrtRRTQSIF" */ },
	/*::[*/0x01A3/*::]*/: { /* n:"BrtRRFormat" */ },
	/*::[*/0x01A4/*::]*/: { /* n:"BrtRREndFormat" */ },
	/*::[*/0x01A5/*::]*/: { /* n:"BrtRRAutoFmt" */ },
	/*::[*/0x01A6/*::]*/: { /* n:"BrtBeginUserShViews", */ T:1 },
	/*::[*/0x01A7/*::]*/: { /* n:"BrtBeginUserShView", */ T:1 },
	/*::[*/0x01A8/*::]*/: { /* n:"BrtEndUserShView", */ T:-1 },
	/*::[*/0x01A9/*::]*/: { /* n:"BrtEndUserShViews", */ T:-1 },
	/*::[*/0x01AA/*::]*/: { /* n:"BrtArrFmla", */ f:parse_BrtArrFmla },
	/*::[*/0x01AB/*::]*/: { /* n:"BrtShrFmla", */ f:parse_BrtShrFmla },
	/*::[*/0x01AC/*::]*/: { /* n:"BrtTable" */ },
	/*::[*/0x01AD/*::]*/: { /* n:"BrtBeginExtConnections", */ T:1 },
	/*::[*/0x01AE/*::]*/: { /* n:"BrtEndExtConnections", */ T:-1 },
	/*::[*/0x01AF/*::]*/: { /* n:"BrtBeginPCDCalcMems", */ T:1 },
	/*::[*/0x01B0/*::]*/: { /* n:"BrtEndPCDCalcMems", */ T:-1 },
	/*::[*/0x01B1/*::]*/: { /* n:"BrtBeginPCDCalcMem", */ T:1 },
	/*::[*/0x01B2/*::]*/: { /* n:"BrtEndPCDCalcMem", */ T:-1 },
	/*::[*/0x01B3/*::]*/: { /* n:"BrtBeginPCDHGLevels", */ T:1 },
	/*::[*/0x01B4/*::]*/: { /* n:"BrtEndPCDHGLevels", */ T:-1 },
	/*::[*/0x01B5/*::]*/: { /* n:"BrtBeginPCDHGLevel", */ T:1 },
	/*::[*/0x01B6/*::]*/: { /* n:"BrtEndPCDHGLevel", */ T:-1 },
	/*::[*/0x01B7/*::]*/: { /* n:"BrtBeginPCDHGLGroups", */ T:1 },
	/*::[*/0x01B8/*::]*/: { /* n:"BrtEndPCDHGLGroups", */ T:-1 },
	/*::[*/0x01B9/*::]*/: { /* n:"BrtBeginPCDHGLGroup", */ T:1 },
	/*::[*/0x01BA/*::]*/: { /* n:"BrtEndPCDHGLGroup", */ T:-1 },
	/*::[*/0x01BB/*::]*/: { /* n:"BrtBeginPCDHGLGMembers", */ T:1 },
	/*::[*/0x01BC/*::]*/: { /* n:"BrtEndPCDHGLGMembers", */ T:-1 },
	/*::[*/0x01BD/*::]*/: { /* n:"BrtBeginPCDHGLGMember", */ T:1 },
	/*::[*/0x01BE/*::]*/: { /* n:"BrtEndPCDHGLGMember", */ T:-1 },
	/*::[*/0x01BF/*::]*/: { /* n:"BrtBeginQSI", */ T:1 },
	/*::[*/0x01C0/*::]*/: { /* n:"BrtEndQSI", */ T:-1 },
	/*::[*/0x01C1/*::]*/: { /* n:"BrtBeginQSIR", */ T:1 },
	/*::[*/0x01C2/*::]*/: { /* n:"BrtEndQSIR", */ T:-1 },
	/*::[*/0x01C3/*::]*/: { /* n:"BrtBeginDeletedNames", */ T:1 },
	/*::[*/0x01C4/*::]*/: { /* n:"BrtEndDeletedNames", */ T:-1 },
	/*::[*/0x01C5/*::]*/: { /* n:"BrtBeginDeletedName", */ T:1 },
	/*::[*/0x01C6/*::]*/: { /* n:"BrtEndDeletedName", */ T:-1 },
	/*::[*/0x01C7/*::]*/: { /* n:"BrtBeginQSIFs", */ T:1 },
	/*::[*/0x01C8/*::]*/: { /* n:"BrtEndQSIFs", */ T:-1 },
	/*::[*/0x01C9/*::]*/: { /* n:"BrtBeginQSIF", */ T:1 },
	/*::[*/0x01CA/*::]*/: { /* n:"BrtEndQSIF", */ T:-1 },
	/*::[*/0x01CB/*::]*/: { /* n:"BrtBeginAutoSortScope", */ T:1 },
	/*::[*/0x01CC/*::]*/: { /* n:"BrtEndAutoSortScope", */ T:-1 },
	/*::[*/0x01CD/*::]*/: { /* n:"BrtBeginConditionalFormatting", */ T:1 },
	/*::[*/0x01CE/*::]*/: { /* n:"BrtEndConditionalFormatting", */ T:-1 },
	/*::[*/0x01CF/*::]*/: { /* n:"BrtBeginCFRule", */ T:1 },
	/*::[*/0x01D0/*::]*/: { /* n:"BrtEndCFRule", */ T:-1 },
	/*::[*/0x01D1/*::]*/: { /* n:"BrtBeginIconSet", */ T:1 },
	/*::[*/0x01D2/*::]*/: { /* n:"BrtEndIconSet", */ T:-1 },
	/*::[*/0x01D3/*::]*/: { /* n:"BrtBeginDatabar", */ T:1 },
	/*::[*/0x01D4/*::]*/: { /* n:"BrtEndDatabar", */ T:-1 },
	/*::[*/0x01D5/*::]*/: { /* n:"BrtBeginColorScale", */ T:1 },
	/*::[*/0x01D6/*::]*/: { /* n:"BrtEndColorScale", */ T:-1 },
	/*::[*/0x01D7/*::]*/: { /* n:"BrtCFVO" */ },
	/*::[*/0x01D8/*::]*/: { /* n:"BrtExternValueMeta" */ },
	/*::[*/0x01D9/*::]*/: { /* n:"BrtBeginColorPalette", */ T:1 },
	/*::[*/0x01DA/*::]*/: { /* n:"BrtEndColorPalette", */ T:-1 },
	/*::[*/0x01DB/*::]*/: { /* n:"BrtIndexedColor" */ },
	/*::[*/0x01DC/*::]*/: { /* n:"BrtMargins", */ f:parse_BrtMargins },
	/*::[*/0x01DD/*::]*/: { /* n:"BrtPrintOptions" */ },
	/*::[*/0x01DE/*::]*/: { /* n:"BrtPageSetup" */ },
	/*::[*/0x01DF/*::]*/: { /* n:"BrtBeginHeaderFooter", */ T:1 },
	/*::[*/0x01E0/*::]*/: { /* n:"BrtEndHeaderFooter", */ T:-1 },
	/*::[*/0x01E1/*::]*/: { /* n:"BrtBeginSXCrtFormat", */ T:1 },
	/*::[*/0x01E2/*::]*/: { /* n:"BrtEndSXCrtFormat", */ T:-1 },
	/*::[*/0x01E3/*::]*/: { /* n:"BrtBeginSXCrtFormats", */ T:1 },
	/*::[*/0x01E4/*::]*/: { /* n:"BrtEndSXCrtFormats", */ T:-1 },
	/*::[*/0x01E5/*::]*/: { /* n:"BrtWsFmtInfo", */ f:parse_BrtWsFmtInfo },
	/*::[*/0x01E6/*::]*/: { /* n:"BrtBeginMgs", */ T:1 },
	/*::[*/0x01E7/*::]*/: { /* n:"BrtEndMGs", */ T:-1 },
	/*::[*/0x01E8/*::]*/: { /* n:"BrtBeginMGMaps", */ T:1 },
	/*::[*/0x01E9/*::]*/: { /* n:"BrtEndMGMaps", */ T:-1 },
	/*::[*/0x01EA/*::]*/: { /* n:"BrtBeginMG", */ T:1 },
	/*::[*/0x01EB/*::]*/: { /* n:"BrtEndMG", */ T:-1 },
	/*::[*/0x01EC/*::]*/: { /* n:"BrtBeginMap", */ T:1 },
	/*::[*/0x01ED/*::]*/: { /* n:"BrtEndMap", */ T:-1 },
	/*::[*/0x01EE/*::]*/: { /* n:"BrtHLink", */ f:parse_BrtHLink },
	/*::[*/0x01EF/*::]*/: { /* n:"BrtBeginDCon", */ T:1 },
	/*::[*/0x01F0/*::]*/: { /* n:"BrtEndDCon", */ T:-1 },
	/*::[*/0x01F1/*::]*/: { /* n:"BrtBeginDRefs", */ T:1 },
	/*::[*/0x01F2/*::]*/: { /* n:"BrtEndDRefs", */ T:-1 },
	/*::[*/0x01F3/*::]*/: { /* n:"BrtDRef" */ },
	/*::[*/0x01F4/*::]*/: { /* n:"BrtBeginScenMan", */ T:1 },
	/*::[*/0x01F5/*::]*/: { /* n:"BrtEndScenMan", */ T:-1 },
	/*::[*/0x01F6/*::]*/: { /* n:"BrtBeginSct", */ T:1 },
	/*::[*/0x01F7/*::]*/: { /* n:"BrtEndSct", */ T:-1 },
	/*::[*/0x01F8/*::]*/: { /* n:"BrtSlc" */ },
	/*::[*/0x01F9/*::]*/: { /* n:"BrtBeginDXFs", */ T:1 },
	/*::[*/0x01FA/*::]*/: { /* n:"BrtEndDXFs", */ T:-1 },
	/*::[*/0x01FB/*::]*/: { /* n:"BrtDXF" */ },
	/*::[*/0x01FC/*::]*/: { /* n:"BrtBeginTableStyles", */ T:1 },
	/*::[*/0x01FD/*::]*/: { /* n:"BrtEndTableStyles", */ T:-1 },
	/*::[*/0x01FE/*::]*/: { /* n:"BrtBeginTableStyle", */ T:1 },
	/*::[*/0x01FF/*::]*/: { /* n:"BrtEndTableStyle", */ T:-1 },
	/*::[*/0x0200/*::]*/: { /* n:"BrtTableStyleElement" */ },
	/*::[*/0x0201/*::]*/: { /* n:"BrtTableStyleClient" */ },
	/*::[*/0x0202/*::]*/: { /* n:"BrtBeginVolDeps", */ T:1 },
	/*::[*/0x0203/*::]*/: { /* n:"BrtEndVolDeps", */ T:-1 },
	/*::[*/0x0204/*::]*/: { /* n:"BrtBeginVolType", */ T:1 },
	/*::[*/0x0205/*::]*/: { /* n:"BrtEndVolType", */ T:-1 },
	/*::[*/0x0206/*::]*/: { /* n:"BrtBeginVolMain", */ T:1 },
	/*::[*/0x0207/*::]*/: { /* n:"BrtEndVolMain", */ T:-1 },
	/*::[*/0x0208/*::]*/: { /* n:"BrtBeginVolTopic", */ T:1 },
	/*::[*/0x0209/*::]*/: { /* n:"BrtEndVolTopic", */ T:-1 },
	/*::[*/0x020A/*::]*/: { /* n:"BrtVolSubtopic" */ },
	/*::[*/0x020B/*::]*/: { /* n:"BrtVolRef" */ },
	/*::[*/0x020C/*::]*/: { /* n:"BrtVolNum" */ },
	/*::[*/0x020D/*::]*/: { /* n:"BrtVolErr" */ },
	/*::[*/0x020E/*::]*/: { /* n:"BrtVolStr" */ },
	/*::[*/0x020F/*::]*/: { /* n:"BrtVolBool" */ },
	/*::[*/0x0210/*::]*/: { /* n:"BrtBeginCalcChain$", */ T:1 },
	/*::[*/0x0211/*::]*/: { /* n:"BrtEndCalcChain$", */ T:-1 },
	/*::[*/0x0212/*::]*/: { /* n:"BrtBeginSortState", */ T:1 },
	/*::[*/0x0213/*::]*/: { /* n:"BrtEndSortState", */ T:-1 },
	/*::[*/0x0214/*::]*/: { /* n:"BrtBeginSortCond", */ T:1 },
	/*::[*/0x0215/*::]*/: { /* n:"BrtEndSortCond", */ T:-1 },
	/*::[*/0x0216/*::]*/: { /* n:"BrtBookProtection" */ },
	/*::[*/0x0217/*::]*/: { /* n:"BrtSheetProtection" */ },
	/*::[*/0x0218/*::]*/: { /* n:"BrtRangeProtection" */ },
	/*::[*/0x0219/*::]*/: { /* n:"BrtPhoneticInfo" */ },
	/*::[*/0x021A/*::]*/: { /* n:"BrtBeginECTxtWiz", */ T:1 },
	/*::[*/0x021B/*::]*/: { /* n:"BrtEndECTxtWiz", */ T:-1 },
	/*::[*/0x021C/*::]*/: { /* n:"BrtBeginECTWFldInfoLst", */ T:1 },
	/*::[*/0x021D/*::]*/: { /* n:"BrtEndECTWFldInfoLst", */ T:-1 },
	/*::[*/0x021E/*::]*/: { /* n:"BrtBeginECTwFldInfo", */ T:1 },
	/*::[*/0x0224/*::]*/: { /* n:"BrtFileSharing" */ },
	/*::[*/0x0225/*::]*/: { /* n:"BrtOleSize" */ },
	/*::[*/0x0226/*::]*/: { /* n:"BrtDrawing", */ f:parse_RelID },
	/*::[*/0x0227/*::]*/: { /* n:"BrtLegacyDrawing" */ },
	/*::[*/0x0228/*::]*/: { /* n:"BrtLegacyDrawingHF" */ },
	/*::[*/0x0229/*::]*/: { /* n:"BrtWebOpt" */ },
	/*::[*/0x022A/*::]*/: { /* n:"BrtBeginWebPubItems", */ T:1 },
	/*::[*/0x022B/*::]*/: { /* n:"BrtEndWebPubItems", */ T:-1 },
	/*::[*/0x022C/*::]*/: { /* n:"BrtBeginWebPubItem", */ T:1 },
	/*::[*/0x022D/*::]*/: { /* n:"BrtEndWebPubItem", */ T:-1 },
	/*::[*/0x022E/*::]*/: { /* n:"BrtBeginSXCondFmt", */ T:1 },
	/*::[*/0x022F/*::]*/: { /* n:"BrtEndSXCondFmt", */ T:-1 },
	/*::[*/0x0230/*::]*/: { /* n:"BrtBeginSXCondFmts", */ T:1 },
	/*::[*/0x0231/*::]*/: { /* n:"BrtEndSXCondFmts", */ T:-1 },
	/*::[*/0x0232/*::]*/: { /* n:"BrtBkHim" */ },
	/*::[*/0x0234/*::]*/: { /* n:"BrtColor" */ },
	/*::[*/0x0235/*::]*/: { /* n:"BrtBeginIndexedColors", */ T:1 },
	/*::[*/0x0236/*::]*/: { /* n:"BrtEndIndexedColors", */ T:-1 },
	/*::[*/0x0239/*::]*/: { /* n:"BrtBeginMRUColors", */ T:1 },
	/*::[*/0x023A/*::]*/: { /* n:"BrtEndMRUColors", */ T:-1 },
	/*::[*/0x023C/*::]*/: { /* n:"BrtMRUColor" */ },
	/*::[*/0x023D/*::]*/: { /* n:"BrtBeginDVals", */ T:1 },
	/*::[*/0x023E/*::]*/: { /* n:"BrtEndDVals", */ T:-1 },
	/*::[*/0x0241/*::]*/: { /* n:"BrtSupNameStart" */ },
	/*::[*/0x0242/*::]*/: { /* n:"BrtSupNameValueStart" */ },
	/*::[*/0x0243/*::]*/: { /* n:"BrtSupNameValueEnd" */ },
	/*::[*/0x0244/*::]*/: { /* n:"BrtSupNameNum" */ },
	/*::[*/0x0245/*::]*/: { /* n:"BrtSupNameErr" */ },
	/*::[*/0x0246/*::]*/: { /* n:"BrtSupNameSt" */ },
	/*::[*/0x0247/*::]*/: { /* n:"BrtSupNameNil" */ },
	/*::[*/0x0248/*::]*/: { /* n:"BrtSupNameBool" */ },
	/*::[*/0x0249/*::]*/: { /* n:"BrtSupNameFmla" */ },
	/*::[*/0x024A/*::]*/: { /* n:"BrtSupNameBits" */ },
	/*::[*/0x024B/*::]*/: { /* n:"BrtSupNameEnd" */ },
	/*::[*/0x024C/*::]*/: { /* n:"BrtEndSupBook", */ T:-1 },
	/*::[*/0x024D/*::]*/: { /* n:"BrtCellSmartTagProperty" */ },
	/*::[*/0x024E/*::]*/: { /* n:"BrtBeginCellSmartTag", */ T:1 },
	/*::[*/0x024F/*::]*/: { /* n:"BrtEndCellSmartTag", */ T:-1 },
	/*::[*/0x0250/*::]*/: { /* n:"BrtBeginCellSmartTags", */ T:1 },
	/*::[*/0x0251/*::]*/: { /* n:"BrtEndCellSmartTags", */ T:-1 },
	/*::[*/0x0252/*::]*/: { /* n:"BrtBeginSmartTags", */ T:1 },
	/*::[*/0x0253/*::]*/: { /* n:"BrtEndSmartTags", */ T:-1 },
	/*::[*/0x0254/*::]*/: { /* n:"BrtSmartTagType" */ },
	/*::[*/0x0255/*::]*/: { /* n:"BrtBeginSmartTagTypes", */ T:1 },
	/*::[*/0x0256/*::]*/: { /* n:"BrtEndSmartTagTypes", */ T:-1 },
	/*::[*/0x0257/*::]*/: { /* n:"BrtBeginSXFilters", */ T:1 },
	/*::[*/0x0258/*::]*/: { /* n:"BrtEndSXFilters", */ T:-1 },
	/*::[*/0x0259/*::]*/: { /* n:"BrtBeginSXFILTER", */ T:1 },
	/*::[*/0x025A/*::]*/: { /* n:"BrtEndSXFilter", */ T:-1 },
	/*::[*/0x025B/*::]*/: { /* n:"BrtBeginFills", */ T:1 },
	/*::[*/0x025C/*::]*/: { /* n:"BrtEndFills", */ T:-1 },
	/*::[*/0x025D/*::]*/: { /* n:"BrtBeginCellWatches", */ T:1 },
	/*::[*/0x025E/*::]*/: { /* n:"BrtEndCellWatches", */ T:-1 },
	/*::[*/0x025F/*::]*/: { /* n:"BrtCellWatch" */ },
	/*::[*/0x0260/*::]*/: { /* n:"BrtBeginCRErrs", */ T:1 },
	/*::[*/0x0261/*::]*/: { /* n:"BrtEndCRErrs", */ T:-1 },
	/*::[*/0x0262/*::]*/: { /* n:"BrtCrashRecErr" */ },
	/*::[*/0x0263/*::]*/: { /* n:"BrtBeginFonts", */ T:1 },
	/*::[*/0x0264/*::]*/: { /* n:"BrtEndFonts", */ T:-1 },
	/*::[*/0x0265/*::]*/: { /* n:"BrtBeginBorders", */ T:1 },
	/*::[*/0x0266/*::]*/: { /* n:"BrtEndBorders", */ T:-1 },
	/*::[*/0x0267/*::]*/: { /* n:"BrtBeginFmts", */ T:1 },
	/*::[*/0x0268/*::]*/: { /* n:"BrtEndFmts", */ T:-1 },
	/*::[*/0x0269/*::]*/: { /* n:"BrtBeginCellXFs", */ T:1 },
	/*::[*/0x026A/*::]*/: { /* n:"BrtEndCellXFs", */ T:-1 },
	/*::[*/0x026B/*::]*/: { /* n:"BrtBeginStyles", */ T:1 },
	/*::[*/0x026C/*::]*/: { /* n:"BrtEndStyles", */ T:-1 },
	/*::[*/0x0271/*::]*/: { /* n:"BrtBigName" */ },
	/*::[*/0x0272/*::]*/: { /* n:"BrtBeginCellStyleXFs", */ T:1 },
	/*::[*/0x0273/*::]*/: { /* n:"BrtEndCellStyleXFs", */ T:-1 },
	/*::[*/0x0274/*::]*/: { /* n:"BrtBeginComments", */ T:1 },
	/*::[*/0x0275/*::]*/: { /* n:"BrtEndComments", */ T:-1 },
	/*::[*/0x0276/*::]*/: { /* n:"BrtBeginCommentAuthors", */ T:1 },
	/*::[*/0x0277/*::]*/: { /* n:"BrtEndCommentAuthors", */ T:-1 },
	/*::[*/0x0278/*::]*/: { /* n:"BrtCommentAuthor", */ f:parse_BrtCommentAuthor },
	/*::[*/0x0279/*::]*/: { /* n:"BrtBeginCommentList", */ T:1 },
	/*::[*/0x027A/*::]*/: { /* n:"BrtEndCommentList", */ T:-1 },
	/*::[*/0x027B/*::]*/: { /* n:"BrtBeginComment", */ T:1, f:parse_BrtBeginComment},
	/*::[*/0x027C/*::]*/: { /* n:"BrtEndComment", */ T:-1 },
	/*::[*/0x027D/*::]*/: { /* n:"BrtCommentText", */ f:parse_BrtCommentText },
	/*::[*/0x027E/*::]*/: { /* n:"BrtBeginOleObjects", */ T:1 },
	/*::[*/0x027F/*::]*/: { /* n:"BrtOleObject" */ },
	/*::[*/0x0280/*::]*/: { /* n:"BrtEndOleObjects", */ T:-1 },
	/*::[*/0x0281/*::]*/: { /* n:"BrtBeginSxrules", */ T:1 },
	/*::[*/0x0282/*::]*/: { /* n:"BrtEndSxRules", */ T:-1 },
	/*::[*/0x0283/*::]*/: { /* n:"BrtBeginActiveXControls", */ T:1 },
	/*::[*/0x0284/*::]*/: { /* n:"BrtActiveX" */ },
	/*::[*/0x0285/*::]*/: { /* n:"BrtEndActiveXControls", */ T:-1 },
	/*::[*/0x0286/*::]*/: { /* n:"BrtBeginPCDSDTCEMembersSortBy", */ T:1 },
	/*::[*/0x0288/*::]*/: { /* n:"BrtBeginCellIgnoreECs", */ T:1 },
	/*::[*/0x0289/*::]*/: { /* n:"BrtCellIgnoreEC" */ },
	/*::[*/0x028A/*::]*/: { /* n:"BrtEndCellIgnoreECs", */ T:-1 },
	/*::[*/0x028B/*::]*/: { /* n:"BrtCsProp", */ f:parse_BrtCsProp },
	/*::[*/0x028C/*::]*/: { /* n:"BrtCsPageSetup" */ },
	/*::[*/0x028D/*::]*/: { /* n:"BrtBeginUserCsViews", */ T:1 },
	/*::[*/0x028E/*::]*/: { /* n:"BrtEndUserCsViews", */ T:-1 },
	/*::[*/0x028F/*::]*/: { /* n:"BrtBeginUserCsView", */ T:1 },
	/*::[*/0x0290/*::]*/: { /* n:"BrtEndUserCsView", */ T:-1 },
	/*::[*/0x0291/*::]*/: { /* n:"BrtBeginPcdSFCIEntries", */ T:1 },
	/*::[*/0x0292/*::]*/: { /* n:"BrtEndPCDSFCIEntries", */ T:-1 },
	/*::[*/0x0293/*::]*/: { /* n:"BrtPCDSFCIEntry" */ },
	/*::[*/0x0294/*::]*/: { /* n:"BrtBeginListParts", */ T:1 },
	/*::[*/0x0295/*::]*/: { /* n:"BrtListPart" */ },
	/*::[*/0x0296/*::]*/: { /* n:"BrtEndListParts", */ T:-1 },
	/*::[*/0x0297/*::]*/: { /* n:"BrtSheetCalcProp" */ },
	/*::[*/0x0298/*::]*/: { /* n:"BrtBeginFnGroup", */ T:1 },
	/*::[*/0x0299/*::]*/: { /* n:"BrtFnGroup" */ },
	/*::[*/0x029A/*::]*/: { /* n:"BrtEndFnGroup", */ T:-1 },
	/*::[*/0x029B/*::]*/: { /* n:"BrtSupAddin" */ },
	/*::[*/0x029C/*::]*/: { /* n:"BrtSXTDMPOrder" */ },
	/*::[*/0x029D/*::]*/: { /* n:"BrtCsProtection" */ },
	/*::[*/0x029F/*::]*/: { /* n:"BrtBeginWsSortMap", */ T:1 },
	/*::[*/0x02A0/*::]*/: { /* n:"BrtEndWsSortMap", */ T:-1 },
	/*::[*/0x02A1/*::]*/: { /* n:"BrtBeginRRSort", */ T:1 },
	/*::[*/0x02A2/*::]*/: { /* n:"BrtEndRRSort", */ T:-1 },
	/*::[*/0x02A3/*::]*/: { /* n:"BrtRRSortItem" */ },
	/*::[*/0x02A4/*::]*/: { /* n:"BrtFileSharingIso" */ },
	/*::[*/0x02A5/*::]*/: { /* n:"BrtBookProtectionIso" */ },
	/*::[*/0x02A6/*::]*/: { /* n:"BrtSheetProtectionIso" */ },
	/*::[*/0x02A7/*::]*/: { /* n:"BrtCsProtectionIso" */ },
	/*::[*/0x02A8/*::]*/: { /* n:"BrtRangeProtectionIso" */ },
	/*::[*/0x02A9/*::]*/: { /* n:"BrtDValList" */ },
	/*::[*/0x0400/*::]*/: { /* n:"BrtRwDescent" */ },
	/*::[*/0x0401/*::]*/: { /* n:"BrtKnownFonts" */ },
	/*::[*/0x0402/*::]*/: { /* n:"BrtBeginSXTupleSet", */ T:1 },
	/*::[*/0x0403/*::]*/: { /* n:"BrtEndSXTupleSet", */ T:-1 },
	/*::[*/0x0404/*::]*/: { /* n:"BrtBeginSXTupleSetHeader", */ T:1 },
	/*::[*/0x0405/*::]*/: { /* n:"BrtEndSXTupleSetHeader", */ T:-1 },
	/*::[*/0x0406/*::]*/: { /* n:"BrtSXTupleSetHeaderItem" */ },
	/*::[*/0x0407/*::]*/: { /* n:"BrtBeginSXTupleSetData", */ T:1 },
	/*::[*/0x0408/*::]*/: { /* n:"BrtEndSXTupleSetData", */ T:-1 },
	/*::[*/0x0409/*::]*/: { /* n:"BrtBeginSXTupleSetRow", */ T:1 },
	/*::[*/0x040A/*::]*/: { /* n:"BrtEndSXTupleSetRow", */ T:-1 },
	/*::[*/0x040B/*::]*/: { /* n:"BrtSXTupleSetRowItem" */ },
	/*::[*/0x040C/*::]*/: { /* n:"BrtNameExt" */ },
	/*::[*/0x040D/*::]*/: { /* n:"BrtPCDH14" */ },
	/*::[*/0x040E/*::]*/: { /* n:"BrtBeginPCDCalcMem14", */ T:1 },
	/*::[*/0x040F/*::]*/: { /* n:"BrtEndPCDCalcMem14", */ T:-1 },
	/*::[*/0x0410/*::]*/: { /* n:"BrtSXTH14" */ },
	/*::[*/0x0411/*::]*/: { /* n:"BrtBeginSparklineGroup", */ T:1 },
	/*::[*/0x0412/*::]*/: { /* n:"BrtEndSparklineGroup", */ T:-1 },
	/*::[*/0x0413/*::]*/: { /* n:"BrtSparkline" */ },
	/*::[*/0x0414/*::]*/: { /* n:"BrtSXDI14" */ },
	/*::[*/0x0415/*::]*/: { /* n:"BrtWsFmtInfoEx14" */ },
	/*::[*/0x0416/*::]*/: { /* n:"BrtBeginConditionalFormatting14", */ T:1 },
	/*::[*/0x0417/*::]*/: { /* n:"BrtEndConditionalFormatting14", */ T:-1 },
	/*::[*/0x0418/*::]*/: { /* n:"BrtBeginCFRule14", */ T:1 },
	/*::[*/0x0419/*::]*/: { /* n:"BrtEndCFRule14", */ T:-1 },
	/*::[*/0x041A/*::]*/: { /* n:"BrtCFVO14" */ },
	/*::[*/0x041B/*::]*/: { /* n:"BrtBeginDatabar14", */ T:1 },
	/*::[*/0x041C/*::]*/: { /* n:"BrtBeginIconSet14", */ T:1 },
	/*::[*/0x041D/*::]*/: { /* n:"BrtDVal14", */ f: parse_BrtDVal14 },
	/*::[*/0x041E/*::]*/: { /* n:"BrtBeginDVals14", */ T:1 },
	/*::[*/0x041F/*::]*/: { /* n:"BrtColor14" */ },
	/*::[*/0x0420/*::]*/: { /* n:"BrtBeginSparklines", */ T:1 },
	/*::[*/0x0421/*::]*/: { /* n:"BrtEndSparklines", */ T:-1 },
	/*::[*/0x0422/*::]*/: { /* n:"BrtBeginSparklineGroups", */ T:1 },
	/*::[*/0x0423/*::]*/: { /* n:"BrtEndSparklineGroups", */ T:-1 },
	/*::[*/0x0425/*::]*/: { /* n:"BrtSXVD14" */ },
	/*::[*/0x0426/*::]*/: { /* n:"BrtBeginSXView14", */ T:1 },
	/*::[*/0x0427/*::]*/: { /* n:"BrtEndSXView14", */ T:-1 },
	/*::[*/0x0428/*::]*/: { /* n:"BrtBeginSXView16", */ T:1 },
	/*::[*/0x0429/*::]*/: { /* n:"BrtEndSXView16", */ T:-1 },
	/*::[*/0x042A/*::]*/: { /* n:"BrtBeginPCD14", */ T:1 },
	/*::[*/0x042B/*::]*/: { /* n:"BrtEndPCD14", */ T:-1 },
	/*::[*/0x042C/*::]*/: { /* n:"BrtBeginExtConn14", */ T:1 },
	/*::[*/0x042D/*::]*/: { /* n:"BrtEndExtConn14", */ T:-1 },
	/*::[*/0x042E/*::]*/: { /* n:"BrtBeginSlicerCacheIDs", */ T:1 },
	/*::[*/0x042F/*::]*/: { /* n:"BrtEndSlicerCacheIDs", */ T:-1 },
	/*::[*/0x0430/*::]*/: { /* n:"BrtBeginSlicerCacheID", */ T:1 },
	/*::[*/0x0431/*::]*/: { /* n:"BrtEndSlicerCacheID", */ T:-1 },
	/*::[*/0x0433/*::]*/: { /* n:"BrtBeginSlicerCache", */ T:1 },
	/*::[*/0x0434/*::]*/: { /* n:"BrtEndSlicerCache", */ T:-1 },
	/*::[*/0x0435/*::]*/: { /* n:"BrtBeginSlicerCacheDef", */ T:1 },
	/*::[*/0x0436/*::]*/: { /* n:"BrtEndSlicerCacheDef", */ T:-1 },
	/*::[*/0x0437/*::]*/: { /* n:"BrtBeginSlicersEx", */ T:1 },
	/*::[*/0x0438/*::]*/: { /* n:"BrtEndSlicersEx", */ T:-1 },
	/*::[*/0x0439/*::]*/: { /* n:"BrtBeginSlicerEx", */ T:1 },
	/*::[*/0x043A/*::]*/: { /* n:"BrtEndSlicerEx", */ T:-1 },
	/*::[*/0x043B/*::]*/: { /* n:"BrtBeginSlicer", */ T:1 },
	/*::[*/0x043C/*::]*/: { /* n:"BrtEndSlicer", */ T:-1 },
	/*::[*/0x043D/*::]*/: { /* n:"BrtSlicerCachePivotTables" */ },
	/*::[*/0x043E/*::]*/: { /* n:"BrtBeginSlicerCacheOlapImpl", */ T:1 },
	/*::[*/0x043F/*::]*/: { /* n:"BrtEndSlicerCacheOlapImpl", */ T:-1 },
	/*::[*/0x0440/*::]*/: { /* n:"BrtBeginSlicerCacheLevelsData", */ T:1 },
	/*::[*/0x0441/*::]*/: { /* n:"BrtEndSlicerCacheLevelsData", */ T:-1 },
	/*::[*/0x0442/*::]*/: { /* n:"BrtBeginSlicerCacheLevelData", */ T:1 },
	/*::[*/0x0443/*::]*/: { /* n:"BrtEndSlicerCacheLevelData", */ T:-1 },
	/*::[*/0x0444/*::]*/: { /* n:"BrtBeginSlicerCacheSiRanges", */ T:1 },
	/*::[*/0x0445/*::]*/: { /* n:"BrtEndSlicerCacheSiRanges", */ T:-1 },
	/*::[*/0x0446/*::]*/: { /* n:"BrtBeginSlicerCacheSiRange", */ T:1 },
	/*::[*/0x0447/*::]*/: { /* n:"BrtEndSlicerCacheSiRange", */ T:-1 },
	/*::[*/0x0448/*::]*/: { /* n:"BrtSlicerCacheOlapItem" */ },
	/*::[*/0x0449/*::]*/: { /* n:"BrtBeginSlicerCacheSelections", */ T:1 },
	/*::[*/0x044A/*::]*/: { /* n:"BrtSlicerCacheSelection" */ },
	/*::[*/0x044B/*::]*/: { /* n:"BrtEndSlicerCacheSelections", */ T:-1 },
	/*::[*/0x044C/*::]*/: { /* n:"BrtBeginSlicerCacheNative", */ T:1 },
	/*::[*/0x044D/*::]*/: { /* n:"BrtEndSlicerCacheNative", */ T:-1 },
	/*::[*/0x044E/*::]*/: { /* n:"BrtSlicerCacheNativeItem" */ },
	/*::[*/0x044F/*::]*/: { /* n:"BrtRangeProtection14" */ },
	/*::[*/0x0450/*::]*/: { /* n:"BrtRangeProtectionIso14" */ },
	/*::[*/0x0451/*::]*/: { /* n:"BrtCellIgnoreEC14" */ },
	/*::[*/0x0457/*::]*/: { /* n:"BrtList14" */ },
	/*::[*/0x0458/*::]*/: { /* n:"BrtCFIcon" */ },
	/*::[*/0x0459/*::]*/: { /* n:"BrtBeginSlicerCachesPivotCacheIDs", */ T:1 },
	/*::[*/0x045A/*::]*/: { /* n:"BrtEndSlicerCachesPivotCacheIDs", */ T:-1 },
	/*::[*/0x045B/*::]*/: { /* n:"BrtBeginSlicers", */ T:1 },
	/*::[*/0x045C/*::]*/: { /* n:"BrtEndSlicers", */ T:-1 },
	/*::[*/0x045D/*::]*/: { /* n:"BrtWbProp14" */ },
	/*::[*/0x045E/*::]*/: { /* n:"BrtBeginSXEdit", */ T:1 },
	/*::[*/0x045F/*::]*/: { /* n:"BrtEndSXEdit", */ T:-1 },
	/*::[*/0x0460/*::]*/: { /* n:"BrtBeginSXEdits", */ T:1 },
	/*::[*/0x0461/*::]*/: { /* n:"BrtEndSXEdits", */ T:-1 },
	/*::[*/0x0462/*::]*/: { /* n:"BrtBeginSXChange", */ T:1 },
	/*::[*/0x0463/*::]*/: { /* n:"BrtEndSXChange", */ T:-1 },
	/*::[*/0x0464/*::]*/: { /* n:"BrtBeginSXChanges", */ T:1 },
	/*::[*/0x0465/*::]*/: { /* n:"BrtEndSXChanges", */ T:-1 },
	/*::[*/0x0466/*::]*/: { /* n:"BrtSXTupleItems" */ },
	/*::[*/0x0468/*::]*/: { /* n:"BrtBeginSlicerStyle", */ T:1 },
	/*::[*/0x0469/*::]*/: { /* n:"BrtEndSlicerStyle", */ T:-1 },
	/*::[*/0x046A/*::]*/: { /* n:"BrtSlicerStyleElement" */ },
	/*::[*/0x046B/*::]*/: { /* n:"BrtBeginStyleSheetExt14", */ T:1 },
	/*::[*/0x046C/*::]*/: { /* n:"BrtEndStyleSheetExt14", */ T:-1 },
	/*::[*/0x046D/*::]*/: { /* n:"BrtBeginSlicerCachesPivotCacheID", */ T:1 },
	/*::[*/0x046E/*::]*/: { /* n:"BrtEndSlicerCachesPivotCacheID", */ T:-1 },
	/*::[*/0x046F/*::]*/: { /* n:"BrtBeginConditionalFormattings", */ T:1 },
	/*::[*/0x0470/*::]*/: { /* n:"BrtEndConditionalFormattings", */ T:-1 },
	/*::[*/0x0471/*::]*/: { /* n:"BrtBeginPCDCalcMemExt", */ T:1 },
	/*::[*/0x0472/*::]*/: { /* n:"BrtEndPCDCalcMemExt", */ T:-1 },
	/*::[*/0x0473/*::]*/: { /* n:"BrtBeginPCDCalcMemsExt", */ T:1 },
	/*::[*/0x0474/*::]*/: { /* n:"BrtEndPCDCalcMemsExt", */ T:-1 },
	/*::[*/0x0475/*::]*/: { /* n:"BrtPCDField14" */ },
	/*::[*/0x0476/*::]*/: { /* n:"BrtBeginSlicerStyles", */ T:1 },
	/*::[*/0x0477/*::]*/: { /* n:"BrtEndSlicerStyles", */ T:-1 },
	/*::[*/0x0478/*::]*/: { /* n:"BrtBeginSlicerStyleElements", */ T:1 },
	/*::[*/0x0479/*::]*/: { /* n:"BrtEndSlicerStyleElements", */ T:-1 },
	/*::[*/0x047A/*::]*/: { /* n:"BrtCFRuleExt" */ },
	/*::[*/0x047B/*::]*/: { /* n:"BrtBeginSXCondFmt14", */ T:1 },
	/*::[*/0x047C/*::]*/: { /* n:"BrtEndSXCondFmt14", */ T:-1 },
	/*::[*/0x047D/*::]*/: { /* n:"BrtBeginSXCondFmts14", */ T:1 },
	/*::[*/0x047E/*::]*/: { /* n:"BrtEndSXCondFmts14", */ T:-1 },
	/*::[*/0x0480/*::]*/: { /* n:"BrtBeginSortCond14", */ T:1 },
	/*::[*/0x0481/*::]*/: { /* n:"BrtEndSortCond14", */ T:-1 },
	/*::[*/0x0482/*::]*/: { /* n:"BrtEndDVals14", */ T:-1 },
	/*::[*/0x0483/*::]*/: { /* n:"BrtEndIconSet14", */ T:-1 },
	/*::[*/0x0484/*::]*/: { /* n:"BrtEndDatabar14", */ T:-1 },
	/*::[*/0x0485/*::]*/: { /* n:"BrtBeginColorScale14", */ T:1 },
	/*::[*/0x0486/*::]*/: { /* n:"BrtEndColorScale14", */ T:-1 },
	/*::[*/0x0487/*::]*/: { /* n:"BrtBeginSxrules14", */ T:1 },
	/*::[*/0x0488/*::]*/: { /* n:"BrtEndSxrules14", */ T:-1 },
	/*::[*/0x0489/*::]*/: { /* n:"BrtBeginPRule14", */ T:1 },
	/*::[*/0x048A/*::]*/: { /* n:"BrtEndPRule14", */ T:-1 },
	/*::[*/0x048B/*::]*/: { /* n:"BrtBeginPRFilters14", */ T:1 },
	/*::[*/0x048C/*::]*/: { /* n:"BrtEndPRFilters14", */ T:-1 },
	/*::[*/0x048D/*::]*/: { /* n:"BrtBeginPRFilter14", */ T:1 },
	/*::[*/0x048E/*::]*/: { /* n:"BrtEndPRFilter14", */ T:-1 },
	/*::[*/0x048F/*::]*/: { /* n:"BrtBeginPRFItem14", */ T:1 },
	/*::[*/0x0490/*::]*/: { /* n:"BrtEndPRFItem14", */ T:-1 },
	/*::[*/0x0491/*::]*/: { /* n:"BrtBeginCellIgnoreECs14", */ T:1 },
	/*::[*/0x0492/*::]*/: { /* n:"BrtEndCellIgnoreECs14", */ T:-1 },
	/*::[*/0x0493/*::]*/: { /* n:"BrtDxf14" */ },
	/*::[*/0x0494/*::]*/: { /* n:"BrtBeginDxF14s", */ T:1 },
	/*::[*/0x0495/*::]*/: { /* n:"BrtEndDxf14s", */ T:-1 },
	/*::[*/0x0499/*::]*/: { /* n:"BrtFilter14" */ },
	/*::[*/0x049A/*::]*/: { /* n:"BrtBeginCustomFilters14", */ T:1 },
	/*::[*/0x049C/*::]*/: { /* n:"BrtCustomFilter14" */ },
	/*::[*/0x049D/*::]*/: { /* n:"BrtIconFilter14" */ },
	/*::[*/0x049E/*::]*/: { /* n:"BrtPivotCacheConnectionName" */ },
	/*::[*/0x0800/*::]*/: { /* n:"BrtBeginDecoupledPivotCacheIDs", */ T:1 },
	/*::[*/0x0801/*::]*/: { /* n:"BrtEndDecoupledPivotCacheIDs", */ T:-1 },
	/*::[*/0x0802/*::]*/: { /* n:"BrtDecoupledPivotCacheID" */ },
	/*::[*/0x0803/*::]*/: { /* n:"BrtBeginPivotTableRefs", */ T:1 },
	/*::[*/0x0804/*::]*/: { /* n:"BrtEndPivotTableRefs", */ T:-1 },
	/*::[*/0x0805/*::]*/: { /* n:"BrtPivotTableRef" */ },
	/*::[*/0x0806/*::]*/: { /* n:"BrtSlicerCacheBookPivotTables" */ },
	/*::[*/0x0807/*::]*/: { /* n:"BrtBeginSxvcells", */ T:1 },
	/*::[*/0x0808/*::]*/: { /* n:"BrtEndSxvcells", */ T:-1 },
	/*::[*/0x0809/*::]*/: { /* n:"BrtBeginSxRow", */ T:1 },
	/*::[*/0x080A/*::]*/: { /* n:"BrtEndSxRow", */ T:-1 },
	/*::[*/0x080C/*::]*/: { /* n:"BrtPcdCalcMem15" */ },
	/*::[*/0x0813/*::]*/: { /* n:"BrtQsi15" */ },
	/*::[*/0x0814/*::]*/: { /* n:"BrtBeginWebExtensions", */ T:1 },
	/*::[*/0x0815/*::]*/: { /* n:"BrtEndWebExtensions", */ T:-1 },
	/*::[*/0x0816/*::]*/: { /* n:"BrtWebExtension" */ },
	/*::[*/0x0817/*::]*/: { /* n:"BrtAbsPath15" */ },
	/*::[*/0x0818/*::]*/: { /* n:"BrtBeginPivotTableUISettings", */ T:1 },
	/*::[*/0x0819/*::]*/: { /* n:"BrtEndPivotTableUISettings", */ T:-1 },
	/*::[*/0x081B/*::]*/: { /* n:"BrtTableSlicerCacheIDs" */ },
	/*::[*/0x081C/*::]*/: { /* n:"BrtTableSlicerCacheID" */ },
	/*::[*/0x081D/*::]*/: { /* n:"BrtBeginTableSlicerCache", */ T:1 },
	/*::[*/0x081E/*::]*/: { /* n:"BrtEndTableSlicerCache", */ T:-1 },
	/*::[*/0x081F/*::]*/: { /* n:"BrtSxFilter15" */ },
	/*::[*/0x0820/*::]*/: { /* n:"BrtBeginTimelineCachePivotCacheIDs", */ T:1 },
	/*::[*/0x0821/*::]*/: { /* n:"BrtEndTimelineCachePivotCacheIDs", */ T:-1 },
	/*::[*/0x0822/*::]*/: { /* n:"BrtTimelineCachePivotCacheID" */ },
	/*::[*/0x0823/*::]*/: { /* n:"BrtBeginTimelineCacheIDs", */ T:1 },
	/*::[*/0x0824/*::]*/: { /* n:"BrtEndTimelineCacheIDs", */ T:-1 },
	/*::[*/0x0825/*::]*/: { /* n:"BrtBeginTimelineCacheID", */ T:1 },
	/*::[*/0x0826/*::]*/: { /* n:"BrtEndTimelineCacheID", */ T:-1 },
	/*::[*/0x0827/*::]*/: { /* n:"BrtBeginTimelinesEx", */ T:1 },
	/*::[*/0x0828/*::]*/: { /* n:"BrtEndTimelinesEx", */ T:-1 },
	/*::[*/0x0829/*::]*/: { /* n:"BrtBeginTimelineEx", */ T:1 },
	/*::[*/0x082A/*::]*/: { /* n:"BrtEndTimelineEx", */ T:-1 },
	/*::[*/0x082B/*::]*/: { /* n:"BrtWorkBookPr15" */ },
	/*::[*/0x082C/*::]*/: { /* n:"BrtPCDH15" */ },
	/*::[*/0x082D/*::]*/: { /* n:"BrtBeginTimelineStyle", */ T:1 },
	/*::[*/0x082E/*::]*/: { /* n:"BrtEndTimelineStyle", */ T:-1 },
	/*::[*/0x082F/*::]*/: { /* n:"BrtTimelineStyleElement" */ },
	/*::[*/0x0830/*::]*/: { /* n:"BrtBeginTimelineStylesheetExt15", */ T:1 },
	/*::[*/0x0831/*::]*/: { /* n:"BrtEndTimelineStylesheetExt15", */ T:-1 },
	/*::[*/0x0832/*::]*/: { /* n:"BrtBeginTimelineStyles", */ T:1 },
	/*::[*/0x0833/*::]*/: { /* n:"BrtEndTimelineStyles", */ T:-1 },
	/*::[*/0x0834/*::]*/: { /* n:"BrtBeginTimelineStyleElements", */ T:1 },
	/*::[*/0x0835/*::]*/: { /* n:"BrtEndTimelineStyleElements", */ T:-1 },
	/*::[*/0x0836/*::]*/: { /* n:"BrtDxf15" */ },
	/*::[*/0x0837/*::]*/: { /* n:"BrtBeginDxfs15", */ T:1 },
	/*::[*/0x0838/*::]*/: { /* n:"BrtEndDxfs15", */ T:-1 },
	/*::[*/0x0839/*::]*/: { /* n:"BrtSlicerCacheHideItemsWithNoData" */ },
	/*::[*/0x083A/*::]*/: { /* n:"BrtBeginItemUniqueNames", */ T:1 },
	/*::[*/0x083B/*::]*/: { /* n:"BrtEndItemUniqueNames", */ T:-1 },
	/*::[*/0x083C/*::]*/: { /* n:"BrtItemUniqueName" */ },
	/*::[*/0x083D/*::]*/: { /* n:"BrtBeginExtConn15", */ T:1 },
	/*::[*/0x083E/*::]*/: { /* n:"BrtEndExtConn15", */ T:-1 },
	/*::[*/0x083F/*::]*/: { /* n:"BrtBeginOledbPr15", */ T:1 },
	/*::[*/0x0840/*::]*/: { /* n:"BrtEndOledbPr15", */ T:-1 },
	/*::[*/0x0841/*::]*/: { /* n:"BrtBeginDataFeedPr15", */ T:1 },
	/*::[*/0x0842/*::]*/: { /* n:"BrtEndDataFeedPr15", */ T:-1 },
	/*::[*/0x0843/*::]*/: { /* n:"BrtTextPr15" */ },
	/*::[*/0x0844/*::]*/: { /* n:"BrtRangePr15" */ },
	/*::[*/0x0845/*::]*/: { /* n:"BrtDbCommand15" */ },
	/*::[*/0x0846/*::]*/: { /* n:"BrtBeginDbTables15", */ T:1 },
	/*::[*/0x0847/*::]*/: { /* n:"BrtEndDbTables15", */ T:-1 },
	/*::[*/0x0848/*::]*/: { /* n:"BrtDbTable15" */ },
	/*::[*/0x0849/*::]*/: { /* n:"BrtBeginDataModel", */ T:1 },
	/*::[*/0x084A/*::]*/: { /* n:"BrtEndDataModel", */ T:-1 },
	/*::[*/0x084B/*::]*/: { /* n:"BrtBeginModelTables", */ T:1 },
	/*::[*/0x084C/*::]*/: { /* n:"BrtEndModelTables", */ T:-1 },
	/*::[*/0x084D/*::]*/: { /* n:"BrtModelTable" */ },
	/*::[*/0x084E/*::]*/: { /* n:"BrtBeginModelRelationships", */ T:1 },
	/*::[*/0x084F/*::]*/: { /* n:"BrtEndModelRelationships", */ T:-1 },
	/*::[*/0x0850/*::]*/: { /* n:"BrtModelRelationship" */ },
	/*::[*/0x0851/*::]*/: { /* n:"BrtBeginECTxtWiz15", */ T:1 },
	/*::[*/0x0852/*::]*/: { /* n:"BrtEndECTxtWiz15", */ T:-1 },
	/*::[*/0x0853/*::]*/: { /* n:"BrtBeginECTWFldInfoLst15", */ T:1 },
	/*::[*/0x0854/*::]*/: { /* n:"BrtEndECTWFldInfoLst15", */ T:-1 },
	/*::[*/0x0855/*::]*/: { /* n:"BrtBeginECTWFldInfo15", */ T:1 },
	/*::[*/0x0856/*::]*/: { /* n:"BrtFieldListActiveItem" */ },
	/*::[*/0x0857/*::]*/: { /* n:"BrtPivotCacheIdVersion" */ },
	/*::[*/0x0858/*::]*/: { /* n:"BrtSXDI15" */ },
	/*::[*/0x0859/*::]*/: { /* n:"BrtBeginModelTimeGroupings", */ T:1 },
	/*::[*/0x085A/*::]*/: { /* n:"BrtEndModelTimeGroupings", */ T:-1 },
	/*::[*/0x085B/*::]*/: { /* n:"BrtBeginModelTimeGrouping", */ T:1 },
	/*::[*/0x085C/*::]*/: { /* n:"BrtEndModelTimeGrouping", */ T:-1 },
	/*::[*/0x085D/*::]*/: { /* n:"BrtModelTimeGroupingCalcCol" */ },
	/*::[*/0x0C00/*::]*/: { /* n:"BrtUid" */ },
	/*::[*/0x0C01/*::]*/: { /* n:"BrtRevisionPtr" */ },
	/*::[*/0x1000/*::]*/: { /* n:"BrtBeginDynamicArrayPr", */ T:1 },
	/*::[*/0x1001/*::]*/: { /* n:"BrtEndDynamicArrayPr", */ T:-1 },
	/*::[*/0x138A/*::]*/: { /* n:"BrtBeginRichValueBlock", */ T:1 },
	/*::[*/0x138B/*::]*/: { /* n:"BrtEndRichValueBlock", */ T:-1 },
	/*::[*/0x13D9/*::]*/: { /* n:"BrtBeginRichFilters", */ T:1 },
	/*::[*/0x13DA/*::]*/: { /* n:"BrtEndRichFilters", */ T:-1 },
	/*::[*/0x13DB/*::]*/: { /* n:"BrtRichFilter" */ },
	/*::[*/0x13DC/*::]*/: { /* n:"BrtBeginRichFilterColumn", */ T:1 },
	/*::[*/0x13DD/*::]*/: { /* n:"BrtEndRichFilterColumn", */ T:-1 },
	/*::[*/0x13DE/*::]*/: { /* n:"BrtBeginCustomRichFilters", */ T:1 },
	/*::[*/0x13DF/*::]*/: { /* n:"BrtEndCustomRichFilters", */ T:-1 },
	/*::[*/0x13E0/*::]*/: { /* n:"BrtCustomRichFilter" */ },
	/*::[*/0x13E1/*::]*/: { /* n:"BrtTop10RichFilter" */ },
	/*::[*/0x13E2/*::]*/: { /* n:"BrtDynamicRichFilter" */ },
	/*::[*/0x13E4/*::]*/: { /* n:"BrtBeginRichSortCondition", */ T:1 },
	/*::[*/0x13E5/*::]*/: { /* n:"BrtEndRichSortCondition", */ T:-1 },
	/*::[*/0x13E6/*::]*/: { /* n:"BrtRichFilterDateGroupItem" */ },
	/*::[*/0x13E7/*::]*/: { /* n:"BrtBeginCalcFeatures", */ T:1 },
	/*::[*/0x13E8/*::]*/: { /* n:"BrtEndCalcFeatures", */ T:-1 },
	/*::[*/0x13E9/*::]*/: { /* n:"BrtCalcFeature" */ },
	/*::[*/0x13EB/*::]*/: { /* n:"BrtExternalLinksPr" */ },
	/*::[*/0xFFFF/*::]*/: { n:"" }
};

/* [MS-XLS] 2.3 Record Enumeration (and other sources) */
var XLSRecordEnum = {
	/* [MS-XLS] 2.3 Record Enumeration 2021-08-17 */
	/*::[*/0x0006/*::]*/: { /* n:"Formula", */ f:parse_Formula },
	/*::[*/0x000a/*::]*/: { /* n:"EOF", */ f:parsenoop2 },
	/*::[*/0x000c/*::]*/: { /* n:"CalcCount", */ f:parseuint16 }, //
	/*::[*/0x000d/*::]*/: { /* n:"CalcMode", */ f:parseuint16 }, //
	/*::[*/0x000e/*::]*/: { /* n:"CalcPrecision", */ f:parsebool }, //
	/*::[*/0x000f/*::]*/: { /* n:"CalcRefMode", */ f:parsebool }, //
	/*::[*/0x0010/*::]*/: { /* n:"CalcDelta", */ f:parse_Xnum }, //
	/*::[*/0x0011/*::]*/: { /* n:"CalcIter", */ f:parsebool }, //
	/*::[*/0x0012/*::]*/: { /* n:"Protect", */ f:parsebool },
	/*::[*/0x0013/*::]*/: { /* n:"Password", */ f:parseuint16 },
	/*::[*/0x0014/*::]*/: { /* n:"Header", */ f:parse_XLHeaderFooter },
	/*::[*/0x0015/*::]*/: { /* n:"Footer", */ f:parse_XLHeaderFooter },
	/*::[*/0x0017/*::]*/: { /* n:"ExternSheet", */ f:parse_ExternSheet },
	/*::[*/0x0018/*::]*/: { /* n:"Lbl", */ f:parse_Lbl },
	/*::[*/0x0019/*::]*/: { /* n:"WinProtect", */ f:parsebool },
	/*::[*/0x001a/*::]*/: { /* n:"VerticalPageBreaks", */ },
	/*::[*/0x001b/*::]*/: { /* n:"HorizontalPageBreaks", */ },
	/*::[*/0x001c/*::]*/: { /* n:"Note", */ f:parse_Note },
	/*::[*/0x001d/*::]*/: { /* n:"Selection", */ },
	/*::[*/0x0022/*::]*/: { /* n:"Date1904", */ f:parsebool },
	/*::[*/0x0023/*::]*/: { /* n:"ExternName", */ f:parse_ExternName },
	/*::[*/0x0026/*::]*/: { /* n:"LeftMargin", */ f:parse_Xnum }, // *
	/*::[*/0x0027/*::]*/: { /* n:"RightMargin", */ f:parse_Xnum }, // *
	/*::[*/0x0028/*::]*/: { /* n:"TopMargin", */ f:parse_Xnum }, // *
	/*::[*/0x0029/*::]*/: { /* n:"BottomMargin", */ f:parse_Xnum }, // *
	/*::[*/0x002a/*::]*/: { /* n:"PrintRowCol", */ f:parsebool },
	/*::[*/0x002b/*::]*/: { /* n:"PrintGrid", */ f:parsebool },
	/*::[*/0x002f/*::]*/: { /* n:"FilePass", */ f:parse_FilePass },
	/*::[*/0x0031/*::]*/: { /* n:"Font", */ f:parse_Font },
	/*::[*/0x0033/*::]*/: { /* n:"PrintSize", */ f:parseuint16 },
	/*::[*/0x003c/*::]*/: { /* n:"Continue", */ },
	/*::[*/0x003d/*::]*/: { /* n:"Window1", */ f:parse_Window1 },
	/*::[*/0x0040/*::]*/: { /* n:"Backup", */ f:parsebool },
	/*::[*/0x0041/*::]*/: { /* n:"Pane", */ f:parse_Pane },
	/*::[*/0x0042/*::]*/: { /* n:"CodePage", */ f:parseuint16 },
	/*::[*/0x004d/*::]*/: { /* n:"Pls", */ },
	/*::[*/0x0050/*::]*/: { /* n:"DCon", */ },
	/*::[*/0x0051/*::]*/: { /* n:"DConRef", */ },
	/*::[*/0x0052/*::]*/: { /* n:"DConName", */ },
	/*::[*/0x0055/*::]*/: { /* n:"DefColWidth", */ f:parseuint16 },
	/*::[*/0x0059/*::]*/: { /* n:"XCT", */ },
	/*::[*/0x005a/*::]*/: { /* n:"CRN", */ },
	/*::[*/0x005b/*::]*/: { /* n:"FileSharing", */ },
	/*::[*/0x005c/*::]*/: { /* n:"WriteAccess", */ f:parse_WriteAccess },
	/*::[*/0x005d/*::]*/: { /* n:"Obj", */ f:parse_Obj },
	/*::[*/0x005e/*::]*/: { /* n:"Uncalced", */ },
	/*::[*/0x005f/*::]*/: { /* n:"CalcSaveRecalc", */ f:parsebool }, //
	/*::[*/0x0060/*::]*/: { /* n:"Template", */ },
	/*::[*/0x0061/*::]*/: { /* n:"Intl", */ },
	/*::[*/0x0063/*::]*/: { /* n:"ObjProtect", */ f:parsebool },
	/*::[*/0x007d/*::]*/: { /* n:"ColInfo", */ f:parse_ColInfo },
	/*::[*/0x0080/*::]*/: { /* n:"Guts", */ f:parse_Guts },
	/*::[*/0x0081/*::]*/: { /* n:"WsBool", */ f:parse_WsBool },
	/*::[*/0x0082/*::]*/: { /* n:"GridSet", */ f:parseuint16 },
	/*::[*/0x0083/*::]*/: { /* n:"HCenter", */ f:parsebool },
	/*::[*/0x0084/*::]*/: { /* n:"VCenter", */ f:parsebool },
	/*::[*/0x0085/*::]*/: { /* n:"BoundSheet8", */ f:parse_BoundSheet8 },
	/*::[*/0x0086/*::]*/: { /* n:"WriteProtect", */ },
	/*::[*/0x008c/*::]*/: { /* n:"Country", */ f:parse_Country },
	/*::[*/0x008d/*::]*/: { /* n:"HideObj", */ f:parseuint16 },
	/*::[*/0x0090/*::]*/: { /* n:"Sort", */ },
	/*::[*/0x0092/*::]*/: { /* n:"Palette", */ f:parse_Palette },
	/*::[*/0x0097/*::]*/: { /* n:"Sync", */ },
	/*::[*/0x0098/*::]*/: { /* n:"LPr", */ },
	/*::[*/0x0099/*::]*/: { /* n:"DxGCol", */ },
	/*::[*/0x009a/*::]*/: { /* n:"FnGroupName", */ },
	/*::[*/0x009b/*::]*/: { /* n:"FilterMode", */ },
	/*::[*/0x009c/*::]*/: { /* n:"BuiltInFnGroupCount", */ f:parseuint16 },
	/*::[*/0x009d/*::]*/: { /* n:"AutoFilterInfo", */ },
	/*::[*/0x009e/*::]*/: { /* n:"AutoFilter", */ },
	/*::[*/0x00a0/*::]*/: { /* n:"Scl", */ f:parse_Scl },
	/*::[*/0x00a1/*::]*/: { /* n:"Setup", */ f:parse_Setup },
	/*::[*/0x00ae/*::]*/: { /* n:"ScenMan", */ },
	/*::[*/0x00af/*::]*/: { /* n:"SCENARIO", */ },
	/*::[*/0x00b0/*::]*/: { /* n:"SxView", */ },
	/*::[*/0x00b1/*::]*/: { /* n:"Sxvd", */ },
	/*::[*/0x00b2/*::]*/: { /* n:"SXVI", */ },
	/*::[*/0x00b4/*::]*/: { /* n:"SxIvd", */ },
	/*::[*/0x00b5/*::]*/: { /* n:"SXLI", */ },
	/*::[*/0x00b6/*::]*/: { /* n:"SXPI", */ },
	/*::[*/0x00b8/*::]*/: { /* n:"DocRoute", */ },
	/*::[*/0x00b9/*::]*/: { /* n:"RecipName", */ },
	/*::[*/0x00bd/*::]*/: { /* n:"MulRk", */ f:parse_MulRk },
	/*::[*/0x00be/*::]*/: { /* n:"MulBlank", */ f:parse_MulBlank },
	/*::[*/0x00c1/*::]*/: { /* n:"Mms", */ f:parsenoop2 },
	/*::[*/0x00c5/*::]*/: { /* n:"SXDI", */ },
	/*::[*/0x00c6/*::]*/: { /* n:"SXDB", */ },
	/*::[*/0x00c7/*::]*/: { /* n:"SXFDB", */ },
	/*::[*/0x00c8/*::]*/: { /* n:"SXDBB", */ },
	/*::[*/0x00c9/*::]*/: { /* n:"SXNum", */ },
	/*::[*/0x00ca/*::]*/: { /* n:"SxBool", */ f:parsebool },
	/*::[*/0x00cb/*::]*/: { /* n:"SxErr", */ },
	/*::[*/0x00cc/*::]*/: { /* n:"SXInt", */ },
	/*::[*/0x00cd/*::]*/: { /* n:"SXString", */ },
	/*::[*/0x00ce/*::]*/: { /* n:"SXDtr", */ },
	/*::[*/0x00cf/*::]*/: { /* n:"SxNil", */ },
	/*::[*/0x00d0/*::]*/: { /* n:"SXTbl", */ },
	/*::[*/0x00d1/*::]*/: { /* n:"SXTBRGIITM", */ },
	/*::[*/0x00d2/*::]*/: { /* n:"SxTbpg", */ },
	/*::[*/0x00d3/*::]*/: { /* n:"ObProj", */ },
	/*::[*/0x00d5/*::]*/: { /* n:"SXStreamID", */ },
	/*::[*/0x00d7/*::]*/: { /* n:"DBCell", */ },
	/*::[*/0x00d8/*::]*/: { /* n:"SXRng", */ },
	/*::[*/0x00d9/*::]*/: { /* n:"SxIsxoper", */ },
	/*::[*/0x00da/*::]*/: { /* n:"BookBool", */ f:parseuint16 },
	/*::[*/0x00dc/*::]*/: { /* n:"DbOrParamQry", */ },
	/*::[*/0x00dd/*::]*/: { /* n:"ScenarioProtect", */ f:parsebool },
	/*::[*/0x00de/*::]*/: { /* n:"OleObjectSize", */ },
	/*::[*/0x00e0/*::]*/: { /* n:"XF", */ f:parse_XF },
	/*::[*/0x00e1/*::]*/: { /* n:"InterfaceHdr", */ f:parse_InterfaceHdr },
	/*::[*/0x00e2/*::]*/: { /* n:"InterfaceEnd", */ f:parsenoop2 },
	/*::[*/0x00e3/*::]*/: { /* n:"SXVS", */ },
	/*::[*/0x00e5/*::]*/: { /* n:"MergeCells", */ f:parse_MergeCells },
	/*::[*/0x00e9/*::]*/: { /* n:"BkHim", */ },
	/*::[*/0x00eb/*::]*/: { /* n:"MsoDrawingGroup", */ },
	/*::[*/0x00ec/*::]*/: { /* n:"MsoDrawing", */ },
	/*::[*/0x00ed/*::]*/: { /* n:"MsoDrawingSelection", */ },
	/*::[*/0x00ef/*::]*/: { /* n:"PhoneticInfo", */ },
	/*::[*/0x00f0/*::]*/: { /* n:"SxRule", */ },
	/*::[*/0x00f1/*::]*/: { /* n:"SXEx", */ },
	/*::[*/0x00f2/*::]*/: { /* n:"SxFilt", */ },
	/*::[*/0x00f4/*::]*/: { /* n:"SxDXF", */ },
	/*::[*/0x00f5/*::]*/: { /* n:"SxItm", */ },
	/*::[*/0x00f6/*::]*/: { /* n:"SxName", */ },
	/*::[*/0x00f7/*::]*/: { /* n:"SxSelect", */ },
	/*::[*/0x00f8/*::]*/: { /* n:"SXPair", */ },
	/*::[*/0x00f9/*::]*/: { /* n:"SxFmla", */ },
	/*::[*/0x00fb/*::]*/: { /* n:"SxFormat", */ },
	/*::[*/0x00fc/*::]*/: { /* n:"SST", */ f:parse_SST },
	/*::[*/0x00fd/*::]*/: { /* n:"LabelSst", */ f:parse_LabelSst },
	/*::[*/0x00ff/*::]*/: { /* n:"ExtSST", */ f:parse_ExtSST },
	/*::[*/0x0100/*::]*/: { /* n:"SXVDEx", */ },
	/*::[*/0x0103/*::]*/: { /* n:"SXFormula", */ },
	/*::[*/0x0122/*::]*/: { /* n:"SXDBEx", */ },
	/*::[*/0x0137/*::]*/: { /* n:"RRDInsDel", */ },
	/*::[*/0x0138/*::]*/: { /* n:"RRDHead", */ },
	/*::[*/0x013b/*::]*/: { /* n:"RRDChgCell", */ },
	/*::[*/0x013d/*::]*/: { /* n:"RRTabId", */ f:parseuint16a },
	/*::[*/0x013e/*::]*/: { /* n:"RRDRenSheet", */ },
	/*::[*/0x013f/*::]*/: { /* n:"RRSort", */ },
	/*::[*/0x0140/*::]*/: { /* n:"RRDMove", */ },
	/*::[*/0x014a/*::]*/: { /* n:"RRFormat", */ },
	/*::[*/0x014b/*::]*/: { /* n:"RRAutoFmt", */ },
	/*::[*/0x014d/*::]*/: { /* n:"RRInsertSh", */ },
	/*::[*/0x014e/*::]*/: { /* n:"RRDMoveBegin", */ },
	/*::[*/0x014f/*::]*/: { /* n:"RRDMoveEnd", */ },
	/*::[*/0x0150/*::]*/: { /* n:"RRDInsDelBegin", */ },
	/*::[*/0x0151/*::]*/: { /* n:"RRDInsDelEnd", */ },
	/*::[*/0x0152/*::]*/: { /* n:"RRDConflict", */ },
	/*::[*/0x0153/*::]*/: { /* n:"RRDDefName", */ },
	/*::[*/0x0154/*::]*/: { /* n:"RRDRstEtxp", */ },
	/*::[*/0x015f/*::]*/: { /* n:"LRng", */ },
	/*::[*/0x0160/*::]*/: { /* n:"UsesELFs", */ f:parsebool },
	/*::[*/0x0161/*::]*/: { /* n:"DSF", */ f:parsenoop2 },
	/*::[*/0x0191/*::]*/: { /* n:"CUsr", */ },
	/*::[*/0x0192/*::]*/: { /* n:"CbUsr", */ },
	/*::[*/0x0193/*::]*/: { /* n:"UsrInfo", */ },
	/*::[*/0x0194/*::]*/: { /* n:"UsrExcl", */ },
	/*::[*/0x0195/*::]*/: { /* n:"FileLock", */ },
	/*::[*/0x0196/*::]*/: { /* n:"RRDInfo", */ },
	/*::[*/0x0197/*::]*/: { /* n:"BCUsrs", */ },
	/*::[*/0x0198/*::]*/: { /* n:"UsrChk", */ },
	/*::[*/0x01a9/*::]*/: { /* n:"UserBView", */ },
	/*::[*/0x01aa/*::]*/: { /* n:"UserSViewBegin", */ },
	/*::[*/0x01ab/*::]*/: { /* n:"UserSViewEnd", */ },
	/*::[*/0x01ac/*::]*/: { /* n:"RRDUserView", */ },
	/*::[*/0x01ad/*::]*/: { /* n:"Qsi", */ },
	/*::[*/0x01ae/*::]*/: { /* n:"SupBook", */ f:parse_SupBook },
	/*::[*/0x01af/*::]*/: { /* n:"Prot4Rev", */ f:parsebool },
	/*::[*/0x01b0/*::]*/: { /* n:"CondFmt", */ },
	/*::[*/0x01b1/*::]*/: { /* n:"CF", */ },
	/*::[*/0x01b2/*::]*/: { /* n:"DVal", */ },
	/*::[*/0x01b5/*::]*/: { /* n:"DConBin", */ },
	/*::[*/0x01b6/*::]*/: { /* n:"TxO", */ f:parse_TxO },
	/*::[*/0x01b7/*::]*/: { /* n:"RefreshAll", */ f:parsebool }, //
	/*::[*/0x01b8/*::]*/: { /* n:"HLink", */ f:parse_HLink },
	/*::[*/0x01b9/*::]*/: { /* n:"Lel", */ },
	/*::[*/0x01ba/*::]*/: { /* n:"CodeName", */ f:parse_XLUnicodeString },
	/*::[*/0x01bb/*::]*/: { /* n:"SXFDBType", */ },
	/*::[*/0x01bc/*::]*/: { /* n:"Prot4RevPass", */ f:parseuint16 },
	/*::[*/0x01bd/*::]*/: { /* n:"ObNoMacros", */ },
	/*::[*/0x01be/*::]*/: { /* n:"Dv", */ },
	/*::[*/0x01c0/*::]*/: { /* n:"Excel9File", */ f:parsenoop2 },
	/*::[*/0x01c1/*::]*/: { /* n:"RecalcId", */ f:parse_RecalcId, r:2},
	/*::[*/0x01c2/*::]*/: { /* n:"EntExU2", */ f:parsenoop2 },
	/*::[*/0x0200/*::]*/: { /* n:"Dimensions", */ f:parse_Dimensions },
	/*::[*/0x0201/*::]*/: { /* n:"Blank", */ f:parse_Blank },
	/*::[*/0x0203/*::]*/: { /* n:"Number", */ f:parse_Number },
	/*::[*/0x0204/*::]*/: { /* n:"Label", */ f:parse_Label },
	/*::[*/0x0205/*::]*/: { /* n:"BoolErr", */ f:parse_BoolErr },
	/*::[*/0x0207/*::]*/: { /* n:"String", */ f:parse_String },
	/*::[*/0x0208/*::]*/: { /* n:"Row", */ f:parse_Row },
	/*::[*/0x020b/*::]*/: { /* n:"Index", */ },
	/*::[*/0x0221/*::]*/: { /* n:"Array", */ f:parse_Array },
	/*::[*/0x0225/*::]*/: { /* n:"DefaultRowHeight", */ f:parse_DefaultRowHeight },
	/*::[*/0x0236/*::]*/: { /* n:"Table", */ },
	/*::[*/0x023e/*::]*/: { /* n:"Window2", */ f:parse_Window2 },
	/*::[*/0x027e/*::]*/: { /* n:"RK", */ f:parse_RK },
	/*::[*/0x0293/*::]*/: { /* n:"Style", */ },
	/*::[*/0x0418/*::]*/: { /* n:"BigName", */ },
	/*::[*/0x041e/*::]*/: { /* n:"Format", */ f:parse_Format },
	/*::[*/0x043c/*::]*/: { /* n:"ContinueBigName", */ },
	/*::[*/0x04bc/*::]*/: { /* n:"ShrFmla", */ f:parse_ShrFmla },
	/*::[*/0x0800/*::]*/: { /* n:"HLinkTooltip", */ f:parse_HLinkTooltip },
	/*::[*/0x0801/*::]*/: { /* n:"WebPub", */ },
	/*::[*/0x0802/*::]*/: { /* n:"QsiSXTag", */ },
	/*::[*/0x0803/*::]*/: { /* n:"DBQueryExt", */ },
	/*::[*/0x0804/*::]*/: { /* n:"ExtString", */ },
	/*::[*/0x0805/*::]*/: { /* n:"TxtQry", */ },
	/*::[*/0x0806/*::]*/: { /* n:"Qsir", */ },
	/*::[*/0x0807/*::]*/: { /* n:"Qsif", */ },
	/*::[*/0x0808/*::]*/: { /* n:"RRDTQSIF", */ },
	/*::[*/0x0809/*::]*/: { /* n:"BOF", */ f:parse_BOF },
	/*::[*/0x080a/*::]*/: { /* n:"OleDbConn", */ },
	/*::[*/0x080b/*::]*/: { /* n:"WOpt", */ },
	/*::[*/0x080c/*::]*/: { /* n:"SXViewEx", */ },
	/*::[*/0x080d/*::]*/: { /* n:"SXTH", */ },
	/*::[*/0x080e/*::]*/: { /* n:"SXPIEx", */ },
	/*::[*/0x080f/*::]*/: { /* n:"SXVDTEx", */ },
	/*::[*/0x0810/*::]*/: { /* n:"SXViewEx9", */ },
	/*::[*/0x0812/*::]*/: { /* n:"ContinueFrt", */ },
	/*::[*/0x0813/*::]*/: { /* n:"RealTimeData", */ },
	/*::[*/0x0850/*::]*/: { /* n:"ChartFrtInfo", */ },
	/*::[*/0x0851/*::]*/: { /* n:"FrtWrapper", */ },
	/*::[*/0x0852/*::]*/: { /* n:"StartBlock", */ },
	/*::[*/0x0853/*::]*/: { /* n:"EndBlock", */ },
	/*::[*/0x0854/*::]*/: { /* n:"StartObject", */ },
	/*::[*/0x0855/*::]*/: { /* n:"EndObject", */ },
	/*::[*/0x0856/*::]*/: { /* n:"CatLab", */ },
	/*::[*/0x0857/*::]*/: { /* n:"YMult", */ },
	/*::[*/0x0858/*::]*/: { /* n:"SXViewLink", */ },
	/*::[*/0x0859/*::]*/: { /* n:"PivotChartBits", */ },
	/*::[*/0x085a/*::]*/: { /* n:"FrtFontList", */ },
	/*::[*/0x0862/*::]*/: { /* n:"SheetExt", */ },
	/*::[*/0x0863/*::]*/: { /* n:"BookExt", */ r:12},
	/*::[*/0x0864/*::]*/: { /* n:"SXAddl", */ },
	/*::[*/0x0865/*::]*/: { /* n:"CrErr", */ },
	/*::[*/0x0866/*::]*/: { /* n:"HFPicture", */ },
	/*::[*/0x0867/*::]*/: { /* n:"FeatHdr", */ f:parsenoop2 },
	/*::[*/0x0868/*::]*/: { /* n:"Feat", */ },
	/*::[*/0x086a/*::]*/: { /* n:"DataLabExt", */ },
	/*::[*/0x086b/*::]*/: { /* n:"DataLabExtContents", */ },
	/*::[*/0x086c/*::]*/: { /* n:"CellWatch", */ },
	/*::[*/0x0871/*::]*/: { /* n:"FeatHdr11", */ },
	/*::[*/0x0872/*::]*/: { /* n:"Feature11", */ },
	/*::[*/0x0874/*::]*/: { /* n:"DropDownObjIds", */ },
	/*::[*/0x0875/*::]*/: { /* n:"ContinueFrt11", */ },
	/*::[*/0x0876/*::]*/: { /* n:"DConn", */ },
	/*::[*/0x0877/*::]*/: { /* n:"List12", */ },
	/*::[*/0x0878/*::]*/: { /* n:"Feature12", */ },
	/*::[*/0x0879/*::]*/: { /* n:"CondFmt12", */ },
	/*::[*/0x087a/*::]*/: { /* n:"CF12", */ },
	/*::[*/0x087b/*::]*/: { /* n:"CFEx", */ },
	/*::[*/0x087c/*::]*/: { /* n:"XFCRC", */ f:parse_XFCRC, r:12 },
	/*::[*/0x087d/*::]*/: { /* n:"XFExt", */ f:parse_XFExt, r:12 },
	/*::[*/0x087e/*::]*/: { /* n:"AutoFilter12", */ },
	/*::[*/0x087f/*::]*/: { /* n:"ContinueFrt12", */ },
	/*::[*/0x0884/*::]*/: { /* n:"MDTInfo", */ },
	/*::[*/0x0885/*::]*/: { /* n:"MDXStr", */ },
	/*::[*/0x0886/*::]*/: { /* n:"MDXTuple", */ },
	/*::[*/0x0887/*::]*/: { /* n:"MDXSet", */ },
	/*::[*/0x0888/*::]*/: { /* n:"MDXProp", */ },
	/*::[*/0x0889/*::]*/: { /* n:"MDXKPI", */ },
	/*::[*/0x088a/*::]*/: { /* n:"MDB", */ },
	/*::[*/0x088b/*::]*/: { /* n:"PLV", */ },
	/*::[*/0x088c/*::]*/: { /* n:"Compat12", */ f:parsebool, r:12 },
	/*::[*/0x088d/*::]*/: { /* n:"DXF", */ },
	/*::[*/0x088e/*::]*/: { /* n:"TableStyles", */ r:12 },
	/*::[*/0x088f/*::]*/: { /* n:"TableStyle", */ },
	/*::[*/0x0890/*::]*/: { /* n:"TableStyleElement", */ },
	/*::[*/0x0892/*::]*/: { /* n:"StyleExt", */ },
	/*::[*/0x0893/*::]*/: { /* n:"NamePublish", */ },
	/*::[*/0x0894/*::]*/: { /* n:"NameCmt", */ f:parse_NameCmt, r:12 },
	/*::[*/0x0895/*::]*/: { /* n:"SortData", */ },
	/*::[*/0x0896/*::]*/: { /* n:"Theme", */ f:parse_Theme, r:12 },
	/*::[*/0x0897/*::]*/: { /* n:"GUIDTypeLib", */ },
	/*::[*/0x0898/*::]*/: { /* n:"FnGrp12", */ },
	/*::[*/0x0899/*::]*/: { /* n:"NameFnGrp12", */ },
	/*::[*/0x089a/*::]*/: { /* n:"MTRSettings", */ f:parse_MTRSettings, r:12 },
	/*::[*/0x089b/*::]*/: { /* n:"CompressPictures", */ f:parsenoop2 },
	/*::[*/0x089c/*::]*/: { /* n:"HeaderFooter", */ },
	/*::[*/0x089d/*::]*/: { /* n:"CrtLayout12", */ },
	/*::[*/0x089e/*::]*/: { /* n:"CrtMlFrt", */ },
	/*::[*/0x089f/*::]*/: { /* n:"CrtMlFrtContinue", */ },
	/*::[*/0x08a3/*::]*/: { /* n:"ForceFullCalculation", */ f:parse_ForceFullCalculation },
	/*::[*/0x08a4/*::]*/: { /* n:"ShapePropsStream", */ },
	/*::[*/0x08a5/*::]*/: { /* n:"TextPropsStream", */ },
	/*::[*/0x08a6/*::]*/: { /* n:"RichTextStream", */ },
	/*::[*/0x08a7/*::]*/: { /* n:"CrtLayout12A", */ },
	/*::[*/0x1001/*::]*/: { /* n:"Units", */ },
	/*::[*/0x1002/*::]*/: { /* n:"Chart", */ },
	/*::[*/0x1003/*::]*/: { /* n:"Series", */ },
	/*::[*/0x1006/*::]*/: { /* n:"DataFormat", */ },
	/*::[*/0x1007/*::]*/: { /* n:"LineFormat", */ },
	/*::[*/0x1009/*::]*/: { /* n:"MarkerFormat", */ },
	/*::[*/0x100a/*::]*/: { /* n:"AreaFormat", */ },
	/*::[*/0x100b/*::]*/: { /* n:"PieFormat", */ },
	/*::[*/0x100c/*::]*/: { /* n:"AttachedLabel", */ },
	/*::[*/0x100d/*::]*/: { /* n:"SeriesText", */ },
	/*::[*/0x1014/*::]*/: { /* n:"ChartFormat", */ },
	/*::[*/0x1015/*::]*/: { /* n:"Legend", */ },
	/*::[*/0x1016/*::]*/: { /* n:"SeriesList", */ },
	/*::[*/0x1017/*::]*/: { /* n:"Bar", */ },
	/*::[*/0x1018/*::]*/: { /* n:"Line", */ },
	/*::[*/0x1019/*::]*/: { /* n:"Pie", */ },
	/*::[*/0x101a/*::]*/: { /* n:"Area", */ },
	/*::[*/0x101b/*::]*/: { /* n:"Scatter", */ },
	/*::[*/0x101c/*::]*/: { /* n:"CrtLine", */ },
	/*::[*/0x101d/*::]*/: { /* n:"Axis", */ },
	/*::[*/0x101e/*::]*/: { /* n:"Tick", */ },
	/*::[*/0x101f/*::]*/: { /* n:"ValueRange", */ },
	/*::[*/0x1020/*::]*/: { /* n:"CatSerRange", */ },
	/*::[*/0x1021/*::]*/: { /* n:"AxisLine", */ },
	/*::[*/0x1022/*::]*/: { /* n:"CrtLink", */ },
	/*::[*/0x1024/*::]*/: { /* n:"DefaultText", */ },
	/*::[*/0x1025/*::]*/: { /* n:"Text", */ },
	/*::[*/0x1026/*::]*/: { /* n:"FontX", */ f:parseuint16 },
	/*::[*/0x1027/*::]*/: { /* n:"ObjectLink", */ },
	/*::[*/0x1032/*::]*/: { /* n:"Frame", */ },
	/*::[*/0x1033/*::]*/: { /* n:"Begin", */ },
	/*::[*/0x1034/*::]*/: { /* n:"End", */ },
	/*::[*/0x1035/*::]*/: { /* n:"PlotArea", */ },
	/*::[*/0x103a/*::]*/: { /* n:"Chart3d", */ },
	/*::[*/0x103c/*::]*/: { /* n:"PicF", */ },
	/*::[*/0x103d/*::]*/: { /* n:"DropBar", */ },
	/*::[*/0x103e/*::]*/: { /* n:"Radar", */ },
	/*::[*/0x103f/*::]*/: { /* n:"Surf", */ },
	/*::[*/0x1040/*::]*/: { /* n:"RadarArea", */ },
	/*::[*/0x1041/*::]*/: { /* n:"AxisParent", */ },
	/*::[*/0x1043/*::]*/: { /* n:"LegendException", */ },
	/*::[*/0x1044/*::]*/: { /* n:"ShtProps", */ f:parse_ShtProps },
	/*::[*/0x1045/*::]*/: { /* n:"SerToCrt", */ },
	/*::[*/0x1046/*::]*/: { /* n:"AxesUsed", */ },
	/*::[*/0x1048/*::]*/: { /* n:"SBaseRef", */ },
	/*::[*/0x104a/*::]*/: { /* n:"SerParent", */ },
	/*::[*/0x104b/*::]*/: { /* n:"SerAuxTrend", */ },
	/*::[*/0x104e/*::]*/: { /* n:"IFmtRecord", */ },
	/*::[*/0x104f/*::]*/: { /* n:"Pos", */ },
	/*::[*/0x1050/*::]*/: { /* n:"AlRuns", */ },
	/*::[*/0x1051/*::]*/: { /* n:"BRAI", */ },
	/*::[*/0x105b/*::]*/: { /* n:"SerAuxErrBar", */ },
	/*::[*/0x105c/*::]*/: { /* n:"ClrtClient", */ f:parse_ClrtClient },
	/*::[*/0x105d/*::]*/: { /* n:"SerFmt", */ },
	/*::[*/0x105f/*::]*/: { /* n:"Chart3DBarShape", */ },
	/*::[*/0x1060/*::]*/: { /* n:"Fbi", */ },
	/*::[*/0x1061/*::]*/: { /* n:"BopPop", */ },
	/*::[*/0x1062/*::]*/: { /* n:"AxcExt", */ },
	/*::[*/0x1063/*::]*/: { /* n:"Dat", */ },
	/*::[*/0x1064/*::]*/: { /* n:"PlotGrowth", */ },
	/*::[*/0x1065/*::]*/: { /* n:"SIIndex", */ },
	/*::[*/0x1066/*::]*/: { /* n:"GelFrame", */ },
	/*::[*/0x1067/*::]*/: { /* n:"BopPopCustom", */ },
	/*::[*/0x1068/*::]*/: { /* n:"Fbi2", */ },

	/*::[*/0x0000/*::]*/: { /* n:"Dimensions", */ f:parse_Dimensions },
	/*::[*/0x0001/*::]*/: { /* n:"BIFF2BLANK", */ },
	/*::[*/0x0002/*::]*/: { /* n:"BIFF2INT", */ f:parse_BIFF2INT },
	/*::[*/0x0003/*::]*/: { /* n:"BIFF2NUM", */ f:parse_BIFF2NUM },
	/*::[*/0x0004/*::]*/: { /* n:"BIFF2STR", */ f:parse_BIFF2STR },
	/*::[*/0x0005/*::]*/: { /* n:"BoolErr", */ f:parse_BoolErr },
	/*::[*/0x0007/*::]*/: { /* n:"String", */ f:parse_BIFF2STRING },
	/*::[*/0x0008/*::]*/: { /* n:"BIFF2ROW", */ },
	/*::[*/0x0009/*::]*/: { /* n:"BOF", */ f:parse_BOF },
	/*::[*/0x000b/*::]*/: { /* n:"Index", */ },
	/*::[*/0x0016/*::]*/: { /* n:"ExternCount", */ f:parseuint16 },
	/*::[*/0x001e/*::]*/: { /* n:"BIFF2FORMAT", */ f:parse_BIFF2Format },
	/*::[*/0x001f/*::]*/: { /* n:"BIFF2FMTCNT", */ }, /* 16-bit cnt of BIFF2FORMAT records */
	/*::[*/0x0020/*::]*/: { /* n:"BIFF2COLINFO", */ },
	/*::[*/0x0021/*::]*/: { /* n:"Array", */ f:parse_Array },
	/*::[*/0x0024/*::]*/: { /* n:"COLWIDTH", */ },
	/*::[*/0x0025/*::]*/: { /* n:"DefaultRowHeight", */ f:parse_DefaultRowHeight },
	// 0x2c ??
	// 0x2d ??
	// 0x2e ??
	// 0x30 FONTCOUNT: number of fonts
	/*::[*/0x0032/*::]*/: { /* n:"BIFF2FONTXTRA", */ f:parse_BIFF2FONTXTRA },
	// 0x35: INFOOPTS
	// 0x36: TABLE (BIFF2 only)
	// 0x37: TABLE2 (BIFF2 only)
	// 0x38: WNDESK
	// 0x39 ??
	// 0x3a: BEGINPREF
	// 0x3b: ENDPREF
	/*::[*/0x003e/*::]*/: { /* n:"BIFF2WINDOW2", */ },
	// 0x3f ??
	// 0x46: SHOWSCROLL
	// 0x47: SHOWFORMULA
	// 0x48: STATUSBAR
	// 0x49: SHORTMENUS
	// 0x4A:
	// 0x4B:
	// 0x4C:
	// 0x4E:
	// 0x4F:
	// 0x58: TOOLBAR (BIFF3)

	/* - - - */
	/*::[*/0x0034/*::]*/: { /* n:"DDEObjName", */ },
	/*::[*/0x0043/*::]*/: { /* n:"BIFF2XF", */ },
	/*::[*/0x0044/*::]*/: { /* n:"BIFF2XFINDEX", */ f:parseuint16 },
	/*::[*/0x0045/*::]*/: { /* n:"BIFF2FONTCLR", */ },
	/*::[*/0x0056/*::]*/: { /* n:"BIFF4FMTCNT", */ }, /* 16-bit cnt, similar to BIFF2 */
	/*::[*/0x007e/*::]*/: { /* n:"RK", */ }, /* Not necessarily same as 0x027e */
	/*::[*/0x007f/*::]*/: { /* n:"ImData", */ f:parse_ImData },
	/*::[*/0x0087/*::]*/: { /* n:"Addin", */ },
	/*::[*/0x0088/*::]*/: { /* n:"Edg", */ },
	/*::[*/0x0089/*::]*/: { /* n:"Pub", */ },
	// 0x8A
	// 0x8B LH: alternate menu key flag (BIFF3/4)
	// 0x8E
	// 0x8F
	/*::[*/0x0091/*::]*/: { /* n:"Sub", */ },
	// 0x93 STYLE
	/*::[*/0x0094/*::]*/: { /* n:"LHRecord", */ },
	/*::[*/0x0095/*::]*/: { /* n:"LHNGraph", */ },
	/*::[*/0x0096/*::]*/: { /* n:"Sound", */ },
	// 0xA2 FNPROTO: function prototypes (BIFF4)
	// 0xA3
	// 0xA8
	/*::[*/0x00a9/*::]*/: { /* n:"CoordList", */ },
	/*::[*/0x00ab/*::]*/: { /* n:"GCW", */ },
	/*::[*/0x00bc/*::]*/: { /* n:"ShrFmla", */ }, /* Not necessarily same as 0x04bc */
	/*::[*/0x00bf/*::]*/: { /* n:"ToolbarHdr", */ },
	/*::[*/0x00c0/*::]*/: { /* n:"ToolbarEnd", */ },
	/*::[*/0x00c2/*::]*/: { /* n:"AddMenu", */ },
	/*::[*/0x00c3/*::]*/: { /* n:"DelMenu", */ },
	/*::[*/0x00d6/*::]*/: { /* n:"RString", */ f:parse_RString },
	/*::[*/0x00df/*::]*/: { /* n:"UDDesc", */ },
	/*::[*/0x00ea/*::]*/: { /* n:"TabIdConf", */ },
	/*::[*/0x0162/*::]*/: { /* n:"XL5Modify", */ },
	/*::[*/0x01a5/*::]*/: { /* n:"FileSharing2", */ },
	/*::[*/0x0206/*::]*/: { /* n:"Formula", */ f:parse_Formula },
	/*::[*/0x0209/*::]*/: { /* n:"BOF", */ f:parse_BOF },
	/*::[*/0x0218/*::]*/: { /* n:"Lbl", */ f:parse_Lbl },
	/*::[*/0x0223/*::]*/: { /* n:"ExternName", */ f:parse_ExternName },
	/*::[*/0x0231/*::]*/: { /* n:"Font", */ },
	/*::[*/0x0243/*::]*/: { /* n:"BIFF3XF", */ },
	/*::[*/0x0406/*::]*/: { /* n:"Formula", */ f:parse_Formula },
	/*::[*/0x0409/*::]*/: { /* n:"BOF", */ f:parse_BOF },
	/*::[*/0x0443/*::]*/: { /* n:"BIFF4XF", */ },
	/*::[*/0x086d/*::]*/: { /* n:"FeatInfo", */ },
	/*::[*/0x0873/*::]*/: { /* n:"FeatInfo11", */ },
	/*::[*/0x0881/*::]*/: { /* n:"SXAddl12", */ },
	/*::[*/0x08c0/*::]*/: { /* n:"AutoWebPub", */ },
	/*::[*/0x08c1/*::]*/: { /* n:"ListObj", */ },
	/*::[*/0x08c2/*::]*/: { /* n:"ListField", */ },
	/*::[*/0x08c3/*::]*/: { /* n:"ListDV", */ },
	/*::[*/0x08c4/*::]*/: { /* n:"ListCondFmt", */ },
	/*::[*/0x08c5/*::]*/: { /* n:"ListCF", */ },
	/*::[*/0x08c6/*::]*/: { /* n:"FMQry", */ },
	/*::[*/0x08c7/*::]*/: { /* n:"FMSQry", */ },
	/*::[*/0x08c8/*::]*/: { /* n:"PLV", */ },
	/*::[*/0x08c9/*::]*/: { /* n:"LnExt", */ },
	/*::[*/0x08ca/*::]*/: { /* n:"MkrExt", */ },
	/*::[*/0x08cb/*::]*/: { /* n:"CrtCoopt", */ },
	/*::[*/0x08d6/*::]*/: { /* n:"FRTArchId$", */ r:12 },

	/*::[*/0x7262/*::]*/: {}
};

function write_biff_rec(ba/*:BufArray*/, type/*:number*/, payload, length/*:?number*/)/*:void*/ {
	var t/*:number*/ = type;
	if(isNaN(t)) return;
	var len = length || (payload||[]).length || 0;
	var o = ba.next(4);
	o.write_shift(2, t);
	o.write_shift(2, len);
	if(/*:: len != null &&*/len > 0 && is_buf(payload)) ba.push(payload);
}

function write_biff_continue(ba/*:BufArray*/, type/*:number*/, payload, length/*:?number*/)/*:void*/ {
	var len = length || (payload||[]).length || 0;
	if(len <= 8224) return write_biff_rec(ba, type, payload, len);
	var t = type;
	if(isNaN(t)) return;
	var parts = payload.parts || [], sidx = 0;
	var i = 0, w = 0;
	while(w + (parts[sidx] || 8224) <= 8224) { w+= (parts[sidx] || 8224); sidx++; }
	var o = ba.next(4);
	o.write_shift(2, t);
	o.write_shift(2, w);
	ba.push(payload.slice(i, i + w));
	i += w;
	while(i < len) {
		o = ba.next(4);
		o.write_shift(2, 0x3c); // TODO: figure out correct continue type
		w = 0;
		while(w + (parts[sidx] || 8224) <= 8224) { w+= (parts[sidx] || 8224); sidx++; }
		o.write_shift(2, w);
		ba.push(payload.slice(i, i+w)); i+= w;
	}
}

function write_BIFF2Cell(out, r/*:number*/, c/*:number*/) {
	if(!out) out = new_buf(7);
	out.write_shift(2, r);
	out.write_shift(2, c);
	out.write_shift(2, 0);
	out.write_shift(1, 0);
	return out;
}

function write_BIFF2BERR(r/*:number*/, c/*:number*/, val, t/*:?string*/) {
	var out = new_buf(9);
	write_BIFF2Cell(out, r, c);
	write_Bes(val, t || 'b', out);
	return out;
}

/* TODO: codepage, large strings */
function write_BIFF2LABEL(r/*:number*/, c/*:number*/, val) {
	var out = new_buf(8 + 2*val.length);
	write_BIFF2Cell(out, r, c);
	out.write_shift(1, val.length);
	out.write_shift(val.length, val, 'sbcs');
	return out.l < out.length ? out.slice(0, out.l) : out;
}

function write_ws_biff2_cell(ba/*:BufArray*/, cell/*:Cell*/, R/*:number*/, C/*:number*//*::, opts*/) {
	if(cell.v != null) switch(cell.t) {
		case 'd': case 'n':
			var v = cell.t == 'd' ? datenum(parseDate(cell.v)) : cell.v;
			if((v == (v|0)) && (v >= 0) && (v < 65536))
				write_biff_rec(ba, 0x0002, write_BIFF2INT(R, C, v));
			else
				write_biff_rec(ba, 0x0003, write_BIFF2NUM(R,C, v));
			return;
		case 'b': case 'e': write_biff_rec(ba, 0x0005, write_BIFF2BERR(R, C, cell.v, cell.t)); return;
		/* TODO: codepage, sst */
		case 's': case 'str':
			write_biff_rec(ba, 0x0004, write_BIFF2LABEL(R, C, (cell.v||"").slice(0,255)));
			return;
	}
	write_biff_rec(ba, 0x0001, write_BIFF2Cell(null, R, C));
}

function write_ws_biff2(ba/*:BufArray*/, ws/*:Worksheet*/, idx/*:number*/, opts/*::, wb:Workbook*/) {
	var dense = Array.isArray(ws);
	var range = safe_decode_range(ws['!ref'] || "A1"), ref/*:string*/, rr = "", cols/*:Array<string>*/ = [];
	if(range.e.c > 0xFF || range.e.r > 0x3FFF) {
		if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
		range.e.c = Math.min(range.e.c, 0xFF);
		range.e.r = Math.min(range.e.c, 0x3FFF);
		ref = encode_range(range);
	}
	for(var R = range.s.r; R <= range.e.r; ++R) {
		rr = encode_row(R);
		for(var C = range.s.c; C <= range.e.c; ++C) {
			if(R === range.s.r) cols[C] = encode_col(C);
			ref = cols[C] + rr;
			var cell = dense ? (ws[R]||[])[C] : ws[ref];
			if(!cell) continue;
			/* write cell */
			write_ws_biff2_cell(ba, cell, R, C, opts);
		}
	}
}

/* Based on test files */
function write_biff2_buf(wb/*:Workbook*/, opts/*:WriteOpts*/) {
	var o = opts || {};
	if(DENSE != null && o.dense == null) o.dense = DENSE;
	var ba = buf_array();
	var idx = 0;
	for(var i=0;i<wb.SheetNames.length;++i) if(wb.SheetNames[i] == o.sheet) idx=i;
	if(idx == 0 && !!o.sheet && wb.SheetNames[0] != o.sheet) throw new Error("Sheet not found: " + o.sheet);
	write_biff_rec(ba, (o.biff == 4 ? 0x0409 : (o.biff == 3 ? 0x0209 : 0x0009)), write_BOF(wb, 0x10, o));
	/* ... */
	write_ws_biff2(ba, wb.Sheets[wb.SheetNames[idx]], idx, o, wb);
	/* ... */
	write_biff_rec(ba, 0x000A);
	return ba.end();
}

function write_FONTS_biff8(ba, data, opts) {
	write_biff_rec(ba, 0x0031 /* Font */, write_Font({
		sz:12,
		color: {theme:1},
		name: "Arial",
		family: 2,
		scheme: "minor"
	}, opts));
}


function write_FMTS_biff8(ba, NF/*:?SSFTable*/, opts) {
	if(!NF) return;
	[[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
		/*:: if(!NF) return; */
		for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) write_biff_rec(ba, 0x041E /* Format */, write_Format(i, NF[i], opts));
	});
}

function write_FEAT(ba, ws) {
	/* [MS-XLS] 2.4.112 */
	var o = new_buf(19);
	o.write_shift(4, 0x867); o.write_shift(4, 0); o.write_shift(4, 0);
	o.write_shift(2, 3); o.write_shift(1, 1); o.write_shift(4, 0);
	write_biff_rec(ba, 0x0867 /* FeatHdr */, o);
	/* [MS-XLS] 2.4.111 */
	o = new_buf(39);
	o.write_shift(4, 0x868); o.write_shift(4, 0); o.write_shift(4, 0);
	o.write_shift(2, 3); o.write_shift(1, 0); o.write_shift(4, 0);
	o.write_shift(2, 1); o.write_shift(4, 4); o.write_shift(2, 0);
	write_Ref8U(safe_decode_range(ws['!ref']||"A1"), o);
	o.write_shift(4, 4);
	write_biff_rec(ba, 0x0868 /* Feat */, o);
}

function write_CELLXFS_biff8(ba, opts) {
	for(var i = 0; i < 16; ++i) write_biff_rec(ba, 0x00e0 /* XF */, write_XF({numFmtId:0, style:true}, 0, opts));
	opts.cellXfs.forEach(function(c) {
		write_biff_rec(ba, 0x00e0 /* XF */, write_XF(c, 0, opts));
	});
}

function write_ws_biff8_hlinks(ba/*:BufArray*/, ws) {
	for(var R=0; R<ws['!links'].length; ++R) {
		var HL = ws['!links'][R];
		write_biff_rec(ba, 0x01b8 /* HLink */, write_HLink(HL));
		if(HL[1].Tooltip) write_biff_rec(ba, 0x0800 /* HLinkTooltip */, write_HLinkTooltip(HL));
	}
	delete ws['!links'];
}

function write_ws_cols_biff8(ba, cols) {
	if(!cols) return;
	var cnt = 0;
	cols.forEach(function(col, idx) {
		if(++cnt <= 256 && col) {
			write_biff_rec(ba, 0x007d /* ColInfo */, write_ColInfo(col_obj_w(idx, col), idx));
		}
	});
}

function write_ws_biff8_cell(ba/*:BufArray*/, cell/*:Cell*/, R/*:number*/, C/*:number*/, opts) {
	var os = 16 + get_cell_style(opts.cellXfs, cell, opts);
	if(cell.v == null && !cell.bf) {
		write_biff_rec(ba, 0x0201 /* Blank */, write_XLSCell(R, C, os));
		return;
	}
	if(cell.bf) write_biff_rec(ba, 0x0006 /* Formula */, write_Formula(cell, R, C, opts, os));
	else switch(cell.t) {
		case 'd': case 'n':
			var v = cell.t == 'd' ? datenum(parseDate(cell.v)) : cell.v;
			/* TODO: emit RK as appropriate */
			write_biff_rec(ba, 0x0203 /* Number */, write_Number(R, C, v, os, opts));
			break;
		case 'b': case 'e':
			write_biff_rec(ba, 0x0205 /* BoolErr */, write_BoolErr(R, C, cell.v, os, opts, cell.t));
			break;
		/* TODO: codepage, sst */
		case 's': case 'str':
			if(opts.bookSST) {
				var isst = get_sst_id(opts.Strings, cell.v, opts.revStrings);
				write_biff_rec(ba, 0x00fd /* LabelSst */, write_LabelSst(R, C, isst, os, opts));
			} else write_biff_rec(ba, 0x0204 /* Label */, write_Label(R, C, (cell.v||"").slice(0,255), os, opts));
			break;
		default:
			write_biff_rec(ba, 0x0201 /* Blank */, write_XLSCell(R, C, os));
	}
}

/* [MS-XLS] 2.1.7.20.5 */
function write_ws_biff8(idx/*:number*/, opts, wb/*:Workbook*/) {
	var ba = buf_array();
	var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
	var _WB/*:WBWBProps*/ = ((wb||{}).Workbook||{}/*:any*/);
	var _sheet/*:WBWSProp*/ = ((_WB.Sheets||[])[idx]||{}/*:any*/);
	var dense = Array.isArray(ws);
	var b8 = opts.biff == 8;
	var ref/*:string*/, rr = "", cols/*:Array<string>*/ = [];
	var range = safe_decode_range(ws['!ref'] || "A1");
	var MAX_ROWS = b8 ? 65536 : 16384;
	if(range.e.c > 0xFF || range.e.r >= MAX_ROWS) {
		if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
		range.e.c = Math.min(range.e.c, 0xFF);
		range.e.r = Math.min(range.e.c, MAX_ROWS-1);
	}

	write_biff_rec(ba, 0x0809, write_BOF(wb, 0x10, opts));
	/* [Uncalced] Index */
	write_biff_rec(ba, 0x000d /* CalcMode */, writeuint16(1));
	write_biff_rec(ba, 0x000c /* CalcCount */, writeuint16(100));
	write_biff_rec(ba, 0x000f /* CalcRefMode */, writebool(true));
	write_biff_rec(ba, 0x0011 /* CalcIter */, writebool(false));
	write_biff_rec(ba, 0x0010 /* CalcDelta */, write_Xnum(0.001));
	write_biff_rec(ba, 0x005f /* CalcSaveRecalc */, writebool(true));
	write_biff_rec(ba, 0x002a /* PrintRowCol */, writebool(false));
	write_biff_rec(ba, 0x002b /* PrintGrid */, writebool(false));
	write_biff_rec(ba, 0x0082 /* GridSet */, writeuint16(1));
	write_biff_rec(ba, 0x0080 /* Guts */, write_Guts([0,0]));
	/* DefaultRowHeight WsBool [Sync] [LPr] [HorizontalPageBreaks] [VerticalPageBreaks] */
	/* Header (string) */
	/* Footer (string) */
	write_biff_rec(ba, 0x0083 /* HCenter */, writebool(false));
	write_biff_rec(ba, 0x0084 /* VCenter */, writebool(false));
	/* ... */
	if(b8) write_ws_cols_biff8(ba, ws["!cols"]);
	/* ... */
	write_biff_rec(ba, 0x200, write_Dimensions(range, opts));
	/* ... */

	if(b8) ws['!links'] = [];
	for(var R = range.s.r; R <= range.e.r; ++R) {
		rr = encode_row(R);
		for(var C = range.s.c; C <= range.e.c; ++C) {
			if(R === range.s.r) cols[C] = encode_col(C);
			ref = cols[C] + rr;
			var cell = dense ? (ws[R]||[])[C] : ws[ref];
			if(!cell) continue;
			/* write cell */
			write_ws_biff8_cell(ba, cell, R, C, opts);
			if(b8 && cell.l) ws['!links'].push([ref, cell.l]);
		}
	}
	var cname/*:string*/ = _sheet.CodeName || _sheet.name || s;
	/* ... */
	if(b8) write_biff_rec(ba, 0x023e /* Window2 */, write_Window2((_WB.Views||[])[0]));
	/* ... */
	if(b8 && (ws['!merges']||[]).length) write_biff_rec(ba, 0x00e5 /* MergeCells */, write_MergeCells(ws['!merges']));
	/* [LRng] *QUERYTABLE [PHONETICINFO] CONDFMTS */
	if(b8) write_ws_biff8_hlinks(ba, ws);
	/* [DVAL] */
	write_biff_rec(ba, 0x01ba /* CodeName */, write_XLUnicodeString(cname, opts));
	/* *WebPub *CellWatch [SheetExt] */
	if(b8) write_FEAT(ba, ws);
	/* *FEAT11 *RECORD12 */
	write_biff_rec(ba, 0x000a /* EOF */);
	return ba.end();
}

/* [MS-XLS] 2.1.7.20.3 */
function write_biff8_global(wb/*:Workbook*/, bufs, opts/*:WriteOpts*/) {
	var A = buf_array();
	var _WB/*:WBWBProps*/ = ((wb||{}).Workbook||{}/*:any*/);
	var _sheets/*:Array<WBWSProp>*/ = (_WB.Sheets||[]);
	var _wb/*:WBProps*/ = /*::((*/_WB.WBProps||{/*::CodeName:"ThisWorkbook"*/}/*:: ):any)*/;
	var b8 = opts.biff == 8, b5 = opts.biff == 5;
	write_biff_rec(A, 0x0809, write_BOF(wb, 0x05, opts));
	if(opts.bookType == "xla") write_biff_rec(A, 0x0087 /* Addin */);
	write_biff_rec(A, 0x00e1 /* InterfaceHdr */, b8 ? writeuint16(0x04b0) : null);
	write_biff_rec(A, 0x00c1 /* Mms */, writezeroes(2));
	if(b5) write_biff_rec(A, 0x00bf /* ToolbarHdr */);
	if(b5) write_biff_rec(A, 0x00c0 /* ToolbarEnd */);
	write_biff_rec(A, 0x00e2 /* InterfaceEnd */);
	write_biff_rec(A, 0x005c /* WriteAccess */, write_WriteAccess("SheetJS", opts));
	/* [FileSharing] */
	write_biff_rec(A, 0x0042 /* CodePage */, writeuint16(b8 ? 0x04b0 : 0x04E4));
	/* *2047 Lel */
	if(b8) write_biff_rec(A, 0x0161 /* DSF */, writeuint16(0));
	if(b8) write_biff_rec(A, 0x01c0 /* Excel9File */);
	write_biff_rec(A, 0x013d /* RRTabId */, write_RRTabId(wb.SheetNames.length));
	if(b8 && wb.vbaraw) write_biff_rec(A, 0x00d3 /* ObProj */);
	/* [ObNoMacros] */
	if(b8 && wb.vbaraw) {
		var cname/*:string*/ = _wb.CodeName || "ThisWorkbook";
		write_biff_rec(A, 0x01ba /* CodeName */, write_XLUnicodeString(cname, opts));
	}
	write_biff_rec(A, 0x009c /* BuiltInFnGroupCount */, writeuint16(0x11));
	/* *FnGroupName *FnGrp12 */
	/* *Lbl */
	/* [OleObjectSize] */
	write_biff_rec(A, 0x0019 /* WinProtect */, writebool(false));
	write_biff_rec(A, 0x0012 /* Protect */, writebool(false));
	write_biff_rec(A, 0x0013 /* Password */, writeuint16(0));
	if(b8) write_biff_rec(A, 0x01af /* Prot4Rev */, writebool(false));
	if(b8) write_biff_rec(A, 0x01bc /* Prot4RevPass */, writeuint16(0));
	write_biff_rec(A, 0x003d /* Window1 */, write_Window1(opts));
	write_biff_rec(A, 0x0040 /* Backup */, writebool(false));
	write_biff_rec(A, 0x008d /* HideObj */, writeuint16(0));
	write_biff_rec(A, 0x0022 /* Date1904 */, writebool(safe1904(wb)=="true"));
	write_biff_rec(A, 0x000e /* CalcPrecision */, writebool(true));
	if(b8) write_biff_rec(A, 0x01b7 /* RefreshAll */, writebool(false));
	write_biff_rec(A, 0x00DA /* BookBool */, writeuint16(0));
	/* ... */
	write_FONTS_biff8(A, wb, opts);
	write_FMTS_biff8(A, wb.SSF, opts);
	write_CELLXFS_biff8(A, opts);
	/* ... */
	if(b8) write_biff_rec(A, 0x0160 /* UsesELFs */, writebool(false));
	var a = A.end();

	var C = buf_array();
	/* METADATA [MTRSettings] [ForceFullCalculation] */
	if(b8) write_biff_rec(C, 0x008C, write_Country());
	/* *SUPBOOK *LBL *RTD [RecalcId] *HFPicture *MSODRAWINGGROUP */

	/* BIFF8: [SST *Continue] ExtSST */
	if(b8 && opts.Strings) write_biff_continue(C, 0x00FC, write_SST(opts.Strings, opts));

	/* *WebPub [WOpt] [CrErr] [BookExt] *FeatHdr *DConn [THEME] [CompressPictures] [Compat12] [GUIDTypeLib] */
	write_biff_rec(C, 0x000A /* EOF */);
	var c = C.end();

	var B = buf_array();
	var blen = 0, j = 0;
	for(j = 0; j < wb.SheetNames.length; ++j) blen += (b8 ? 12 : 11) + (b8 ? 2 : 1) * wb.SheetNames[j].length;
	var start = a.length + blen + c.length;
	for(j = 0; j < wb.SheetNames.length; ++j) {
		var _sheet/*:WBWSProp*/ = _sheets[j] || ({}/*:any*/);
		write_biff_rec(B, 0x0085 /* BoundSheet8 */, write_BoundSheet8({pos:start, hs:_sheet.Hidden||0, dt:0, name:wb.SheetNames[j]}, opts));
		start += bufs[j].length;
	}
	/* 1*BoundSheet8 */
	var b = B.end();
	if(blen != b.length) throw new Error("BS8 " + blen + " != " + b.length);

	var out = [];
	if(a.length) out.push(a);
	if(b.length) out.push(b);
	if(c.length) out.push(c);
	return bconcat(out);
}

/* [MS-XLS] 2.1.7.20 Workbook Stream */
function write_biff8_buf(wb/*:Workbook*/, opts/*:WriteOpts*/) {
	var o = opts || {};
	var bufs = [];

	if(wb && !wb.SSF) {
		wb.SSF = dup(table_fmt);
	}
	if(wb && wb.SSF) {
		make_ssf(); SSF_load_table(wb.SSF);
		// $FlowIgnore
		o.revssf = evert_num(wb.SSF); o.revssf[wb.SSF[65535]] = 0;
		o.ssf = wb.SSF;
	}

	o.Strings = /*::((*/[]/*:: :any):SST)*/; o.Strings.Count = 0; o.Strings.Unique = 0;
	fix_write_opts(o);

	o.cellXfs = [];
	get_cell_style(o.cellXfs, {}, {revssf:{"General":0}});

	if(!wb.Props) wb.Props = {};

	for(var i = 0; i < wb.SheetNames.length; ++i) bufs[bufs.length] = write_ws_biff8(i, o, wb);
	bufs.unshift(write_biff8_global(wb, bufs, o));
	return bconcat(bufs);
}

function write_biff_buf(wb/*:Workbook*/, opts/*:WriteOpts*/) {
	for(var i = 0; i <= wb.SheetNames.length; ++i) {
		var ws = wb.Sheets[wb.SheetNames[i]];
		if(!ws || !ws["!ref"]) continue;
		var range = decode_range(ws["!ref"]);
		if(range.e.c > 255) { // note: 255 is IV
		if(typeof console != "undefined" && console.error) console.error("Worksheet '" + wb.SheetNames[i] + "' extends beyond column IV (255).  Data may be lost.");
		}
	}

	var o = opts || {};
	switch(o.biff || 2) {
		case 8: case 5: return write_biff8_buf(wb, opts);
		case 4: case 3: case 2: return write_biff2_buf(wb, opts);
	}
	throw new Error("invalid type " + o.bookType + " for BIFF");
}
/* note: browser DOM element cannot see mso- style attrs, must parse */
function html_to_sheet(str/*:string*/, _opts)/*:Workbook*/ {
	var opts = _opts || {};
	if(DENSE != null && opts.dense == null) opts.dense = DENSE;
	var ws/*:Worksheet*/ = opts.dense ? ([]/*:any*/) : ({}/*:any*/);
	str = str.replace(/<!--.*?-->/g, "");
	var mtch/*:any*/ = str.match(/<table/i);
	if(!mtch) throw new Error("Invalid HTML: could not find <table>");
	var mtch2/*:any*/ = str.match(/<\/table/i);
	var i/*:number*/ = mtch.index, j/*:number*/ = mtch2 && mtch2.index || str.length;
	var rows = split_regex(str.slice(i, j), /(:?<tr[^>]*>)/i, "<tr>");
	var R = -1, C = 0, RS = 0, CS = 0;
	var range/*:Range*/ = {s:{r:10000000, c:10000000},e:{r:0,c:0}};
	var merges/*:Array<Range>*/ = [];
	for(i = 0; i < rows.length; ++i) {
		var row = rows[i].trim();
		var hd = row.slice(0,3).toLowerCase();
		if(hd == "<tr") { ++R; if(opts.sheetRows && opts.sheetRows <= R) { --R; break; } C = 0; continue; }
		if(hd != "<td" && hd != "<th") continue;
		var cells = row.split(/<\/t[dh]>/i);
		for(j = 0; j < cells.length; ++j) {
			var cell = cells[j].trim();
			if(!cell.match(/<t[dh]/i)) continue;
			var m = cell, cc = 0;
			/* TODO: parse styles etc */
			while(m.charAt(0) == "<" && (cc = m.indexOf(">")) > -1) m = m.slice(cc+1);
			for(var midx = 0; midx < merges.length; ++midx) {
				var _merge/*:Range*/ = merges[midx];
				if(_merge.s.c == C && _merge.s.r < R && R <= _merge.e.r) { C = _merge.e.c + 1; midx = -1; }
			}
			var tag = parsexmltag(cell.slice(0, cell.indexOf(">")));
			CS = tag.colspan ? +tag.colspan : 1;
			if((RS = +tag.rowspan)>1 || CS>1) merges.push({s:{r:R,c:C},e:{r:R + (RS||1) - 1, c:C + CS - 1}});
			var _t/*:string*/ = tag.t || tag["data-t"] || "";
			/* TODO: generate stub cells */
			if(!m.length) { C += CS; continue; }
			m = htmldecode(m);
			if(range.s.r > R) range.s.r = R; if(range.e.r < R) range.e.r = R;
			if(range.s.c > C) range.s.c = C; if(range.e.c < C) range.e.c = C;
			if(!m.length) { C += CS; continue; }
			var o/*:Cell*/ = {t:'s', v:m};
			if(opts.raw || !m.trim().length || _t == 's'){}
			else if(m === 'TRUE') o = {t:'b', v:true};
			else if(m === 'FALSE') o = {t:'b', v:false};
			else if(!isNaN(fuzzynum(m))) o = {t:'n', v:fuzzynum(m)};
			else if(!isNaN(fuzzydate(m).getDate())) {
				o = ({t:'d', v:parseDate(m)}/*:any*/);
				if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)}/*:any*/);
				o.z = opts.dateNF || table_fmt[14];
			}
			if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = o; }
			else ws[encode_cell({r:R, c:C})] = o;
			C += CS;
		}
	}
	ws['!ref'] = encode_range(range);
	if(merges.length) ws["!merges"] = merges;
	return ws;
}
function make_html_row(ws/*:Worksheet*/, r/*:Range*/, R/*:number*/, o/*:Sheet2HTMLOpts*/)/*:string*/ {
	var M/*:Array<Range>*/ = (ws['!merges'] ||[]);
	var oo/*:Array<string>*/ = [];
	for(var C = r.s.c; C <= r.e.c; ++C) {
		var RS = 0, CS = 0;
		for(var j = 0; j < M.length; ++j) {
			if(M[j].s.r > R || M[j].s.c > C) continue;
			if(M[j].e.r < R || M[j].e.c < C) continue;
			if(M[j].s.r < R || M[j].s.c < C) { RS = -1; break; }
			RS = M[j].e.r - M[j].s.r + 1; CS = M[j].e.c - M[j].s.c + 1; break;
		}
		if(RS < 0) continue;
		var coord = encode_cell({r:R,c:C});
		var cell = o.dense ? (ws[R]||[])[C] : ws[coord];
		/* TODO: html entities */
		var w = (cell && cell.v != null) && (cell.h || escapehtml(cell.w || (format_cell(cell), cell.w) || "")) || "";
		var sp = ({}/*:any*/);
		if(RS > 1) sp.rowspan = RS;
		if(CS > 1) sp.colspan = CS;
		if(o.editable) w = '<span contenteditable="true">' + w + '</span>';
		else if(cell) {
			sp["data-t"] = cell && cell.t || 'z';
			if(cell.v != null) sp["data-v"] = cell.v;
			if(cell.z != null) sp["data-z"] = cell.z;
			if(cell.l && (cell.l.Target || "#").charAt(0) != "#") w = '<a href="' + cell.l.Target +'">' + w + '</a>';
		}
		sp.id = (o.id || "sjs") + "-" + coord;
		oo.push(writextag('td', w, sp));
	}
	var preamble = "<tr>";
	return preamble + oo.join("") + "</tr>";
}

var HTML_BEGIN = '<html><head><meta charset="utf-8"/><title>SheetJS Table Export</title></head><body>';
var HTML_END = '</body></html>';

function html_to_workbook(str/*:string*/, opts)/*:Workbook*/ {
	var mtch = str.match(/<table[\s\S]*?>[\s\S]*?<\/table>/gi);
	if(!mtch || mtch.length == 0) throw new Error("Invalid HTML: could not find <table>");
	if(mtch.length == 1) return sheet_to_workbook(html_to_sheet(mtch[0], opts), opts);
	var wb = book_new();
	mtch.forEach(function(s, idx) { book_append_sheet(wb, html_to_sheet(s, opts), "Sheet" + (idx+1)); });
	return wb;
}

function make_html_preamble(ws/*:Worksheet*/, R/*:Range*/, o/*:Sheet2HTMLOpts*/)/*:string*/ {
	var out/*:Array<string>*/ = [];
	return out.join("") + '<table' + (o && o.id ? ' id="' + o.id + '"' : "") + '>';
}

function sheet_to_html(ws/*:Worksheet*/, opts/*:?Sheet2HTMLOpts*//*, wb:?Workbook*/)/*:string*/ {
	var o = opts || {};
	var header = o.header != null ? o.header : HTML_BEGIN;
	var footer = o.footer != null ? o.footer : HTML_END;
	var out/*:Array<string>*/ = [header];
	var r = decode_range(ws['!ref']);
	o.dense = Array.isArray(ws);
	out.push(make_html_preamble(ws, r, o));
	for(var R = r.s.r; R <= r.e.r; ++R) out.push(make_html_row(ws, r, R, o));
	out.push("</table>" + footer);
	return out.join("");
}

function sheet_add_dom(ws/*:Worksheet*/, table/*:HTMLElement*/, _opts/*:?any*/)/*:Worksheet*/ {
	var opts = _opts || {};
	if(DENSE != null) opts.dense = DENSE;
	var or_R = 0, or_C = 0;
	if(opts.origin != null) {
		if(typeof opts.origin == 'number') or_R = opts.origin;
		else {
			var _origin/*:CellAddress*/ = typeof opts.origin == "string" ? decode_cell(opts.origin) : opts.origin;
			or_R = _origin.r; or_C = _origin.c;
		}
	}

	var rows/*:HTMLCollection<HTMLTableRowElement>*/ = table.getElementsByTagName('tr');
	var sheetRows = Math.min(opts.sheetRows||10000000, rows.length);
	var range/*:Range*/ = {s:{r:0,c:0},e:{r:or_R,c:or_C}};
	if(ws["!ref"]) {
		var _range/*:Range*/ = decode_range(ws["!ref"]);
		range.s.r = Math.min(range.s.r, _range.s.r);
		range.s.c = Math.min(range.s.c, _range.s.c);
		range.e.r = Math.max(range.e.r, _range.e.r);
		range.e.c = Math.max(range.e.c, _range.e.c);
		if(or_R == -1) range.e.r = or_R = _range.e.r + 1;
	}
	var merges/*:Array<Range>*/ = [], midx = 0;
	var rowinfo/*:Array<RowInfo>*/ = ws["!rows"] || (ws["!rows"] = []);
	var _R = 0, R = 0, _C = 0, C = 0, RS = 0, CS = 0;
	if(!ws["!cols"]) ws['!cols'] = [];
	for(; _R < rows.length && R < sheetRows; ++_R) {
		var row/*:HTMLTableRowElement*/ = rows[_R];
		if (is_dom_element_hidden(row)) {
			if (opts.display) continue;
			rowinfo[R] = {hidden: true};
		}
		var elts/*:HTMLCollection<HTMLTableCellElement>*/ = (row.children/*:any*/);
		for(_C = C = 0; _C < elts.length; ++_C) {
			var elt/*:HTMLTableCellElement*/ = elts[_C];
			if (opts.display && is_dom_element_hidden(elt)) continue;
			var v/*:?string*/ = elt.hasAttribute('data-v') ? elt.getAttribute('data-v') : elt.hasAttribute('v') ? elt.getAttribute('v') : htmldecode(elt.innerHTML);
			var z/*:?string*/ = elt.getAttribute('data-z') || elt.getAttribute('z');
			for(midx = 0; midx < merges.length; ++midx) {
				var m/*:Range*/ = merges[midx];
				if(m.s.c == C + or_C && m.s.r < R + or_R && R + or_R <= m.e.r) { C = m.e.c+1 - or_C; midx = -1; }
			}
			/* TODO: figure out how to extract nonstandard mso- style */
			CS = +elt.getAttribute("colspan") || 1;
			if( ((RS = (+elt.getAttribute("rowspan") || 1)))>1 || CS>1) merges.push({s:{r:R + or_R,c:C + or_C},e:{r:R + or_R + (RS||1) - 1, c:C + or_C + (CS||1) - 1}});
			var o/*:Cell*/ = {t:'s', v:v};
			var _t/*:string*/ = elt.getAttribute("data-t") || elt.getAttribute("t") || "";
			if(v != null) {
				if(v.length == 0) o.t = _t || 'z';
				else if(opts.raw || v.trim().length == 0 || _t == "s"){}
				else if(v === 'TRUE') o = {t:'b', v:true};
				else if(v === 'FALSE') o = {t:'b', v:false};
				else if(!isNaN(fuzzynum(v))) o = {t:'n', v:fuzzynum(v)};
				else if(!isNaN(fuzzydate(v).getDate())) {
					o = ({t:'d', v:parseDate(v)}/*:any*/);
					if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)}/*:any*/);
					o.z = opts.dateNF || table_fmt[14];
				}
			}
			if(o.z === undefined && z != null) o.z = z;
			/* The first link is used.  Links are assumed to be fully specified.
			 * TODO: The right way to process relative links is to make a new <a> */
			var l = "", Aelts = elt.getElementsByTagName("A");
			if(Aelts && Aelts.length) for(var Aelti = 0; Aelti < Aelts.length; ++Aelti)	if(Aelts[Aelti].hasAttribute("href")) {
				l = Aelts[Aelti].getAttribute("href"); if(l.charAt(0) != "#") break;
			}
			if(l && l.charAt(0) != "#") o.l = ({ Target: l });
			if(opts.dense) { if(!ws[R + or_R]) ws[R + or_R] = []; ws[R + or_R][C + or_C] = o; }
			else ws[encode_cell({c:C + or_C, r:R + or_R})] = o;
			if(range.e.c < C + or_C) range.e.c = C + or_C;
			C += CS;
		}
		++R;
	}
	if(merges.length) ws['!merges'] = (ws["!merges"] || []).concat(merges);
	range.e.r = Math.max(range.e.r, R - 1 + or_R);
	ws['!ref'] = encode_range(range);
	if(R >= sheetRows) ws['!fullref'] = encode_range((range.e.r = rows.length-_R+R-1 + or_R,range)); // We can count the real number of rows to parse but we don't to improve the performance
	return ws;
}

function parse_dom_table(table/*:HTMLElement*/, _opts/*:?any*/)/*:Worksheet*/ {
	var opts = _opts || {};
	var ws/*:Worksheet*/ = opts.dense ? ([]/*:any*/) : ({}/*:any*/);
	return sheet_add_dom(ws, table, _opts);
}

function table_to_book(table/*:HTMLElement*/, opts/*:?any*/)/*:Workbook*/ {
	return sheet_to_workbook(parse_dom_table(table, opts), opts);
}

function is_dom_element_hidden(element/*:HTMLElement*/)/*:boolean*/ {
	var display/*:string*/ = '';
	var get_computed_style/*:?function*/ = get_get_computed_style_function(element);
	if(get_computed_style) display = get_computed_style(element).getPropertyValue('display');
	if(!display) display = element.style && element.style.display;
	return display === 'none';
}

/* global getComputedStyle */
function get_get_computed_style_function(element/*:HTMLElement*/)/*:?function*/ {
	// The proper getComputedStyle implementation is the one defined in the element window
	if(element.ownerDocument.defaultView && typeof element.ownerDocument.defaultView.getComputedStyle === 'function') return element.ownerDocument.defaultView.getComputedStyle;
	// If it is not available, try to get one from the global namespace
	if(typeof getComputedStyle === 'function') return getComputedStyle;
	return null;
}
/* OpenDocument */
function parse_text_p(text/*:string*//*::, tag*/)/*:Array<any>*/ {
	/* 6.1.2 White Space Characters */
	var fixed = text
		.replace(/[\t\r\n]/g, " ").trim().replace(/ +/g, " ")
		.replace(/<text:s\/>/g," ")
		.replace(/<text:s text:c="(\d+)"\/>/g, function($$,$1) { return Array(parseInt($1,10)+1).join(" "); })
		.replace(/<text:tab[^>]*\/>/g,"\t")
		.replace(/<text:line-break\/>/g,"\n");
	var v = unescapexml(fixed.replace(/<[^>]*>/g,""));

	return [v];
}

var number_formats_ods = {
	/* ods name: [short ssf fmt, long ssf fmt] */
	day:           ["d",   "dd"],
	month:         ["m",   "mm"],
	year:          ["y",   "yy"],
	hours:         ["h",   "hh"],
	minutes:       ["m",   "mm"],
	seconds:       ["s",   "ss"],
	"am-pm":       ["A/P", "AM/PM"],
	"day-of-week": ["ddd", "dddd"],
	era:           ["e",   "ee"],
	/* there is no native representation of LO "Q" format */
	quarter:       ["\\Qm", "m\\\"th quarter\""]
};


function parse_content_xml(d/*:string*/, _opts)/*:Workbook*/ {
		var opts = _opts || {};
		if(DENSE != null && opts.dense == null) opts.dense = DENSE;
		var str = xlml_normalize(d);
		var state/*:Array<any>*/ = [], tmp;
		var tag/*:: = {}*/;
		var NFtag = {name:""}, NF = "", pidx = 0;
		var sheetag/*:: = {name:"", '名称':""}*/;
		var rowtag/*:: = {'行号':""}*/;
		var Sheets = {}, SheetNames/*:Array<string>*/ = [];
		var ws = opts.dense ? ([]/*:any*/) : ({}/*:any*/);
		var Rn, q/*:: :any = ({t:"", v:null, z:null, w:"",c:[],}:any)*/;
		var ctag = ({value:""}/*:any*/);
		var textp = "", textpidx = 0, textptag/*:: = {}*/;
		var textR = [];
		var R = -1, C = -1, range = {s: {r:1000000,c:10000000}, e: {r:0, c:0}};
		var row_ol = 0;
		var number_format_map = {};
		var merges/*:Array<Range>*/ = [], mrange = {}, mR = 0, mC = 0;
		var rowinfo/*:Array<RowInfo>*/ = [], rowpeat = 1, colpeat = 1;
		var arrayf/*:Array<[Range, string]>*/ = [];
		var WB = {Names:[]};
		var atag = ({}/*:any*/);
		var _Ref/*:[string, string]*/ = ["", ""];
		var comments/*:Array<Comment>*/ = [], comment/*:Comment*/ = ({}/*:any*/);
		var creator = "", creatoridx = 0;
		var isstub = false, intable = false;
		var i = 0;
		xlmlregex.lastIndex = 0;
		str = str.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
		while((Rn = xlmlregex.exec(str))) switch((Rn[3]=Rn[3].replace(/_.*$/,""))) {

			case 'table': case '工作表': // 9.1.2 <table:table>
				if(Rn[1]==='/') {
					if(range.e.c >= range.s.c && range.e.r >= range.s.r) ws['!ref'] = encode_range(range);
					else ws['!ref'] = "A1:A1";
					if(opts.sheetRows > 0 && opts.sheetRows <= range.e.r) {
						ws['!fullref'] = ws['!ref'];
						range.e.r = opts.sheetRows - 1;
						ws['!ref'] = encode_range(range);
					}
					if(merges.length) ws['!merges'] = merges;
					if(rowinfo.length) ws["!rows"] = rowinfo;
					sheetag.name = sheetag['名称'] || sheetag.name;
					if(typeof JSON !== 'undefined') JSON.stringify(sheetag);
					SheetNames.push(sheetag.name);
					Sheets[sheetag.name] = ws;
					intable = false;
				}
				else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
					sheetag = parsexmltag(Rn[0], false);
					R = C = -1;
					range.s.r = range.s.c = 10000000; range.e.r = range.e.c = 0;
					ws = opts.dense ? ([]/*:any*/) : ({}/*:any*/); merges = [];
					rowinfo = [];
					intable = true;
				}
				break;

			case 'table-row-group': // 9.1.9 <table:table-row-group>
				if(Rn[1] === "/") --row_ol; else ++row_ol;
				break;
			case 'table-row': case '行': // 9.1.3 <table:table-row>
				if(Rn[1] === '/') { R+=rowpeat; rowpeat = 1; break; }
				rowtag = parsexmltag(Rn[0], false);
				if(rowtag['行号']) R = rowtag['行号'] - 1; else if(R == -1) R = 0;
				rowpeat = +rowtag['number-rows-repeated'] || 1;
				/* TODO: remove magic */
				if(rowpeat < 10) for(i = 0; i < rowpeat; ++i) if(row_ol > 0) rowinfo[R + i] = {level: row_ol};
				C = -1; break;
			case 'covered-table-cell': // 9.1.5 <table:covered-table-cell>
				if(Rn[1] !== '/') ++C;
				if(opts.sheetStubs) {
					if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = {t:'z'}; }
					else ws[encode_cell({r:R,c:C})] = {t:'z'};
				}
				textp = ""; textR = [];
				break; /* stub */
			case 'table-cell': case '数据':
				if(Rn[0].charAt(Rn[0].length-2) === '/') {
					++C;
					ctag = parsexmltag(Rn[0], false);
					colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
					q = ({t:'z', v:null/*:: , z:null, w:"",c:[]*/}/*:any*/);
					if(ctag.formula && opts.cellFormula != false) q.f = ods_to_csf_formula(unescapexml(ctag.formula));
					if((ctag['数据类型'] || ctag['value-type']) == "string") {
						q.t = "s"; q.v = unescapexml(ctag['string-value'] || "");
						if(opts.dense) {
							if(!ws[R]) ws[R] = [];
							ws[R][C] = q;
						} else {
							ws[encode_cell({r:R,c:C})] = q;
						}
					}
					C+= colpeat-1;
				} else if(Rn[1]!=='/') {
					++C;
					textp = ""; textpidx = 0; textR = [];
					colpeat = 1;
					var rptR = rowpeat ? R + rowpeat - 1 : R;
					if(C > range.e.c) range.e.c = C;
					if(C < range.s.c) range.s.c = C;
					if(R < range.s.r) range.s.r = R;
					if(rptR > range.e.r) range.e.r = rptR;
					ctag = parsexmltag(Rn[0], false);
					comments = []; comment = ({}/*:any*/);
					q = ({t:ctag['数据类型'] || ctag['value-type'], v:null/*:: , z:null, w:"",c:[]*/}/*:any*/);
					if(opts.cellFormula) {
						if(ctag.formula) ctag.formula = unescapexml(ctag.formula);
						if(ctag['number-matrix-columns-spanned'] && ctag['number-matrix-rows-spanned']) {
							mR = parseInt(ctag['number-matrix-rows-spanned'],10) || 0;
							mC = parseInt(ctag['number-matrix-columns-spanned'],10) || 0;
							mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
							q.F = encode_range(mrange);
							arrayf.push([mrange, q.F]);
						}
						if(ctag.formula) q.f = ods_to_csf_formula(ctag.formula);
						else for(i = 0; i < arrayf.length; ++i)
							if(R >= arrayf[i][0].s.r && R <= arrayf[i][0].e.r)
								if(C >= arrayf[i][0].s.c && C <= arrayf[i][0].e.c)
									q.F = arrayf[i][1];
					}
					if(ctag['number-columns-spanned'] || ctag['number-rows-spanned']) {
						mR = parseInt(ctag['number-rows-spanned'],10) || 0;
						mC = parseInt(ctag['number-columns-spanned'],10) || 0;
						mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
						merges.push(mrange);
					}

					/* 19.675.2 table:number-columns-repeated */
					if(ctag['number-columns-repeated']) colpeat = parseInt(ctag['number-columns-repeated'], 10);

					/* 19.385 office:value-type */
					switch(q.t) {
						case 'boolean': q.t = 'b'; q.v = parsexmlbool(ctag['boolean-value']); break;
						case 'float': q.t = 'n'; q.v = parseFloat(ctag.value); break;
						case 'percentage': q.t = 'n'; q.v = parseFloat(ctag.value); break;
						case 'currency': q.t = 'n'; q.v = parseFloat(ctag.value); break;
						case 'date': q.t = 'd'; q.v = parseDate(ctag['date-value']);
							if(!opts.cellDates) { q.t = 'n'; q.v = datenum(q.v); }
							q.z = 'm/d/yy'; break;
						case 'time': q.t = 'n'; q.v = parse_isodur(ctag['time-value'])/86400;
							if(opts.cellDates) { q.t = 'd'; q.v = numdate(q.v); }
							q.z = 'HH:MM:SS'; break;
						case 'number': q.t = 'n'; q.v = parseFloat(ctag['数据数值']); break;
						default:
							if(q.t === 'string' || q.t === 'text' || !q.t) {
								q.t = 's';
								if(ctag['string-value'] != null) { textp = unescapexml(ctag['string-value']); textR = []; }
							} else throw new Error('Unsupported value type ' + q.t);
					}
				} else {
					isstub = false;
					if(q.t === 's') {
						q.v = textp || '';
						if(textR.length) q.R = textR;
						isstub = textpidx == 0;
					}
					if(atag.Target) q.l = atag;
					if(comments.length > 0) { q.c = comments; comments = []; }
					if(textp && opts.cellText !== false) q.w = textp;
					if(isstub) { q.t = "z"; delete q.v; }
					if(!isstub || opts.sheetStubs) {
						if(!(opts.sheetRows && opts.sheetRows <= R)) {
							for(var rpt = 0; rpt < rowpeat; ++rpt) {
								colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
								if(opts.dense) {
									if(!ws[R + rpt]) ws[R + rpt] = [];
									ws[R + rpt][C] = rpt == 0 ? q : dup(q);
									while(--colpeat > 0) ws[R + rpt][C + colpeat] = dup(q);
								} else {
									ws[encode_cell({r:R + rpt,c:C})] = q;
									while(--colpeat > 0) ws[encode_cell({r:R + rpt,c:C + colpeat})] = dup(q);
								}
								if(range.e.c <= C) range.e.c = C;
							}
						}
					}
					colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
					C += colpeat-1; colpeat = 0;
					q = {/*:: t:"", v:null, z:null, w:"",c:[]*/};
					textp = ""; textR = [];
				}
				atag = ({}/*:any*/);
				break; // 9.1.4 <table:table-cell>

			/* pure state */
			case 'document': // TODO: <office:document> is the root for FODS
			case 'document-content': case '电子表格文档': // 3.1.3.2 <office:document-content>
			case 'spreadsheet': case '主体': // 3.7 <office:spreadsheet>
			case 'scripts': // 3.12 <office:scripts>
			case 'styles': // TODO <office:styles>
			case 'font-face-decls': // 3.14 <office:font-face-decls>
			case 'master-styles': // 3.15.4 <office:master-styles> -- relevant for FODS
				if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
				else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
				break;

			case 'annotation': // 14.1 <office:annotation>
				if(Rn[1]==='/'){
					if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;
					comment.t = textp;
					if(textR.length) /*::(*/comment/*:: :any)*/.R = textR;
					comment.a = creator;
					comments.push(comment);
				}
				else if(Rn[0].charAt(Rn[0].length-2) !== '/') {state.push([Rn[3], false]);}
				creator = ""; creatoridx = 0;
				textp = ""; textpidx = 0; textR = [];
				break;

			case 'creator': // 4.3.2.7 <dc:creator>
				if(Rn[1]==='/') { creator = str.slice(creatoridx,Rn.index); }
				else creatoridx = Rn.index + Rn[0].length;
				break;

			/* ignore state */
			case 'meta': case '元数据': // TODO: <office:meta> <uof:元数据> FODS/UOF
			case 'settings': // TODO: <office:settings>
			case 'config-item-set': // TODO: <office:config-item-set>
			case 'config-item-map-indexed': // TODO: <office:config-item-map-indexed>
			case 'config-item-map-entry': // TODO: <office:config-item-map-entry>
			case 'config-item-map-named': // TODO: <office:config-item-map-entry>
			case 'shapes': // 9.2.8 <table:shapes>
			case 'frame': // 10.4.2 <draw:frame>
			case 'text-box': // 10.4.3 <draw:text-box>
			case 'image': // 10.4.4 <draw:image>
			case 'data-pilot-tables': // 9.6.2 <table:data-pilot-tables>
			case 'list-style': // 16.30 <text:list-style>
			case 'form': // 13.13 <form:form>
			case 'dde-links': // 9.8 <table:dde-links>
			case 'event-listeners': // TODO
			case 'chart': // TODO
				if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
				else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], false]);
				textp = ""; textpidx = 0; textR = [];
				break;

			case 'scientific-number': // TODO: <number:scientific-number>
				break;
			case 'currency-symbol': // TODO: <number:currency-symbol>
				break;
			case 'currency-style': // TODO: <number:currency-style>
				break;
			case 'number-style': // 16.27.2 <number:number-style>
			case 'percentage-style': // 16.27.9 <number:percentage-style>
			case 'date-style': // 16.27.10 <number:date-style>
			case 'time-style': // 16.27.18 <number:time-style>
				if(Rn[1]==='/'){
					number_format_map[NFtag.name] = NF;
					if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;
				} else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
					NF = "";
					NFtag = parsexmltag(Rn[0], false);
					state.push([Rn[3], true]);
				} break;

			case 'script': break; // 3.13 <office:script>
			case 'libraries': break; // TODO: <ooo:libraries>
			case 'automatic-styles': break; // 3.15.3 <office:automatic-styles>

			case 'default-style': // TODO: <style:default-style>
			case 'page-layout': break; // TODO: <style:page-layout>
			case 'style': // 16.2 <style:style>
				break;
			case 'map': break; // 16.3 <style:map>
			case 'font-face': break; // 16.21 <style:font-face>

			case 'paragraph-properties': break; // 17.6 <style:paragraph-properties>
			case 'table-properties': break; // 17.15 <style:table-properties>
			case 'table-column-properties': break; // 17.16 <style:table-column-properties>
			case 'table-row-properties': break; // 17.17 <style:table-row-properties>
			case 'table-cell-properties': break; // 17.18 <style:table-cell-properties>

			case 'number': // 16.27.3 <number:number>
				switch(state[state.length-1][0]) {
					case 'time-style':
					case 'date-style':
						tag = parsexmltag(Rn[0], false);
						NF += number_formats_ods[Rn[3]][tag.style==='long'?1:0]; break;
				} break;

			case 'fraction': break; // TODO 16.27.6 <number:fraction>

			case 'day': // 16.27.11 <number:day>
			case 'month': // 16.27.12 <number:month>
			case 'year': // 16.27.13 <number:year>
			case 'era': // 16.27.14 <number:era>
			case 'day-of-week': // 16.27.15 <number:day-of-week>
			case 'week-of-year': // 16.27.16 <number:week-of-year>
			case 'quarter': // 16.27.17 <number:quarter>
			case 'hours': // 16.27.19 <number:hours>
			case 'minutes': // 16.27.20 <number:minutes>
			case 'seconds': // 16.27.21 <number:seconds>
			case 'am-pm': // 16.27.22 <number:am-pm>
				switch(state[state.length-1][0]) {
					case 'time-style':
					case 'date-style':
						tag = parsexmltag(Rn[0], false);
						NF += number_formats_ods[Rn[3]][tag.style==='long'?1:0]; break;
				} break;

			case 'boolean-style': break; // 16.27.23 <number:boolean-style>
			case 'boolean': break; // 16.27.24 <number:boolean>
			case 'text-style': break; // 16.27.25 <number:text-style>
			case 'text': // 16.27.26 <number:text>
				if(Rn[0].slice(-2) === "/>") break;
				else if(Rn[1]==="/") switch(state[state.length-1][0]) {
					case 'number-style':
					case 'date-style':
					case 'time-style':
						NF += str.slice(pidx, Rn.index);
						break;
				}
				else pidx = Rn.index + Rn[0].length;
				break;

			case 'named-range': // 9.4.12 <table:named-range>
				tag = parsexmltag(Rn[0], false);
				_Ref = ods_to_csf_3D(tag['cell-range-address']);
				var nrange = ({Name:tag.name, Ref:_Ref[0] + '!' + _Ref[1]}/*:any*/);
				if(intable) nrange.Sheet = SheetNames.length;
				WB.Names.push(nrange);
				break;

			case 'text-content': break; // 16.27.27 <number:text-content>
			case 'text-properties': break; // 16.27.27 <style:text-properties>
			case 'embedded-text': break; // 16.27.4 <number:embedded-text>

			case 'body': case '电子表格': break; // 3.3 16.9.6 19.726.3

			case 'forms': break; // 12.25.2 13.2
			case 'table-column': break; // 9.1.6 <table:table-column>
			case 'table-header-rows': break; // 9.1.7 <table:table-header-rows>
			case 'table-rows': break; // 9.1.12 <table:table-rows>
			/* TODO: outline levels */
			case 'table-column-group': break; // 9.1.10 <table:table-column-group>
			case 'table-header-columns': break; // 9.1.11 <table:table-header-columns>
			case 'table-columns': break; // 9.1.12 <table:table-columns>

			case 'null-date': break; // 9.4.2 <table:null-date> TODO: date1904

			case 'graphic-properties': break; // 17.21 <style:graphic-properties>
			case 'calculation-settings': break; // 9.4.1 <table:calculation-settings>
			case 'named-expressions': break; // 9.4.11 <table:named-expressions>
			case 'label-range': break; // 9.4.9 <table:label-range>
			case 'label-ranges': break; // 9.4.10 <table:label-ranges>
			case 'named-expression': break; // 9.4.13 <table:named-expression>
			case 'sort': break; // 9.4.19 <table:sort>
			case 'sort-by': break; // 9.4.20 <table:sort-by>
			case 'sort-groups': break; // 9.4.22 <table:sort-groups>

			case 'tab': break; // 6.1.4 <text:tab>
			case 'line-break': break; // 6.1.5 <text:line-break>
			case 'span': break; // 6.1.7 <text:span>
			case 'p': case '文本串': // 5.1.3 <text:p>
				if(['master-styles'].indexOf(state[state.length-1][0]) > -1) break;
				if(Rn[1]==='/' && (!ctag || !ctag['string-value'])) {
					var ptp = parse_text_p(str.slice(textpidx,Rn.index), textptag);
					textp = (textp.length > 0 ? textp + "\n" : "") + ptp[0];
				} else { textptag = parsexmltag(Rn[0], false); textpidx = Rn.index + Rn[0].length; }
				break; // <text:p>
			case 's': break; // <text:s>

			case 'database-range': // 9.4.15 <table:database-range>
				if(Rn[1]==='/') break;
				try {
					_Ref = ods_to_csf_3D(parsexmltag(Rn[0])['target-range-address']);
					Sheets[_Ref[0]]['!autofilter'] = { ref:_Ref[1] };
				} catch(e) {/* empty */}
				break;

			case 'date': break; // <*:date>

			case 'object': break; // 10.4.6.2 <draw:object>
			case 'title': case '标题': break; // <*:title> OR <uof:标题>
			case 'desc': break; // <*:desc>
			case 'binary-data': break; // 10.4.5 TODO: b64 blob

			/* 9.2 Advanced Tables */
			case 'table-source': break; // 9.2.6
			case 'scenario': break; // 9.2.6

			case 'iteration': break; // 9.4.3 <table:iteration>
			case 'content-validations': break; // 9.4.4 <table:
			case 'content-validation': break; // 9.4.5 <table:
			case 'help-message': break; // 9.4.6 <table:
			case 'error-message': break; // 9.4.7 <table:
			case 'database-ranges': break; // 9.4.14 <table:database-ranges>
			case 'filter': break; // 9.5.2 <table:filter>
			case 'filter-and': break; // 9.5.3 <table:filter-and>
			case 'filter-or': break; // 9.5.4 <table:filter-or>
			case 'filter-condition': break; // 9.5.5 <table:filter-condition>

			case 'list-level-style-bullet': break; // 16.31 <text:
			case 'list-level-style-number': break; // 16.32 <text:
			case 'list-level-properties': break; // 17.19 <style:

			/* 7.3 Document Fields */
			case 'sender-firstname': // 7.3.6.2
			case 'sender-lastname': // 7.3.6.3
			case 'sender-initials': // 7.3.6.4
			case 'sender-title': // 7.3.6.5
			case 'sender-position': // 7.3.6.6
			case 'sender-email': // 7.3.6.7
			case 'sender-phone-private': // 7.3.6.8
			case 'sender-fax': // 7.3.6.9
			case 'sender-company': // 7.3.6.10
			case 'sender-phone-work': // 7.3.6.11
			case 'sender-street': // 7.3.6.12
			case 'sender-city': // 7.3.6.13
			case 'sender-postal-code': // 7.3.6.14
			case 'sender-country': // 7.3.6.15
			case 'sender-state-or-province': // 7.3.6.16
			case 'author-name': // 7.3.7.1
			case 'author-initials': // 7.3.7.2
			case 'chapter': // 7.3.8
			case 'file-name': // 7.3.9
			case 'template-name': // 7.3.9
			case 'sheet-name': // 7.3.9
				break;

			case 'event-listener':
				break;
			/* TODO: FODS Properties */
			case 'initial-creator':
			case 'creation-date':
			case 'print-date':
			case 'generator':
			case 'document-statistic':
			case 'user-defined':
			case 'editing-duration':
			case 'editing-cycles':
				break;

			/* TODO: FODS Config */
			case 'config-item':
				break;

			/* TODO: style tokens */
			case 'page-number': break; // TODO <text:page-number>
			case 'page-count': break; // TODO <text:page-count>
			case 'time': break; // TODO <text:time>

			/* 9.3 Advanced Table Cells */
			case 'cell-range-source': break; // 9.3.1 <table:
			case 'detective': break; // 9.3.2 <table:
			case 'operation': break; // 9.3.3 <table:
			case 'highlighted-range': break; // 9.3.4 <table:

			/* 9.6 Data Pilot Tables <table: */
			case 'data-pilot-table': // 9.6.3
			case 'source-cell-range': // 9.6.5
			case 'source-service': // 9.6.6
			case 'data-pilot-field': // 9.6.7
			case 'data-pilot-level': // 9.6.8
			case 'data-pilot-subtotals': // 9.6.9
			case 'data-pilot-subtotal': // 9.6.10
			case 'data-pilot-members': // 9.6.11
			case 'data-pilot-member': // 9.6.12
			case 'data-pilot-display-info': // 9.6.13
			case 'data-pilot-sort-info': // 9.6.14
			case 'data-pilot-layout-info': // 9.6.15
			case 'data-pilot-field-reference': // 9.6.16
			case 'data-pilot-groups': // 9.6.17
			case 'data-pilot-group': // 9.6.18
			case 'data-pilot-group-member': // 9.6.19
				break;

			/* 10.3 Drawing Shapes */
			case 'rect': // 10.3.2
				break;

			/* 14.6 DDE Connections */
			case 'dde-connection-decls': // 14.6.2 <text:
			case 'dde-connection-decl': // 14.6.3 <text:
			case 'dde-link': // 14.6.4 <table:
			case 'dde-source': // 14.6.5 <office:
				break;

			case 'properties': break; // 13.7 <form:properties>
			case 'property': break; // 13.8 <form:property>

			case 'a': // 6.1.8 hyperlink
				if(Rn[1]!== '/') {
					atag = parsexmltag(Rn[0], false);
					if(!atag.href) break;
					atag.Target = unescapexml(atag.href); delete atag.href;
					if(atag.Target.charAt(0) == "#" && atag.Target.indexOf(".") > -1) {
						_Ref = ods_to_csf_3D(atag.Target.slice(1));
						atag.Target = "#" + _Ref[0] + "!" + _Ref[1];
					} else if(atag.Target.match(/^\.\.[\\\/]/)) atag.Target = atag.Target.slice(3);
				}
				break;

			/* non-standard */
			case 'table-protection': break;
			case 'data-pilot-grand-total': break; // <table:
			case 'office-document-common-attrs': break; // bare
			default: switch(Rn[2]) {
				case 'dc:':       // TODO: properties
				case 'calcext:':  // ignore undocumented extensions
				case 'loext:':    // ignore undocumented extensions
				case 'ooo:':      // ignore undocumented extensions
				case 'chartooo:': // ignore undocumented extensions
				case 'draw:':     // TODO: drawing
				case 'style:':    // TODO: styles
				case 'chart:':    // TODO: charts
				case 'form:':     // TODO: forms
				case 'uof:':      // TODO: uof
				case '表:':       // TODO: uof
				case '字:':       // TODO: uof
					break;
				default: if(opts.WTF) throw new Error(Rn);
			}
		}
		var out/*:Workbook*/ = ({
			Sheets: Sheets,
			SheetNames: SheetNames,
			Workbook: WB
		}/*:any*/);
		if(opts.bookSheets) delete /*::(*/out/*:: :any)*/.Sheets;
		return out;
}

function parse_ods(zip/*:ZIPFile*/, opts/*:?ParseOpts*/)/*:Workbook*/ {
	opts = opts || ({}/*:any*/);
	if(safegetzipfile(zip, 'META-INF/manifest.xml')) parse_manifest(getzipdata(zip, 'META-INF/manifest.xml'), opts);
	var content = getzipstr(zip, 'content.xml');
	if(!content) throw new Error("Missing content.xml in ODS / UOF file");
	var wb = parse_content_xml(utf8read(content), opts);
	if(safegetzipfile(zip, 'meta.xml')) wb.Props = parse_core_props(getzipdata(zip, 'meta.xml'));
	return wb;
}
function parse_fods(data/*:string*/, opts/*:?ParseOpts*/)/*:Workbook*/ {
	return parse_content_xml(data, opts);
}

/* OpenDocument */
var write_styles_ods/*:{(wb:any, opts:any):string}*/ = /* @__PURE__ */(function() {
	var master_styles = [
		'<office:master-styles>',
			'<style:master-page style:name="mp1" style:page-layout-name="mp1">',
				'<style:header/>',
				'<style:header-left style:display="false"/>',
				'<style:footer/>',
				'<style:footer-left style:display="false"/>',
			'</style:master-page>',
		'</office:master-styles>'
	].join("");

	var payload = '<office:document-styles ' + wxt_helper({
		'xmlns:office':   "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
		'xmlns:table':    "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
		'xmlns:style':    "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
		'xmlns:text':     "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
		'xmlns:draw':     "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
		'xmlns:fo':       "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
		'xmlns:xlink':    "http://www.w3.org/1999/xlink",
		'xmlns:dc':       "http://purl.org/dc/elements/1.1/",
		'xmlns:number':   "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
		'xmlns:svg':      "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
		'xmlns:of':       "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
		'office:version': "1.2"
	}) + '>' + master_styles + '</office:document-styles>';

	return function wso(/*::wb, opts*/) {
		return XML_HEADER + payload;
	};
})();
var write_content_ods/*:{(wb:any, opts:any):string}*/ = /* @__PURE__ */(function() {
	/* 6.1.2 White Space Characters */
	var write_text_p = function(text/*:string*/)/*:string*/ {
		return escapexml(text)
			.replace(/  +/g, function($$){return '<text:s text:c="'+$$.length+'"/>';})
			.replace(/\t/g, "<text:tab/>")
			.replace(/\n/g, "</text:p><text:p>")
			.replace(/^ /, "<text:s/>").replace(/ $/, "<text:s/>");
	};

	var null_cell_xml = '          <table:table-cell />\n';
	var covered_cell_xml = '          <table:covered-table-cell/>\n';
	var write_ws = function(ws, wb/*:Workbook*/, i/*:number*//*::, opts*/)/*:string*/ {
		/* Section 9 Tables */
		var o/*:Array<string>*/ = [];
		o.push('      <table:table table:name="' + escapexml(wb.SheetNames[i]) + '" table:style-name="ta1">\n');
		var R=0,C=0, range = decode_range(ws['!ref']||"A1");
		var marr/*:Array<Range>*/ = ws['!merges'] || [], mi = 0;
		var dense = Array.isArray(ws);
		if(ws["!cols"]) {
			for(C = 0; C <= range.e.c; ++C) o.push('        <table:table-column' + (ws["!cols"][C] ? ' table:style-name="co' + ws["!cols"][C].ods + '"' : '') + '></table:table-column>\n');
		}
		var H = "", ROWS = ws["!rows"]||[];
		for(R = 0; R < range.s.r; ++R) {
			H = ROWS[R] ? ' table:style-name="ro' + ROWS[R].ods + '"' : "";
			o.push('        <table:table-row' + H + '></table:table-row>\n');
		}
		for(; R <= range.e.r; ++R) {
			H = ROWS[R] ? ' table:style-name="ro' + ROWS[R].ods + '"' : "";
			o.push('        <table:table-row' + H + '>\n');
			for(C=0; C < range.s.c; ++C) o.push(null_cell_xml);
			for(; C <= range.e.c; ++C) {
				var skip = false, ct = {}, textp = "";
				for(mi = 0; mi != marr.length; ++mi) {
					if(marr[mi].s.c > C) continue;
					if(marr[mi].s.r > R) continue;
					if(marr[mi].e.c < C) continue;
					if(marr[mi].e.r < R) continue;
					if(marr[mi].s.c != C || marr[mi].s.r != R) skip = true;
					ct['table:number-columns-spanned'] = (marr[mi].e.c - marr[mi].s.c + 1);
					ct['table:number-rows-spanned'] =    (marr[mi].e.r - marr[mi].s.r + 1);
					break;
				}
				if(skip) { o.push(covered_cell_xml); continue; }
				var ref = encode_cell({r:R, c:C}), cell = dense ? (ws[R]||[])[C]: ws[ref];
				if(cell && cell.f) {
					ct['table:formula'] = escapexml(csf_to_ods_formula(cell.f));
					if(cell.F) {
						if(cell.F.slice(0, ref.length) == ref) {
							var _Fref = decode_range(cell.F);
							ct['table:number-matrix-columns-spanned'] = (_Fref.e.c - _Fref.s.c + 1);
							ct['table:number-matrix-rows-spanned'] =    (_Fref.e.r - _Fref.s.r + 1);
						}
					}
				}
				if(!cell) { o.push(null_cell_xml); continue; }
				switch(cell.t) {
					case 'b':
						textp = (cell.v ? 'TRUE' : 'FALSE');
						ct['office:value-type'] = "boolean";
						ct['office:boolean-value'] = (cell.v ? 'true' : 'false');
						break;
					case 'n':
						textp = (cell.w||String(cell.v||0));
						ct['office:value-type'] = "float";
						ct['office:value'] = (cell.v||0);
						break;
					case 's': case 'str':
						textp = cell.v == null ? "" : cell.v;
						ct['office:value-type'] = "string";
						break;
					case 'd':
						textp = (cell.w||(parseDate(cell.v).toISOString()));
						ct['office:value-type'] = "date";
						ct['office:date-value'] = (parseDate(cell.v).toISOString());
						ct['table:style-name'] = "ce1";
						break;
					//case 'e':
					default: o.push(null_cell_xml); continue;
				}
				var text_p = write_text_p(textp);
				if(cell.l && cell.l.Target) {
					var _tgt = cell.l.Target;
					_tgt = _tgt.charAt(0) == "#" ? "#" + csf_to_ods_3D(_tgt.slice(1)) : _tgt;
					// TODO: choose correct parent path format based on link delimiters
					if(_tgt.charAt(0) != "#" && !_tgt.match(/^\w+:/)) _tgt = '../' + _tgt;
					text_p = writextag('text:a', text_p, {'xlink:href': _tgt.replace(/&/g, "&amp;")});
				}
				o.push('          ' + writextag('table:table-cell', writextag('text:p', text_p, {}), ct) + '\n');
			}
			o.push('        </table:table-row>\n');
		}
		o.push('      </table:table>\n');
		return o.join("");
	};

	var write_automatic_styles_ods = function(o/*:Array<string>*/, wb) {
		o.push(' <office:automatic-styles>\n');

		o.push('  <number:date-style style:name="N37" number:automatic-order="true">\n');
		o.push('   <number:month number:style="long"/>\n');
		o.push('   <number:text>/</number:text>\n');
		o.push('   <number:day number:style="long"/>\n');
		o.push('   <number:text>/</number:text>\n');
		o.push('   <number:year/>\n');
		o.push('  </number:date-style>\n');

		/* column styles */
		var cidx = 0;
		wb.SheetNames.map(function(n) { return wb.Sheets[n]; }).forEach(function(ws) {
			if(!ws) return;
			if(ws["!cols"]) {
				for(var C = 0; C < ws["!cols"].length; ++C) if(ws["!cols"][C]) {
					var colobj = ws["!cols"][C];
					if(colobj.width == null && colobj.wpx == null && colobj.wch == null) continue;
					process_col(colobj);
					colobj.ods = cidx;
					var w = ws["!cols"][C].wpx + "px";
					o.push('  <style:style style:name="co' + cidx + '" style:family="table-column">\n');
					o.push('   <style:table-column-properties fo:break-before="auto" style:column-width="' + w + '"/>\n');
					o.push('  </style:style>\n');
					++cidx;
				}
			}
		});

		/* row styles */
		var ridx = 0;
		wb.SheetNames.map(function(n) { return wb.Sheets[n]; }).forEach(function(ws) {
			if(!ws) return;
			if(ws["!rows"]) {
				for(var R = 0; R < ws["!rows"].length; ++R) if(ws["!rows"][R]) {
					ws["!rows"][R].ods = ridx;
					var h = ws["!rows"][R].hpx + "px";
					o.push('  <style:style style:name="ro' + ridx + '" style:family="table-row">\n');
					o.push('   <style:table-row-properties fo:break-before="auto" style:row-height="' + h + '"/>\n');
					o.push('  </style:style>\n');
					++ridx;
				}
			}
		});

		/* table */
		o.push('  <style:style style:name="ta1" style:family="table" style:master-page-name="mp1">\n');
		o.push('   <style:table-properties table:display="true" style:writing-mode="lr-tb"/>\n');
		o.push('  </style:style>\n');

		/* table cells, text */
		o.push('  <style:style style:name="ce1" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="N37"/>\n');

		/* page-layout */

		o.push(' </office:automatic-styles>\n');
	};

	return function wcx(wb, opts) {
		var o = [XML_HEADER];
		/* 3.1.3.2 */
		var attr = wxt_helper({
			'xmlns:office':       "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
			'xmlns:table':        "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
			'xmlns:style':        "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
			'xmlns:text':         "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
			'xmlns:draw':         "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
			'xmlns:fo':           "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
			'xmlns:xlink':        "http://www.w3.org/1999/xlink",
			'xmlns:dc':           "http://purl.org/dc/elements/1.1/",
			'xmlns:meta':         "urn:oasis:names:tc:opendocument:xmlns:meta:1.0",
			'xmlns:number':       "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
			'xmlns:presentation': "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0",
			'xmlns:svg':          "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
			'xmlns:chart':        "urn:oasis:names:tc:opendocument:xmlns:chart:1.0",
			'xmlns:dr3d':         "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0",
			'xmlns:math':         "http://www.w3.org/1998/Math/MathML",
			'xmlns:form':         "urn:oasis:names:tc:opendocument:xmlns:form:1.0",
			'xmlns:script':       "urn:oasis:names:tc:opendocument:xmlns:script:1.0",
			'xmlns:ooo':          "http://openoffice.org/2004/office",
			'xmlns:ooow':         "http://openoffice.org/2004/writer",
			'xmlns:oooc':         "http://openoffice.org/2004/calc",
			'xmlns:dom':          "http://www.w3.org/2001/xml-events",
			'xmlns:xforms':       "http://www.w3.org/2002/xforms",
			'xmlns:xsd':          "http://www.w3.org/2001/XMLSchema",
			'xmlns:xsi':          "http://www.w3.org/2001/XMLSchema-instance",
			'xmlns:sheet':        "urn:oasis:names:tc:opendocument:sh33tjs:1.0",
			'xmlns:rpt':          "http://openoffice.org/2005/report",
			'xmlns:of':           "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
			'xmlns:xhtml':        "http://www.w3.org/1999/xhtml",
			'xmlns:grddl':        "http://www.w3.org/2003/g/data-view#",
			'xmlns:tableooo':     "http://openoffice.org/2009/table",
			'xmlns:drawooo':      "http://openoffice.org/2010/draw",
			'xmlns:calcext':      "urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0",
			'xmlns:loext':        "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0",
			'xmlns:field':        "urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0",
			'xmlns:formx':        "urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0",
			'xmlns:css3t':        "http://www.w3.org/TR/css3-text/",
			'office:version':     "1.2"
		});

		var fods = wxt_helper({
			'xmlns:config':    "urn:oasis:names:tc:opendocument:xmlns:config:1.0",
			'office:mimetype': "application/vnd.oasis.opendocument.spreadsheet"
		});

		if(opts.bookType == "fods") {
			o.push('<office:document' + attr + fods + '>\n');
			o.push(write_meta_ods().replace(/office:document-meta/g, "office:meta"));
			// TODO: settings (equiv of settings.xml for ODS)
		} else o.push('<office:document-content' + attr  + '>\n');
		// o.push('  <office:scripts/>\n');
		write_automatic_styles_ods(o, wb);
		o.push('  <office:body>\n');
		o.push('    <office:spreadsheet>\n');
		for(var i = 0; i != wb.SheetNames.length; ++i) o.push(write_ws(wb.Sheets[wb.SheetNames[i]], wb, i, opts));
		o.push('    </office:spreadsheet>\n');
		o.push('  </office:body>\n');
		if(opts.bookType == "fods") o.push('</office:document>');
		else o.push('</office:document-content>');
		return o.join("");
	};
})();

function write_ods(wb/*:any*/, opts/*:any*/) {
	if(opts.bookType == "fods") return write_content_ods(wb, opts);

	var zip = zip_new();
	var f = "";

	var manifest/*:Array<Array<string> >*/ = [];
	var rdf/*:Array<[string, string]>*/ = [];

	/* Part 3 Section 3.3 MIME Media Type */
	f = "mimetype";
	zip_add_file(zip, f, "application/vnd.oasis.opendocument.spreadsheet");

	/* Part 1 Section 2.2 Documents */
	f = "content.xml";
	zip_add_file(zip, f, write_content_ods(wb, opts));
	manifest.push([f, "text/xml"]);
	rdf.push([f, "ContentFile"]);

	/* TODO: these are hard-coded styles to satiate excel */
	f = "styles.xml";
	zip_add_file(zip, f, write_styles_ods(wb, opts));
	manifest.push([f, "text/xml"]);
	rdf.push([f, "StylesFile"]);

	/* TODO: this is hard-coded to satiate excel */
	f = "meta.xml";
	zip_add_file(zip, f, XML_HEADER + write_meta_ods(/*::wb, opts*/));
	manifest.push([f, "text/xml"]);
	rdf.push([f, "MetadataFile"]);

	/* Part 3 Section 6 Metadata Manifest File */
	f = "manifest.rdf";
	zip_add_file(zip, f, write_rdf(rdf/*, opts*/));
	manifest.push([f, "application/rdf+xml"]);

	/* Part 3 Section 4 Manifest File */
	f = "META-INF/manifest.xml";
	zip_add_file(zip, f, write_manifest(manifest/*, opts*/));

	return zip;
}

/*! sheetjs (C) 2013-present SheetJS -- http://sheetjs.com */
function u8_to_dataview(array) {
  return new DataView(array.buffer, array.byteOffset, array.byteLength);
}
function u8str(u8) {
  return typeof TextDecoder != "undefined" ? new TextDecoder().decode(u8) : utf8read(a2s(u8));
}
function stru8(str) {
  return typeof TextEncoder != "undefined" ? new TextEncoder().encode(str) : s2a(utf8write(str));
}
function u8contains(body, search) {
  outer:
    for (var L = 0; L <= body.length - search.length; ++L) {
      for (var j = 0; j < search.length; ++j)
        if (body[L + j] != search[j])
          continue outer;
      return true;
    }
  return false;
}
function u8concat(u8a) {
  var len = u8a.reduce(function(acc, x) {
    return acc + x.length;
  }, 0);
  var out = new Uint8Array(len);
  var off = 0;
  u8a.forEach(function(u8) {
    out.set(u8, off);
    off += u8.length;
  });
  return out;
}
function popcnt(x) {
  x -= x >> 1 & 1431655765;
  x = (x & 858993459) + (x >> 2 & 858993459);
  return (x + (x >> 4) & 252645135) * 16843009 >>> 24;
}
function readDecimal128LE(buf, offset) {
  var exp = (buf[offset + 15] & 127) << 7 | buf[offset + 14] >> 1;
  var mantissa = buf[offset + 14] & 1;
  for (var j = offset + 13; j >= offset; --j)
    mantissa = mantissa * 256 + buf[j];
  return (buf[offset + 15] & 128 ? -mantissa : mantissa) * Math.pow(10, exp - 6176);
}
function writeDecimal128LE(buf, offset, value) {
  var exp = Math.floor(value == 0 ? 0 : Math.LOG10E * Math.log(Math.abs(value))) + 6176 - 20;
  var mantissa = value / Math.pow(10, exp - 6176);
  buf[offset + 15] |= exp >> 7;
  buf[offset + 14] |= (exp & 127) << 1;
  for (var i = 0; mantissa >= 1; ++i, mantissa /= 256)
    buf[offset + i] = mantissa & 255;
  buf[offset + 15] |= value >= 0 ? 0 : 128;
}
function parse_varint49(buf, ptr) {
  var l = ptr ? ptr[0] : 0;
  var usz = buf[l] & 127;
  varint:
    if (buf[l++] >= 128) {
      usz |= (buf[l] & 127) << 7;
      if (buf[l++] < 128)
        break varint;
      usz |= (buf[l] & 127) << 14;
      if (buf[l++] < 128)
        break varint;
      usz |= (buf[l] & 127) << 21;
      if (buf[l++] < 128)
        break varint;
      usz += (buf[l] & 127) * Math.pow(2, 28);
      ++l;
      if (buf[l++] < 128)
        break varint;
      usz += (buf[l] & 127) * Math.pow(2, 35);
      ++l;
      if (buf[l++] < 128)
        break varint;
      usz += (buf[l] & 127) * Math.pow(2, 42);
      ++l;
      if (buf[l++] < 128)
        break varint;
    }
  if (ptr)
    ptr[0] = l;
  return usz;
}
function write_varint49(v) {
  var usz = new Uint8Array(7);
  usz[0] = v & 127;
  var L = 1;
  sz:
    if (v > 127) {
      usz[L - 1] |= 128;
      usz[L] = v >> 7 & 127;
      ++L;
      if (v <= 16383)
        break sz;
      usz[L - 1] |= 128;
      usz[L] = v >> 14 & 127;
      ++L;
      if (v <= 2097151)
        break sz;
      usz[L - 1] |= 128;
      usz[L] = v >> 21 & 127;
      ++L;
      if (v <= 268435455)
        break sz;
      usz[L - 1] |= 128;
      usz[L] = v / 256 >>> 21 & 127;
      ++L;
      if (v <= 34359738367)
        break sz;
      usz[L - 1] |= 128;
      usz[L] = v / 65536 >>> 21 & 127;
      ++L;
      if (v <= 4398046511103)
        break sz;
      usz[L - 1] |= 128;
      usz[L] = v / 16777216 >>> 21 & 127;
      ++L;
    }
  return usz.slice(0, L);
}
function varint_to_i32(buf) {
  var l = 0, i32 = buf[l] & 127;
  varint:
    if (buf[l++] >= 128) {
      i32 |= (buf[l] & 127) << 7;
      if (buf[l++] < 128)
        break varint;
      i32 |= (buf[l] & 127) << 14;
      if (buf[l++] < 128)
        break varint;
      i32 |= (buf[l] & 127) << 21;
      if (buf[l++] < 128)
        break varint;
      i32 |= (buf[l] & 127) << 28;
    }
  return i32;
}
function parse_shallow(buf) {
  var out = [], ptr = [0];
  while (ptr[0] < buf.length) {
    var off = ptr[0];
    var num = parse_varint49(buf, ptr);
    var type = num & 7;
    num = Math.floor(num / 8);
    var len = 0;
    var res;
    if (num == 0)
      break;
    switch (type) {
      case 0:
        {
          var l = ptr[0];
          while (buf[ptr[0]++] >= 128)
            ;
          res = buf.slice(l, ptr[0]);
        }
        break;
      case 5:
        len = 4;
        res = buf.slice(ptr[0], ptr[0] + len);
        ptr[0] += len;
        break;
      case 1:
        len = 8;
        res = buf.slice(ptr[0], ptr[0] + len);
        ptr[0] += len;
        break;
      case 2:
        len = parse_varint49(buf, ptr);
        res = buf.slice(ptr[0], ptr[0] + len);
        ptr[0] += len;
        break;
      case 3:
      case 4:
      default:
        throw new Error("PB Type ".concat(type, " for Field ").concat(num, " at offset ").concat(off));
    }
    var v = { data: res, type: type };
    if (out[num] == null)
      out[num] = [v];
    else
      out[num].push(v);
  }
  return out;
}
function write_shallow(proto) {
  var out = [];
  proto.forEach(function(field, idx) {
    field.forEach(function(item) {
      if (!item.data)
        return;
      out.push(write_varint49(idx * 8 + item.type));
      if (item.type == 2)
        out.push(write_varint49(item.data.length));
      out.push(item.data);
    });
  });
  return u8concat(out);
}
function mappa(data, cb) {
  return (data == null ? void 0 : data.map(function(d) {
    return cb(d.data);
  })) || [];
}
function parse_iwa_file(buf) {
  var _a;
  var out = [], ptr = [0];
  while (ptr[0] < buf.length) {
    var len = parse_varint49(buf, ptr);
    var ai = parse_shallow(buf.slice(ptr[0], ptr[0] + len));
    ptr[0] += len;
    var res = {
      id: varint_to_i32(ai[1][0].data),
      messages: []
    };
    ai[2].forEach(function(b) {
      var mi = parse_shallow(b.data);
      var fl = varint_to_i32(mi[3][0].data);
      res.messages.push({
        meta: mi,
        data: buf.slice(ptr[0], ptr[0] + fl)
      });
      ptr[0] += fl;
    });
    if ((_a = ai[3]) == null ? void 0 : _a[0])
      res.merge = varint_to_i32(ai[3][0].data) >>> 0 > 0;
    out.push(res);
  }
  return out;
}
function write_iwa_file(ias) {
  var bufs = [];
  ias.forEach(function(ia) {
    var ai = [];
    ai[1] = [{ data: write_varint49(ia.id), type: 0 }];
    ai[2] = [];
    if (ia.merge != null)
      ai[3] = [{ data: write_varint49(+!!ia.merge), type: 0 }];
    var midata = [];
    ia.messages.forEach(function(mi) {
      midata.push(mi.data);
      mi.meta[3] = [{ type: 0, data: write_varint49(mi.data.length) }];
      ai[2].push({ data: write_shallow(mi.meta), type: 2 });
    });
    var aipayload = write_shallow(ai);
    bufs.push(write_varint49(aipayload.length));
    bufs.push(aipayload);
    midata.forEach(function(mid) {
      return bufs.push(mid);
    });
  });
  return u8concat(bufs);
}
function parse_snappy_chunk(type, buf) {
  if (type != 0)
    throw new Error("Unexpected Snappy chunk type ".concat(type));
  var ptr = [0];
  var usz = parse_varint49(buf, ptr);
  var chunks = [];
  while (ptr[0] < buf.length) {
    var tag = buf[ptr[0]] & 3;
    if (tag == 0) {
      var len = buf[ptr[0]++] >> 2;
      if (len < 60)
        ++len;
      else {
        var c = len - 59;
        len = buf[ptr[0]];
        if (c > 1)
          len |= buf[ptr[0] + 1] << 8;
        if (c > 2)
          len |= buf[ptr[0] + 2] << 16;
        if (c > 3)
          len |= buf[ptr[0] + 3] << 24;
        len >>>= 0;
        len++;
        ptr[0] += c;
      }
      chunks.push(buf.slice(ptr[0], ptr[0] + len));
      ptr[0] += len;
      continue;
    } else {
      var offset = 0, length = 0;
      if (tag == 1) {
        length = (buf[ptr[0]] >> 2 & 7) + 4;
        offset = (buf[ptr[0]++] & 224) << 3;
        offset |= buf[ptr[0]++];
      } else {
        length = (buf[ptr[0]++] >> 2) + 1;
        if (tag == 2) {
          offset = buf[ptr[0]] | buf[ptr[0] + 1] << 8;
          ptr[0] += 2;
        } else {
          offset = (buf[ptr[0]] | buf[ptr[0] + 1] << 8 | buf[ptr[0] + 2] << 16 | buf[ptr[0] + 3] << 24) >>> 0;
          ptr[0] += 4;
        }
      }
      chunks = [u8concat(chunks)];
      if (offset == 0)
        throw new Error("Invalid offset 0");
      if (offset > chunks[0].length)
        throw new Error("Invalid offset beyond length");
      if (length >= offset) {
        chunks.push(chunks[0].slice(-offset));
        length -= offset;
        while (length >= chunks[chunks.length - 1].length) {
          chunks.push(chunks[chunks.length - 1]);
          length -= chunks[chunks.length - 1].length;
        }
      }
      chunks.push(chunks[0].slice(-offset, -offset + length));
    }
  }
  var o = u8concat(chunks);
  if (o.length != usz)
    throw new Error("Unexpected length: ".concat(o.length, " != ").concat(usz));
  return o;
}
function decompress_iwa_file(buf) {
  var out = [];
  var l = 0;
  while (l < buf.length) {
    var t = buf[l++];
    var len = buf[l] | buf[l + 1] << 8 | buf[l + 2] << 16;
    l += 3;
    out.push(parse_snappy_chunk(t, buf.slice(l, l + len)));
    l += len;
  }
  if (l !== buf.length)
    throw new Error("data is not a valid framed stream!");
  return u8concat(out);
}
function compress_iwa_file(buf) {
  var out = [];
  var l = 0;
  while (l < buf.length) {
    var c = Math.min(buf.length - l, 268435455);
    var frame = new Uint8Array(4);
    out.push(frame);
    var usz = write_varint49(c);
    var L = usz.length;
    out.push(usz);
    if (c <= 60) {
      L++;
      out.push(new Uint8Array([c - 1 << 2]));
    } else if (c <= 256) {
      L += 2;
      out.push(new Uint8Array([240, c - 1 & 255]));
    } else if (c <= 65536) {
      L += 3;
      out.push(new Uint8Array([244, c - 1 & 255, c - 1 >> 8 & 255]));
    } else if (c <= 16777216) {
      L += 4;
      out.push(new Uint8Array([248, c - 1 & 255, c - 1 >> 8 & 255, c - 1 >> 16 & 255]));
    } else if (c <= 4294967296) {
      L += 5;
      out.push(new Uint8Array([252, c - 1 & 255, c - 1 >> 8 & 255, c - 1 >> 16 & 255, c - 1 >>> 24 & 255]));
    }
    out.push(buf.slice(l, l + c));
    L += c;
    frame[0] = 0;
    frame[1] = L & 255;
    frame[2] = L >> 8 & 255;
    frame[3] = L >> 16 & 255;
    l += c;
  }
  return u8concat(out);
}
function parse_old_storage(buf, sst, rsst, v) {
  var dv = u8_to_dataview(buf);
  var flags = dv.getUint32(4, true);
  var data_offset = (v > 1 ? 12 : 8) + popcnt(flags & (v > 1 ? 3470 : 398)) * 4;
  var ridx = -1, sidx = -1, ieee = NaN, dt = new Date(2001, 0, 1);
  if (flags & 512) {
    ridx = dv.getUint32(data_offset, true);
    data_offset += 4;
  }
  data_offset += popcnt(flags & (v > 1 ? 12288 : 4096)) * 4;
  if (flags & 16) {
    sidx = dv.getUint32(data_offset, true);
    data_offset += 4;
  }
  if (flags & 32) {
    ieee = dv.getFloat64(data_offset, true);
    data_offset += 8;
  }
  if (flags & 64) {
    dt.setTime(dt.getTime() + dv.getFloat64(data_offset, true) * 1e3);
    data_offset += 8;
  }
  var ret;
  switch (buf[2]) {
    case 0:
      break;
    case 2:
      ret = { t: "n", v: ieee };
      break;
    case 3:
      ret = { t: "s", v: sst[sidx] };
      break;
    case 5:
      ret = { t: "d", v: dt };
      break;
    case 6:
      ret = { t: "b", v: ieee > 0 };
      break;
    case 7:
      ret = { t: "n", v: ieee / 86400 };
      break;
    case 8:
      ret = { t: "e", v: 0 };
      break;
    case 9:
      {
        if (ridx > -1)
          ret = { t: "s", v: rsst[ridx] };
        else if (sidx > -1)
          ret = { t: "s", v: sst[sidx] };
        else if (!isNaN(ieee))
          ret = { t: "n", v: ieee };
        else
          throw new Error("Unsupported cell type ".concat(buf.slice(0, 4)));
      }
      break;
    default:
      throw new Error("Unsupported cell type ".concat(buf.slice(0, 4)));
  }
  return ret;
}
function parse_new_storage(buf, sst, rsst) {
  var dv = u8_to_dataview(buf);
  var flags = dv.getUint32(8, true);
  var data_offset = 12;
  var ridx = -1, sidx = -1, d128 = NaN, ieee = NaN, dt = new Date(2001, 0, 1);
  if (flags & 1) {
    d128 = readDecimal128LE(buf, data_offset);
    data_offset += 16;
  }
  if (flags & 2) {
    ieee = dv.getFloat64(data_offset, true);
    data_offset += 8;
  }
  if (flags & 4) {
    dt.setTime(dt.getTime() + dv.getFloat64(data_offset, true) * 1e3);
    data_offset += 8;
  }
  if (flags & 8) {
    sidx = dv.getUint32(data_offset, true);
    data_offset += 4;
  }
  if (flags & 16) {
    ridx = dv.getUint32(data_offset, true);
    data_offset += 4;
  }
  var ret;
  switch (buf[1]) {
    case 0:
      break;
    case 2:
      ret = { t: "n", v: d128 };
      break;
    case 3:
      ret = { t: "s", v: sst[sidx] };
      break;
    case 5:
      ret = { t: "d", v: dt };
      break;
    case 6:
      ret = { t: "b", v: ieee > 0 };
      break;
    case 7:
      ret = { t: "n", v: ieee / 86400 };
      break;
    case 8:
      ret = { t: "e", v: 0 };
      break;
    case 9:
      {
        if (ridx > -1)
          ret = { t: "s", v: rsst[ridx] };
        else
          throw new Error("Unsupported cell type ".concat(buf[1], " : ").concat(flags & 31, " : ").concat(buf.slice(0, 4)));
      }
      break;
    case 10:
      ret = { t: "n", v: d128 };
      break;
    default:
      throw new Error("Unsupported cell type ".concat(buf[1], " : ").concat(flags & 31, " : ").concat(buf.slice(0, 4)));
  }
  return ret;
}
function write_new_storage(cell, sst) {
  var out = new Uint8Array(32), dv = u8_to_dataview(out), l = 12, flags = 0;
  out[0] = 5;
  switch (cell.t) {
    case "n":
      out[1] = 2;
      writeDecimal128LE(out, l, cell.v);
      flags |= 1;
      l += 16;
      break;
    case "b":
      out[1] = 6;
      dv.setFloat64(l, cell.v ? 1 : 0, true);
      flags |= 2;
      l += 8;
      break;
    case "s":
      if (sst.indexOf(cell.v) == -1)
        throw new Error("Value ".concat(cell.v, " missing from SST!"));
      out[1] = 3;
      dv.setUint32(l, sst.indexOf(cell.v), true);
      flags |= 8;
      l += 4;
      break;
    default:
      throw "unsupported cell type " + cell.t;
  }
  dv.setUint32(8, flags, true);
  return out.slice(0, l);
}
function write_old_storage(cell, sst) {
  var out = new Uint8Array(32), dv = u8_to_dataview(out), l = 12, flags = 0;
  out[0] = 3;
  switch (cell.t) {
    case "n":
      out[2] = 2;
      dv.setFloat64(l, cell.v, true);
      flags |= 32;
      l += 8;
      break;
    case "b":
      out[2] = 6;
      dv.setFloat64(l, cell.v ? 1 : 0, true);
      flags |= 32;
      l += 8;
      break;
    case "s":
      if (sst.indexOf(cell.v) == -1)
        throw new Error("Value ".concat(cell.v, " missing from SST!"));
      out[2] = 3;
      dv.setUint32(l, sst.indexOf(cell.v), true);
      flags |= 16;
      l += 4;
      break;
    default:
      throw "unsupported cell type " + cell.t;
  }
  dv.setUint32(4, flags, true);
  return out.slice(0, l);
}
function parse_cell_storage(buf, sst, rsst) {
  switch (buf[0]) {
    case 0:
    case 1:
    case 2:
    case 3:
      return parse_old_storage(buf, sst, rsst, buf[0]);
    case 5:
      return parse_new_storage(buf, sst, rsst);
    default:
      throw new Error("Unsupported payload version ".concat(buf[0]));
  }
}
function parse_TSP_Reference(buf) {
  var pb = parse_shallow(buf);
  return parse_varint49(pb[1][0].data);
}
function write_TSP_Reference(idx) {
  var out = [];
  out[1] = [{ type: 0, data: write_varint49(idx) }];
  return write_shallow(out);
}
function parse_TST_TableDataList(M, root) {
  var pb = parse_shallow(root.data);
  var type = varint_to_i32(pb[1][0].data);
  var entries = pb[3];
  var data = [];
  (entries || []).forEach(function(entry) {
    var le = parse_shallow(entry.data);
    var key = varint_to_i32(le[1][0].data) >>> 0;
    switch (type) {
      case 1:
        data[key] = u8str(le[3][0].data);
        break;
      case 8:
        {
          var rt = M[parse_TSP_Reference(le[9][0].data)][0];
          var rtp = parse_shallow(rt.data);
          var rtpref = M[parse_TSP_Reference(rtp[1][0].data)][0];
          var mtype = varint_to_i32(rtpref.meta[1][0].data);
          if (mtype != 2001)
            throw new Error("2000 unexpected reference to ".concat(mtype));
          var tswpsa = parse_shallow(rtpref.data);
          data[key] = tswpsa[3].map(function(x) {
            return u8str(x.data);
          }).join("");
        }
        break;
    }
  });
  return data;
}
function parse_TST_TileRowInfo(u8, type) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
  var pb = parse_shallow(u8);
  var R = varint_to_i32(pb[1][0].data) >>> 0;
  var cnt = varint_to_i32(pb[2][0].data) >>> 0;
  var wide_offsets = ((_b = (_a = pb[8]) == null ? void 0 : _a[0]) == null ? void 0 : _b.data) && varint_to_i32(pb[8][0].data) > 0 || false;
  var used_storage_u8, used_storage;
  if (((_d = (_c = pb[7]) == null ? void 0 : _c[0]) == null ? void 0 : _d.data) && type != 0) {
    used_storage_u8 = (_f = (_e = pb[7]) == null ? void 0 : _e[0]) == null ? void 0 : _f.data;
    used_storage = (_h = (_g = pb[6]) == null ? void 0 : _g[0]) == null ? void 0 : _h.data;
  } else if (((_j = (_i = pb[4]) == null ? void 0 : _i[0]) == null ? void 0 : _j.data) && type != 1) {
    used_storage_u8 = (_l = (_k = pb[4]) == null ? void 0 : _k[0]) == null ? void 0 : _l.data;
    used_storage = (_n = (_m = pb[3]) == null ? void 0 : _m[0]) == null ? void 0 : _n.data;
  } else
    throw "NUMBERS Tile missing ".concat(type, " cell storage");
  var width = wide_offsets ? 4 : 1;
  var used_storage_offsets = u8_to_dataview(used_storage_u8);
  var offsets = [];
  for (var C = 0; C < used_storage_u8.length / 2; ++C) {
    var off = used_storage_offsets.getUint16(C * 2, true);
    if (off < 65535)
      offsets.push([C, off]);
  }
  if (offsets.length != cnt)
    throw "Expected ".concat(cnt, " cells, found ").concat(offsets.length);
  var cells = [];
  for (C = 0; C < offsets.length - 1; ++C)
    cells[offsets[C][0]] = used_storage.subarray(offsets[C][1] * width, offsets[C + 1][1] * width);
  if (offsets.length >= 1)
    cells[offsets[offsets.length - 1][0]] = used_storage.subarray(offsets[offsets.length - 1][1] * width);
  return { R: R, cells: cells };
}
function parse_TST_Tile(M, root) {
  var _a;
  var pb = parse_shallow(root.data);
  var storage = ((_a = pb == null ? void 0 : pb[7]) == null ? void 0 : _a[0]) ? varint_to_i32(pb[7][0].data) >>> 0 > 0 ? 1 : 0 : -1;
  var ri = mappa(pb[5], function(u8) {
    return parse_TST_TileRowInfo(u8, storage);
  });
  return {
    nrows: varint_to_i32(pb[4][0].data) >>> 0,
    data: ri.reduce(function(acc, x) {
      if (!acc[x.R])
        acc[x.R] = [];
      x.cells.forEach(function(cell, C) {
        if (acc[x.R][C])
          throw new Error("Duplicate cell r=".concat(x.R, " c=").concat(C));
        acc[x.R][C] = cell;
      });
      return acc;
    }, [])
  };
}
function parse_TST_TableModelArchive(M, root, ws) {
  var _a;
  var pb = parse_shallow(root.data);
  var range = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
  range.e.r = (varint_to_i32(pb[6][0].data) >>> 0) - 1;
  if (range.e.r < 0)
    throw new Error("Invalid row varint ".concat(pb[6][0].data));
  range.e.c = (varint_to_i32(pb[7][0].data) >>> 0) - 1;
  if (range.e.c < 0)
    throw new Error("Invalid col varint ".concat(pb[7][0].data));
  ws["!ref"] = encode_range(range);
  var store = parse_shallow(pb[4][0].data);
  var sst = parse_TST_TableDataList(M, M[parse_TSP_Reference(store[4][0].data)][0]);
  var rsst = ((_a = store[17]) == null ? void 0 : _a[0]) ? parse_TST_TableDataList(M, M[parse_TSP_Reference(store[17][0].data)][0]) : [];
  var tile = parse_shallow(store[3][0].data);
  var _R = 0;
  tile[1].forEach(function(t) {
    var tl = parse_shallow(t.data);
    var ref = M[parse_TSP_Reference(tl[2][0].data)][0];
    var mtype = varint_to_i32(ref.meta[1][0].data);
    if (mtype != 6002)
      throw new Error("6001 unexpected reference to ".concat(mtype));
    var _tile = parse_TST_Tile(M, ref);
    _tile.data.forEach(function(row, R) {
      row.forEach(function(buf, C) {
        var addr = encode_cell({ r: _R + R, c: C });
        var res = parse_cell_storage(buf, sst, rsst);
        if (res)
          ws[addr] = res;
      });
    });
    _R += _tile.nrows;
  });
}
function parse_TST_TableInfoArchive(M, root) {
  var pb = parse_shallow(root.data);
  var out = { "!ref": "A1" };
  var tableref = M[parse_TSP_Reference(pb[2][0].data)];
  var mtype = varint_to_i32(tableref[0].meta[1][0].data);
  if (mtype != 6001)
    throw new Error("6000 unexpected reference to ".concat(mtype));
  parse_TST_TableModelArchive(M, tableref[0], out);
  return out;
}
function parse_TN_SheetArchive(M, root) {
  var _a;
  var pb = parse_shallow(root.data);
  var out = {
    name: ((_a = pb[1]) == null ? void 0 : _a[0]) ? u8str(pb[1][0].data) : "",
    sheets: []
  };
  var shapeoffs = mappa(pb[2], parse_TSP_Reference);
  shapeoffs.forEach(function(off) {
    M[off].forEach(function(m) {
      var mtype = varint_to_i32(m.meta[1][0].data);
      if (mtype == 6e3)
        out.sheets.push(parse_TST_TableInfoArchive(M, m));
    });
  });
  return out;
}
function parse_TN_DocumentArchive(M, root) {
  var out = book_new();
  var pb = parse_shallow(root.data);
  var sheetoffs = mappa(pb[1], parse_TSP_Reference);
  sheetoffs.forEach(function(off) {
    M[off].forEach(function(m) {
      var mtype = varint_to_i32(m.meta[1][0].data);
      if (mtype == 2) {
        var root2 = parse_TN_SheetArchive(M, m);
        root2.sheets.forEach(function(sheet, idx) {
          book_append_sheet(out, sheet, idx == 0 ? root2.name : root2.name + "_" + idx, true);
        });
      }
    });
  });
  if (out.SheetNames.length == 0)
    throw new Error("Empty NUMBERS file");
  return out;
}
function parse_numbers_iwa(cfb) {
  var _a, _b, _c, _d;
  var M = {}, indices = [];
  cfb.FullPaths.forEach(function(p) {
    if (p.match(/\.iwpv2/))
      throw new Error("Unsupported password protection");
  });
  cfb.FileIndex.forEach(function(s) {
    if (!s.name.match(/\.iwa$/))
      return;
    var o;
    try {
      o = decompress_iwa_file(s.content);
    } catch (e) {
      return console.log("?? " + s.content.length + " " + (e.message || e));
    }
    var packets;
    try {
      packets = parse_iwa_file(o);
    } catch (e) {
      return console.log("## " + (e.message || e));
    }
    packets.forEach(function(packet) {
      M[packet.id] = packet.messages;
      indices.push(packet.id);
    });
  });
  if (!indices.length)
    throw new Error("File has no messages");
  var docroot = ((_d = (_c = (_b = (_a = M == null ? void 0 : M[1]) == null ? void 0 : _a[0]) == null ? void 0 : _b.meta) == null ? void 0 : _c[1]) == null ? void 0 : _d[0].data) && varint_to_i32(M[1][0].meta[1][0].data) == 1 && M[1][0];
  if (!docroot)
    indices.forEach(function(idx) {
      M[idx].forEach(function(iwam) {
        var mtype = varint_to_i32(iwam.meta[1][0].data) >>> 0;
        if (mtype == 1) {
          if (!docroot)
            docroot = iwam;
          else
            throw new Error("Document has multiple roots");
        }
      });
    });
  if (!docroot)
    throw new Error("Cannot find Document root");
  return parse_TN_DocumentArchive(M, docroot);
}
function write_tile_row(tri, data, SST) {
  var _a, _b, _c, _d;
  if (!((_a = tri[6]) == null ? void 0 : _a[0]) || !((_b = tri[7]) == null ? void 0 : _b[0]))
    throw "Mutation only works on post-BNC storages!";
  var wide_offsets = ((_d = (_c = tri[8]) == null ? void 0 : _c[0]) == null ? void 0 : _d.data) && varint_to_i32(tri[8][0].data) > 0 || false;
  if (wide_offsets)
    throw "Math only works with normal offsets";
  var cnt = 0;
  var dv = u8_to_dataview(tri[7][0].data), last_offset = 0, cell_storage = [];
  var _dv = u8_to_dataview(tri[4][0].data), _last_offset = 0, _cell_storage = [];
  for (var C = 0; C < data.length; ++C) {
    if (data[C] == null) {
      dv.setUint16(C * 2, 65535, true);
      _dv.setUint16(C * 2, 65535);
      continue;
    }
    dv.setUint16(C * 2, last_offset, true);
    _dv.setUint16(C * 2, _last_offset, true);
    var celload, _celload;
    switch (typeof data[C]) {
      case "string":
        celload = write_new_storage({ t: "s", v: data[C] }, SST);
        _celload = write_old_storage({ t: "s", v: data[C] }, SST);
        break;
      case "number":
        celload = write_new_storage({ t: "n", v: data[C] }, SST);
        _celload = write_old_storage({ t: "n", v: data[C] }, SST);
        break;
      case "boolean":
        celload = write_new_storage({ t: "b", v: data[C] }, SST);
        _celload = write_old_storage({ t: "b", v: data[C] }, SST);
        break;
      default:
        throw new Error("Unsupported value " + data[C]);
    }
    cell_storage.push(celload);
    last_offset += celload.length;
    _cell_storage.push(_celload);
    _last_offset += _celload.length;
    ++cnt;
  }
  tri[2][0].data = write_varint49(cnt);
  for (; C < tri[7][0].data.length / 2; ++C) {
    dv.setUint16(C * 2, 65535, true);
    _dv.setUint16(C * 2, 65535, true);
  }
  tri[6][0].data = u8concat(cell_storage);
  tri[3][0].data = u8concat(_cell_storage);
  return cnt;
}
function write_numbers_iwa(wb, opts) {
  if (!opts || !opts.numbers)
    throw new Error("Must pass a `numbers` option -- check the README");
  var ws = wb.Sheets[wb.SheetNames[0]];
  if (wb.SheetNames.length > 1)
    console.error("The Numbers writer currently writes only the first table");
  var range = decode_range(ws["!ref"]);
  range.s.r = range.s.c = 0;
  var trunc = false;
  if (range.e.c > 9) {
    trunc = true;
    range.e.c = 9;
  }
  if (range.e.r > 49) {
    trunc = true;
    range.e.r = 49;
  }
  if (trunc)
    console.error("The Numbers writer is currently limited to ".concat(encode_range(range)));
  var data = sheet_to_json(ws, { range: range, header: 1 });
  var SST = ["~Sh33tJ5~"];
  data.forEach(function(row) {
    return row.forEach(function(cell) {
      if (typeof cell == "string")
        SST.push(cell);
    });
  });
  var dependents = {};
  var indices = [];
  var cfb = CFB.read(opts.numbers, { type: "base64" });
  cfb.FileIndex.map(function(fi, idx) {
    return [fi, cfb.FullPaths[idx]];
  }).forEach(function(row) {
    var fi = row[0], fp = row[1];
    if (fi.type != 2)
      return;
    if (!fi.name.match(/\.iwa/))
      return;
    var old_content = fi.content;
    var raw1 = decompress_iwa_file(old_content);
    var x2 = parse_iwa_file(raw1);
    x2.forEach(function(packet2) {
      indices.push(packet2.id);
      dependents[packet2.id] = { deps: [], location: fp, type: varint_to_i32(packet2.messages[0].meta[1][0].data) };
    });
  });
  indices.sort(function(x2, y2) {
    return x2 - y2;
  });
  var indices_varint = indices.filter(function(x2) {
    return x2 > 1;
  }).map(function(x2) {
    return [x2, write_varint49(x2)];
  });
  cfb.FileIndex.map(function(fi, idx) {
    return [fi, cfb.FullPaths[idx]];
  }).forEach(function(row) {
    var fi = row[0], fp = row[1];
    if (!fi.name.match(/\.iwa/))
      return;
    var x2 = parse_iwa_file(decompress_iwa_file(fi.content));
    x2.forEach(function(ia) {
      ia.messages.forEach(function(m) {
        indices_varint.forEach(function(ivi) {
          if (ia.messages.some(function(mess) {
            return varint_to_i32(mess.meta[1][0].data) != 11006 && u8contains(mess.data, ivi[1]);
          })) {
            dependents[ivi[0]].deps.push(ia.id);
          }
        });
      });
    });
  });
  function get_unique_msgid() {
    for (var i = 927262; i < 2e6; ++i)
      if (!dependents[i])
        return i;
    throw new Error("Too many messages");
  }
  var entry = CFB.find(cfb, dependents[1].location);
  var x = parse_iwa_file(decompress_iwa_file(entry.content));
  var docroot;
  for (var xi = 0; xi < x.length; ++xi) {
    var packet = x[xi];
    if (packet.id == 1)
      docroot = packet;
  }
  var sheetrootref = parse_TSP_Reference(parse_shallow(docroot.messages[0].data)[1][0].data);
  entry = CFB.find(cfb, dependents[sheetrootref].location);
  x = parse_iwa_file(decompress_iwa_file(entry.content));
  for (xi = 0; xi < x.length; ++xi) {
    packet = x[xi];
    if (packet.id == sheetrootref)
      docroot = packet;
  }
  sheetrootref = parse_TSP_Reference(parse_shallow(docroot.messages[0].data)[2][0].data);
  entry = CFB.find(cfb, dependents[sheetrootref].location);
  x = parse_iwa_file(decompress_iwa_file(entry.content));
  for (xi = 0; xi < x.length; ++xi) {
    packet = x[xi];
    if (packet.id == sheetrootref)
      docroot = packet;
  }
  sheetrootref = parse_TSP_Reference(parse_shallow(docroot.messages[0].data)[2][0].data);
  entry = CFB.find(cfb, dependents[sheetrootref].location);
  x = parse_iwa_file(decompress_iwa_file(entry.content));
  for (xi = 0; xi < x.length; ++xi) {
    packet = x[xi];
    if (packet.id == sheetrootref)
      docroot = packet;
  }
  var pb = parse_shallow(docroot.messages[0].data);
  {
    pb[6][0].data = write_varint49(range.e.r + 1);
    pb[7][0].data = write_varint49(range.e.c + 1);
    var cruidsref = parse_TSP_Reference(pb[46][0].data);
    var oldbucket = CFB.find(cfb, dependents[cruidsref].location);
    var _x = parse_iwa_file(decompress_iwa_file(oldbucket.content));
    {
      for (var j = 0; j < _x.length; ++j) {
        if (_x[j].id == cruidsref)
          break;
      }
      if (_x[j].id != cruidsref)
        throw "Bad ColumnRowUIDMapArchive";
      var cruids = parse_shallow(_x[j].messages[0].data);
      cruids[1] = [];
      cruids[2] = [], cruids[3] = [];
      for (var C = 0; C <= range.e.c; ++C) {
        var uuid = [];
        uuid[1] = uuid[2] = [{ type: 0, data: write_varint49(C + 420690) }];
        cruids[1].push({ type: 2, data: write_shallow(uuid) });
        cruids[2].push({ type: 0, data: write_varint49(C) });
        cruids[3].push({ type: 0, data: write_varint49(C) });
      }
      cruids[4] = [];
      cruids[5] = [], cruids[6] = [];
      for (var R = 0; R <= range.e.r; ++R) {
        uuid = [];
        uuid[1] = uuid[2] = [{ type: 0, data: write_varint49(R + 726270) }];
        cruids[4].push({ type: 2, data: write_shallow(uuid) });
        cruids[5].push({ type: 0, data: write_varint49(R) });
        cruids[6].push({ type: 0, data: write_varint49(R) });
      }
      _x[j].messages[0].data = write_shallow(cruids);
    }
    oldbucket.content = compress_iwa_file(write_iwa_file(_x));
    oldbucket.size = oldbucket.content.length;
    delete pb[46];
    var store = parse_shallow(pb[4][0].data);
    {
      store[7][0].data = write_varint49(range.e.r + 1);
      var row_headers = parse_shallow(store[1][0].data);
      var row_header_ref = parse_TSP_Reference(row_headers[2][0].data);
      oldbucket = CFB.find(cfb, dependents[row_header_ref].location);
      _x = parse_iwa_file(decompress_iwa_file(oldbucket.content));
      {
        if (_x[0].id != row_header_ref)
          throw "Bad HeaderStorageBucket";
        var base_bucket = parse_shallow(_x[0].messages[0].data);
        for (R = 0; R < data.length; ++R) {
          var _bucket = parse_shallow(base_bucket[2][0].data);
          _bucket[1][0].data = write_varint49(R);
          _bucket[4][0].data = write_varint49(data[R].length);
          base_bucket[2][R] = { type: base_bucket[2][0].type, data: write_shallow(_bucket) };
        }
        _x[0].messages[0].data = write_shallow(base_bucket);
      }
      oldbucket.content = compress_iwa_file(write_iwa_file(_x));
      oldbucket.size = oldbucket.content.length;
      var col_header_ref = parse_TSP_Reference(store[2][0].data);
      oldbucket = CFB.find(cfb, dependents[col_header_ref].location);
      _x = parse_iwa_file(decompress_iwa_file(oldbucket.content));
      {
        if (_x[0].id != col_header_ref)
          throw "Bad HeaderStorageBucket";
        base_bucket = parse_shallow(_x[0].messages[0].data);
        for (C = 0; C <= range.e.c; ++C) {
          _bucket = parse_shallow(base_bucket[2][0].data);
          _bucket[1][0].data = write_varint49(C);
          _bucket[4][0].data = write_varint49(range.e.r + 1);
          base_bucket[2][C] = { type: base_bucket[2][0].type, data: write_shallow(_bucket) };
        }
        _x[0].messages[0].data = write_shallow(base_bucket);
      }
      oldbucket.content = compress_iwa_file(write_iwa_file(_x));
      oldbucket.size = oldbucket.content.length;
      var sstref = parse_TSP_Reference(store[4][0].data);
      (function() {
        var sentry = CFB.find(cfb, dependents[sstref].location);
        var sx = parse_iwa_file(decompress_iwa_file(sentry.content));
        var sstroot;
        for (var sxi = 0; sxi < sx.length; ++sxi) {
          var packet2 = sx[sxi];
          if (packet2.id == sstref)
            sstroot = packet2;
        }
        var sstdata = parse_shallow(sstroot.messages[0].data);
        {
          sstdata[3] = [];
          var newsst = [];
          SST.forEach(function(str, i) {
            newsst[1] = [{ type: 0, data: write_varint49(i) }];
            newsst[2] = [{ type: 0, data: write_varint49(1) }];
            newsst[3] = [{ type: 2, data: stru8(str) }];
            sstdata[3].push({ type: 2, data: write_shallow(newsst) });
          });
        }
        sstroot.messages[0].data = write_shallow(sstdata);
        var sy = write_iwa_file(sx);
        var raw32 = compress_iwa_file(sy);
        sentry.content = raw32;
        sentry.size = sentry.content.length;
      })();
      var tile = parse_shallow(store[3][0].data);
      {
        var t = tile[1][0];
        delete tile[2];
        var tl = parse_shallow(t.data);
        {
          var tileref = parse_TSP_Reference(tl[2][0].data);
          (function() {
            var tentry = CFB.find(cfb, dependents[tileref].location);
            var tx = parse_iwa_file(decompress_iwa_file(tentry.content));
            var tileroot;
            for (var sxi = 0; sxi < tx.length; ++sxi) {
              var packet2 = tx[sxi];
              if (packet2.id == tileref)
                tileroot = packet2;
            }
            var tiledata = parse_shallow(tileroot.messages[0].data);
            {
              delete tiledata[6];
              delete tile[7];
              var rowload = new Uint8Array(tiledata[5][0].data);
              tiledata[5] = [];
              var cnt = 0;
              for (var R2 = 0; R2 <= range.e.r; ++R2) {
                var tilerow = parse_shallow(rowload);
                cnt += write_tile_row(tilerow, data[R2], SST);
                tilerow[1][0].data = write_varint49(R2);
                tiledata[5].push({ data: write_shallow(tilerow), type: 2 });
              }
              tiledata[1] = [{ type: 0, data: write_varint49(range.e.c + 1) }];
              tiledata[2] = [{ type: 0, data: write_varint49(range.e.r + 1) }];
              tiledata[3] = [{ type: 0, data: write_varint49(cnt) }];
              tiledata[4] = [{ type: 0, data: write_varint49(range.e.r + 1) }];
            }
            tileroot.messages[0].data = write_shallow(tiledata);
            var ty = write_iwa_file(tx);
            var raw32 = compress_iwa_file(ty);
            tentry.content = raw32;
            tentry.size = tentry.content.length;
          })();
        }
        t.data = write_shallow(tl);
      }
      store[3][0].data = write_shallow(tile);
    }
    pb[4][0].data = write_shallow(store);
  }
  docroot.messages[0].data = write_shallow(pb);
  var y = write_iwa_file(x);
  var raw3 = compress_iwa_file(y);
  entry.content = raw3;
  entry.size = entry.content.length;
  return cfb;
}
function fix_opts_func(defaults/*:Array<Array<any> >*/)/*:{(o:any):void}*/ {
	return function fix_opts(opts) {
		for(var i = 0; i != defaults.length; ++i) {
			var d = defaults[i];
			if(opts[d[0]] === undefined) opts[d[0]] = d[1];
			if(d[2] === 'n') opts[d[0]] = Number(opts[d[0]]);
		}
	};
}

function fix_read_opts(opts) {
fix_opts_func([
	['cellNF', false], /* emit cell number format string as .z */
	['cellHTML', true], /* emit html string as .h */
	['cellFormula', true], /* emit formulae as .f */
	['cellStyles', false], /* emits style/theme as .s */
	['cellText', true], /* emit formatted text as .w */
	['cellDates', false], /* emit date cells with type `d` */

	['sheetStubs', false], /* emit empty cells */
	['sheetRows', 0, 'n'], /* read n rows (0 = read all rows) */

	['bookDeps', false], /* parse calculation chains */
	['bookSheets', false], /* only try to get sheet names (no Sheets) */
	['bookProps', false], /* only try to get properties (no Sheets) */
	['bookFiles', false], /* include raw file structure (keys, files, cfb) */
	['bookVBA', false], /* include vba raw data (vbaraw) */

	['password',''], /* password */
	['WTF', false] /* WTF mode (throws errors) */
])(opts);
}

function fix_write_opts(opts) {
fix_opts_func([
	['cellDates', false], /* write date cells with type `d` */

	['bookSST', false], /* Generate Shared String Table */

	['bookType', 'xlsx'], /* Type of workbook (xlsx/m/b) */

	['compression', false], /* Use file compression */

	['WTF', false] /* WTF mode (throws errors) */
])(opts);
}
function get_sheet_type(n/*:string*/)/*:string*/ {
	if(RELS.WS.indexOf(n) > -1) return "sheet";
	if(RELS.CS && n == RELS.CS) return "chart";
	if(RELS.DS && n == RELS.DS) return "dialog";
	if(RELS.MS && n == RELS.MS) return "macro";
	return (n && n.length) ? n : "sheet";
}
function safe_parse_wbrels(wbrels, sheets) {
	if(!wbrels) return 0;
	try {
		wbrels = sheets.map(function pwbr(w) { if(!w.id) w.id = w.strRelID; return [w.name, wbrels['!id'][w.id].Target, get_sheet_type(wbrels['!id'][w.id].Type)]; });
	} catch(e) { return null; }
	return !wbrels || wbrels.length === 0 ? null : wbrels;
}

function safe_parse_sheet(zip, path/*:string*/, relsPath/*:string*/, sheet, idx/*:number*/, sheetRels, sheets, stype/*:string*/, opts, wb, themes, styles) {
	try {
		sheetRels[sheet]=parse_rels(getzipstr(zip, relsPath, true), path);
		var data = getzipdata(zip, path);
		var _ws;
		switch(stype) {
			case 'sheet':  _ws = parse_ws(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
			case 'chart':  _ws = parse_cs(data, path, idx, opts, sheetRels[sheet], wb, themes, styles);
				if(!_ws || !_ws['!drawel']) break;
				var dfile = resolve_path(_ws['!drawel'].Target, path);
				var drelsp = get_rels_path(dfile);
				var draw = parse_drawing(getzipstr(zip, dfile, true), parse_rels(getzipstr(zip, drelsp, true), dfile));
				var chartp = resolve_path(draw, dfile);
				var crelsp = get_rels_path(chartp);
				_ws = parse_chart(getzipstr(zip, chartp, true), chartp, opts, parse_rels(getzipstr(zip, crelsp, true), chartp), wb, _ws);
				break;
			case 'macro':  _ws = parse_ms(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
			case 'dialog': _ws = parse_ds(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
			default: throw new Error("Unrecognized sheet type " + stype);
		}
		sheets[sheet] = _ws;

		/* scan rels for comments and threaded comments */
		var tcomments = [];
		if(sheetRels && sheetRels[sheet]) keys(sheetRels[sheet]).forEach(function(n) {
			var dfile = "";
			if(sheetRels[sheet][n].Type == RELS.CMNT) {
				dfile = resolve_path(sheetRels[sheet][n].Target, path);
				var comments = parse_cmnt(getzipdata(zip, dfile, true), dfile, opts);
				if(!comments || !comments.length) return;
				sheet_insert_comments(_ws, comments, false);
			}
			if(sheetRels[sheet][n].Type == RELS.TCMNT) {
				dfile = resolve_path(sheetRels[sheet][n].Target, path);
				tcomments = tcomments.concat(parse_tcmnt_xml(getzipdata(zip, dfile, true), opts));
			}
		});
		if(tcomments && tcomments.length) sheet_insert_comments(_ws, tcomments, true, opts.people || []);
	} catch(e) { if(opts.WTF) throw e; }
}

function strip_front_slash(x/*:string*/)/*:string*/ { return x.charAt(0) == '/' ? x.slice(1) : x; }

function parse_zip(zip/*:ZIP*/, opts/*:?ParseOpts*/)/*:Workbook*/ {
	make_ssf();
	opts = opts || {};
	fix_read_opts(opts);

	/* OpenDocument Part 3 Section 2.2.1 OpenDocument Package */
	if(safegetzipfile(zip, 'META-INF/manifest.xml')) return parse_ods(zip, opts);
	/* UOC */
	if(safegetzipfile(zip, 'objectdata.xml')) return parse_ods(zip, opts);
	/* Numbers */
	if(safegetzipfile(zip, 'Index/Document.iwa')) {
		if(typeof Uint8Array == "undefined") throw new Error('NUMBERS file parsing requires Uint8Array support');
		if(typeof parse_numbers_iwa != "undefined") {
			if(zip.FileIndex) return parse_numbers_iwa(zip);
			var _zip = CFB.utils.cfb_new();
			zipentries(zip).forEach(function(e) { zip_add_file(_zip, e, getzipbin(zip, e)); });
			return parse_numbers_iwa(_zip);
		}
		throw new Error('Unsupported NUMBERS file');
	}
	if(!safegetzipfile(zip, '[Content_Types].xml')) {
		if(safegetzipfile(zip, 'index.xml.gz')) throw new Error('Unsupported NUMBERS 08 file');
		if(safegetzipfile(zip, 'index.xml')) throw new Error('Unsupported NUMBERS 09 file');
		throw new Error('Unsupported ZIP file');
	}

	var entries = zipentries(zip);
	var dir = parse_ct((getzipstr(zip, '[Content_Types].xml')/*:?any*/));
	var xlsb = false;
	var sheets, binname;
	if(dir.workbooks.length === 0) {
		binname = "xl/workbook.xml";
		if(getzipdata(zip,binname, true)) dir.workbooks.push(binname);
	}
	if(dir.workbooks.length === 0) {
		binname = "xl/workbook.bin";
		if(!getzipdata(zip,binname,true)) throw new Error("Could not find workbook");
		dir.workbooks.push(binname);
		xlsb = true;
	}
	if(dir.workbooks[0].slice(-3) == "bin") xlsb = true;

	var themes = ({}/*:any*/);
	var styles = ({}/*:any*/);
	if(!opts.bookSheets && !opts.bookProps) {
		strs = [];
		if(dir.sst) try { strs=parse_sst(getzipdata(zip, strip_front_slash(dir.sst)), dir.sst, opts); } catch(e) { if(opts.WTF) throw e; }

		if(opts.cellStyles && dir.themes.length) themes = parse_theme(getzipstr(zip, dir.themes[0].replace(/^\//,''), true)||"",dir.themes[0], opts);

		if(dir.style) styles = parse_sty(getzipdata(zip, strip_front_slash(dir.style)), dir.style, themes, opts);
	}

	/*var externbooks = */dir.links.map(function(link) {
		try {
			var rels = parse_rels(getzipstr(zip, get_rels_path(strip_front_slash(link))), link);
			return parse_xlink(getzipdata(zip, strip_front_slash(link)), rels, link, opts);
		} catch(e) {}
	});

	var wb = parse_wb(getzipdata(zip, strip_front_slash(dir.workbooks[0])), dir.workbooks[0], opts);

	var props = {}, propdata = "";

	if(dir.coreprops.length) {
		propdata = getzipdata(zip, strip_front_slash(dir.coreprops[0]), true);
		if(propdata) props = parse_core_props(propdata);
		if(dir.extprops.length !== 0) {
			propdata = getzipdata(zip, strip_front_slash(dir.extprops[0]), true);
			if(propdata) parse_ext_props(propdata, props, opts);
		}
	}

	var custprops = {};
	if(!opts.bookSheets || opts.bookProps) {
		if (dir.custprops.length !== 0) {
			propdata = getzipstr(zip, strip_front_slash(dir.custprops[0]), true);
			if(propdata) custprops = parse_cust_props(propdata, opts);
		}
	}

	var out = ({}/*:any*/);
	if(opts.bookSheets || opts.bookProps) {
		if(wb.Sheets) sheets = wb.Sheets.map(function pluck(x){ return x.name; });
		else if(props.Worksheets && props.SheetNames.length > 0) sheets=props.SheetNames;
		if(opts.bookProps) { out.Props = props; out.Custprops = custprops; }
		if(opts.bookSheets && typeof sheets !== 'undefined') out.SheetNames = sheets;
		if(opts.bookSheets ? out.SheetNames : opts.bookProps) return out;
	}
	sheets = {};

	var deps = {};
	if(opts.bookDeps && dir.calcchain) deps=parse_cc(getzipdata(zip, strip_front_slash(dir.calcchain)),dir.calcchain,opts);

	var i=0;
	var sheetRels = ({}/*:any*/);
	var path, relsPath;

	{
		var wbsheets = wb.Sheets;
		props.Worksheets = wbsheets.length;
		props.SheetNames = [];
		for(var j = 0; j != wbsheets.length; ++j) {
			props.SheetNames[j] = wbsheets[j].name;
		}
	}

	var wbext = xlsb ? "bin" : "xml";
	var wbrelsi = dir.workbooks[0].lastIndexOf("/");
	var wbrelsfile = (dir.workbooks[0].slice(0, wbrelsi+1) + "_rels/" + dir.workbooks[0].slice(wbrelsi+1) + ".rels").replace(/^\//,"");
	if(!safegetzipfile(zip, wbrelsfile)) wbrelsfile = 'xl/_rels/workbook.' + wbext + '.rels';
	var wbrels = parse_rels(getzipstr(zip, wbrelsfile, true), wbrelsfile.replace(/_rels.*/, "s5s"));

	if((dir.metadata || []).length >= 1) {
		/* TODO: MDX and other types of metadata */
		opts.xlmeta = parse_xlmeta(getzipdata(zip, strip_front_slash(dir.metadata[0])),dir.metadata[0],opts);
	}

	if((dir.people || []).length >= 1) {
		opts.people = parse_people_xml(getzipdata(zip, strip_front_slash(dir.people[0])),opts);
	}

	if(wbrels) wbrels = safe_parse_wbrels(wbrels, wb.Sheets);

	/* Numbers iOS hack */
	var nmode = (getzipdata(zip,"xl/worksheets/sheet.xml",true))?1:0;
	wsloop: for(i = 0; i != props.Worksheets; ++i) {
		var stype = "sheet";
		if(wbrels && wbrels[i]) {
			path = 'xl/' + (wbrels[i][1]).replace(/[\/]?xl\//, "");
			if(!safegetzipfile(zip, path)) path = wbrels[i][1];
			if(!safegetzipfile(zip, path)) path = wbrelsfile.replace(/_rels\/.*$/,"") + wbrels[i][1];
			stype = wbrels[i][2];
		} else {
			path = 'xl/worksheets/sheet'+(i+1-nmode)+"." + wbext;
			path = path.replace(/sheet0\./,"sheet.");
		}
		relsPath = path.replace(/^(.*)(\/)([^\/]*)$/, "$1/_rels/$3.rels");
		if(opts && opts.sheets != null) switch(typeof opts.sheets) {
			case "number": if(i != opts.sheets) continue wsloop; break;
			case "string": if(props.SheetNames[i].toLowerCase() != opts.sheets.toLowerCase()) continue wsloop; break;
			default: if(Array.isArray && Array.isArray(opts.sheets)) {
				var snjseen = false;
				for(var snj = 0; snj != opts.sheets.length; ++snj) {
					if(typeof opts.sheets[snj] == "number" && opts.sheets[snj] == i) snjseen=1;
					if(typeof opts.sheets[snj] == "string" && opts.sheets[snj].toLowerCase() == props.SheetNames[i].toLowerCase()) snjseen = 1;
				}
				if(!snjseen) continue wsloop;
			}
		}
		safe_parse_sheet(zip, path, relsPath, props.SheetNames[i], i, sheetRels, sheets, stype, opts, wb, themes, styles);
	}

	out = ({
		Directory: dir,
		Workbook: wb,
		Props: props,
		Custprops: custprops,
		Deps: deps,
		Sheets: sheets,
		SheetNames: props.SheetNames,
		Strings: strs,
		Styles: styles,
		Themes: themes,
		SSF: dup(table_fmt)
	}/*:any*/);
	if(opts && opts.bookFiles) {
		if(zip.files) {
			out.keys = entries;
			out.files = zip.files;
		} else {
			out.keys = [];
			out.files = {};
			zip.FullPaths.forEach(function(p, idx) {
				p = p.replace(/^Root Entry[\/]/, "");
				out.keys.push(p);
				out.files[p] = zip.FileIndex[idx];
			});
		}
	}
	if(opts && opts.bookVBA) {
		if(dir.vba.length > 0) out.vbaraw = getzipdata(zip,strip_front_slash(dir.vba[0]),true);
		else if(dir.defaults && dir.defaults.bin === CT_VBA) out.vbaraw = getzipdata(zip, 'xl/vbaProject.bin',true);
	}
	return out;
}

/* [MS-OFFCRYPTO] 2.1.1 */
function parse_xlsxcfb(cfb, _opts/*:?ParseOpts*/)/*:Workbook*/ {
	var opts = _opts || {};
	var f = 'Workbook', data = CFB.find(cfb, f);
	try {
	f = '/!DataSpaces/Version';
	data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
	/*var version = */parse_DataSpaceVersionInfo(data.content);

	/* 2.3.4.1 */
	f = '/!DataSpaces/DataSpaceMap';
	data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
	var dsm = parse_DataSpaceMap(data.content);
	if(dsm.length !== 1 || dsm[0].comps.length !== 1 || dsm[0].comps[0].t !== 0 || dsm[0].name !== "StrongEncryptionDataSpace" || dsm[0].comps[0].v !== "EncryptedPackage")
		throw new Error("ECMA-376 Encrypted file bad " + f);

	/* 2.3.4.2 */
	f = '/!DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace';
	data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
	var seds = parse_DataSpaceDefinition(data.content);
	if(seds.length != 1 || seds[0] != "StrongEncryptionTransform")
		throw new Error("ECMA-376 Encrypted file bad " + f);

	/* 2.3.4.3 */
	f = '/!DataSpaces/TransformInfo/StrongEncryptionTransform/!Primary';
	data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
	/*var hdr = */parse_Primary(data.content);
	} catch(e) {}

	f = '/EncryptionInfo';
	data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
	var einfo = parse_EncryptionInfo(data.content);

	/* 2.3.4.4 */
	f = '/EncryptedPackage';
	data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);

/*global decrypt_agile */
/*:: declare var decrypt_agile:any; */
	if(einfo[0] == 0x04 && typeof decrypt_agile !== 'undefined') return decrypt_agile(einfo[1], data.content, opts.password || "", opts);
/*global decrypt_std76 */
/*:: declare var decrypt_std76:any; */
	if(einfo[0] == 0x02 && typeof decrypt_std76 !== 'undefined') return decrypt_std76(einfo[1], data.content, opts.password || "", opts);
	throw new Error("File is password-protected");
}

function write_zip(wb/*:Workbook*/, opts/*:WriteOpts*/)/*:ZIP*/ {
	if(opts.bookType == "ods") return write_ods(wb, opts);
	if(opts.bookType == "numbers") return write_numbers_iwa(wb, opts);
	if(opts.bookType == "xlsb") return write_zip_xlsxb(wb, opts);
	return write_zip_xlsx(wb, opts);
}

/* XLSX and XLSB writing are very similar.  Originally they were unified in one
   export function.  This is horrible for tree shaking in the common case (most
   applications need to export files in one format) so this function supports
   both formats while write_zip_xlsx only handles XLSX */
function write_zip_xlsxb(wb/*:Workbook*/, opts/*:WriteOpts*/)/*:ZIP*/ {
	_shapeid = 1024;
	if(wb && !wb.SSF) {
		wb.SSF = dup(table_fmt);
	}
	if(wb && wb.SSF) {
		make_ssf(); SSF_load_table(wb.SSF);
		// $FlowIgnore
		opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
		opts.ssf = wb.SSF;
	}
	opts.rels = {}; opts.wbrels = {};
	opts.Strings = /*::((*/[]/*:: :any):SST)*/; opts.Strings.Count = 0; opts.Strings.Unique = 0;
	if(browser_has_Map) opts.revStrings = new Map();
	else { opts.revStrings = {}; opts.revStrings.foo = []; delete opts.revStrings.foo; }
	var wbext = opts.bookType == "xlsb" ? "bin" : "xml";
	var vbafmt = VBAFMTS.indexOf(opts.bookType) > -1;
	var ct = new_ct();
	fix_write_opts(opts = opts || {});
	var zip = zip_new();
	var f = "", rId = 0;

	opts.cellXfs = [];
	get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});

	if(!wb.Props) wb.Props = {};

	f = "docProps/core.xml";
	zip_add_file(zip, f, write_core_props(wb.Props, opts));
	ct.coreprops.push(f);
	add_rels(opts.rels, 2, f, RELS.CORE_PROPS);

	/*::if(!wb.Props) throw "unreachable"; */
	f = "docProps/app.xml";
	if(wb.Props && wb.Props.SheetNames){/* empty */}
	else if(!wb.Workbook || !wb.Workbook.Sheets) wb.Props.SheetNames = wb.SheetNames;
	else {
		var _sn = [];
		for(var _i = 0; _i < wb.SheetNames.length; ++_i)
			if((wb.Workbook.Sheets[_i]||{}).Hidden != 2) _sn.push(wb.SheetNames[_i]);
		wb.Props.SheetNames = _sn;
	}
	wb.Props.Worksheets = wb.Props.SheetNames.length;
	zip_add_file(zip, f, write_ext_props(wb.Props, opts));
	ct.extprops.push(f);
	add_rels(opts.rels, 3, f, RELS.EXT_PROPS);

	if(wb.Custprops !== wb.Props && keys(wb.Custprops||{}).length > 0) {
		f = "docProps/custom.xml";
		zip_add_file(zip, f, write_cust_props(wb.Custprops, opts));
		ct.custprops.push(f);
		add_rels(opts.rels, 4, f, RELS.CUST_PROPS);
	}

	for(rId=1;rId <= wb.SheetNames.length; ++rId) {
		var wsrels = {'!id':{}};
		var ws = wb.Sheets[wb.SheetNames[rId-1]];
		var _type = (ws || {})["!type"] || "sheet";
		switch(_type) {
		case "chart":
			/* falls through */
		default:
			f = "xl/worksheets/sheet" + rId + "." + wbext;
			zip_add_file(zip, f, write_ws(rId-1, f, opts, wb, wsrels));
			ct.sheets.push(f);
			add_rels(opts.wbrels, -1, "worksheets/sheet" + rId + "." + wbext, RELS.WS[0]);
		}

		if(ws) {
			var comments = ws['!comments'];
			var need_vml = false;
			var cf = "";
			if(comments && comments.length > 0) {
				cf = "xl/comments" + rId + "." + wbext;
				zip_add_file(zip, cf, write_cmnt(comments, cf, opts));
				ct.comments.push(cf);
				add_rels(wsrels, -1, "../comments" + rId + "." + wbext, RELS.CMNT);
				need_vml = true;
			}
			if(ws['!legacy']) {
				if(need_vml) zip_add_file(zip, "xl/drawings/vmlDrawing" + (rId) + ".vml", write_comments_vml(rId, ws['!comments']));
			}
			delete ws['!comments'];
			delete ws['!legacy'];
		}

		if(wsrels['!id'].rId1) zip_add_file(zip, get_rels_path(f), write_rels(wsrels));
	}

	if(opts.Strings != null && opts.Strings.length > 0) {
		f = "xl/sharedStrings." + wbext;
		zip_add_file(zip, f, write_sst(opts.Strings, f, opts));
		ct.strs.push(f);
		add_rels(opts.wbrels, -1, "sharedStrings." + wbext, RELS.SST);
	}

	f = "xl/workbook." + wbext;
	zip_add_file(zip, f, write_wb(wb, f, opts));
	ct.workbooks.push(f);
	add_rels(opts.rels, 1, f, RELS.WB);

	/* TODO: something more intelligent with themes */

	f = "xl/theme/theme1.xml";
	zip_add_file(zip, f, write_theme(wb.Themes, opts));
	ct.themes.push(f);
	add_rels(opts.wbrels, -1, "theme/theme1.xml", RELS.THEME);

	/* TODO: something more intelligent with styles */

	f = "xl/styles." + wbext;
	zip_add_file(zip, f, write_sty(wb, f, opts));
	ct.styles.push(f);
	add_rels(opts.wbrels, -1, "styles." + wbext, RELS.STY);

	if(wb.vbaraw && vbafmt) {
		f = "xl/vbaProject.bin";
		zip_add_file(zip, f, wb.vbaraw);
		ct.vba.push(f);
		add_rels(opts.wbrels, -1, "vbaProject.bin", RELS.VBA);
	}

	f = "xl/metadata." + wbext;
	zip_add_file(zip, f, write_xlmeta(f));
	ct.metadata.push(f);
	add_rels(opts.wbrels, -1, "metadata." + wbext, RELS.XLMETA);

	zip_add_file(zip, "[Content_Types].xml", write_ct(ct, opts));
	zip_add_file(zip, '_rels/.rels', write_rels(opts.rels));
	zip_add_file(zip, 'xl/_rels/workbook.' + wbext + '.rels', write_rels(opts.wbrels));

	delete opts.revssf; delete opts.ssf;
	return zip;
}

function write_zip_xlsx(wb/*:Workbook*/, opts/*:WriteOpts*/)/*:ZIP*/ {
	_shapeid = 1024;
	if(wb && !wb.SSF) {
		wb.SSF = dup(table_fmt);
	}
	if(wb && wb.SSF) {
		make_ssf(); SSF_load_table(wb.SSF);
		// $FlowIgnore
		opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
		opts.ssf = wb.SSF;
	}
	opts.rels = {}; opts.wbrels = {};
	opts.Strings = /*::((*/[]/*:: :any):SST)*/; opts.Strings.Count = 0; opts.Strings.Unique = 0;
	if(browser_has_Map) opts.revStrings = new Map();
	else { opts.revStrings = {}; opts.revStrings.foo = []; delete opts.revStrings.foo; }
	var wbext = "xml";
	var vbafmt = VBAFMTS.indexOf(opts.bookType) > -1;
	var ct = new_ct();
	fix_write_opts(opts = opts || {});
	var zip = zip_new();
	var f = "", rId = 0;

	opts.cellXfs = [];
	get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});

	if(!wb.Props) wb.Props = {};

	f = "docProps/core.xml";
	zip_add_file(zip, f, write_core_props(wb.Props, opts));
	ct.coreprops.push(f);
	add_rels(opts.rels, 2, f, RELS.CORE_PROPS);

	/*::if(!wb.Props) throw "unreachable"; */
	f = "docProps/app.xml";
	if(wb.Props && wb.Props.SheetNames){/* empty */}
	else if(!wb.Workbook || !wb.Workbook.Sheets) wb.Props.SheetNames = wb.SheetNames;
	else {
		var _sn = [];
		for(var _i = 0; _i < wb.SheetNames.length; ++_i)
			if((wb.Workbook.Sheets[_i]||{}).Hidden != 2) _sn.push(wb.SheetNames[_i]);
		wb.Props.SheetNames = _sn;
	}
	wb.Props.Worksheets = wb.Props.SheetNames.length;
	zip_add_file(zip, f, write_ext_props(wb.Props, opts));
	ct.extprops.push(f);
	add_rels(opts.rels, 3, f, RELS.EXT_PROPS);

	if(wb.Custprops !== wb.Props && keys(wb.Custprops||{}).length > 0) {
		f = "docProps/custom.xml";
		zip_add_file(zip, f, write_cust_props(wb.Custprops, opts));
		ct.custprops.push(f);
		add_rels(opts.rels, 4, f, RELS.CUST_PROPS);
	}

	var people = ["SheetJ5"];
	opts.tcid = 0;

	for(rId=1;rId <= wb.SheetNames.length; ++rId) {
		var wsrels = {'!id':{}};
		var ws = wb.Sheets[wb.SheetNames[rId-1]];
		var _type = (ws || {})["!type"] || "sheet";
		switch(_type) {
		case "chart":
			/* falls through */
		default:
			f = "xl/worksheets/sheet" + rId + "." + wbext;
			zip_add_file(zip, f, write_ws_xml(rId-1, opts, wb, wsrels));
			ct.sheets.push(f);
			add_rels(opts.wbrels, -1, "worksheets/sheet" + rId + "." + wbext, RELS.WS[0]);
		}

		if(ws) {
			var comments = ws['!comments'];
			var need_vml = false;
			var cf = "";
			if(comments && comments.length > 0) {
				var needtc = false;
				comments.forEach(function(carr) {
					carr[1].forEach(function(c) { if(c.T == true) needtc = true; });
				});
				if(needtc) {
					cf = "xl/threadedComments/threadedComment" + rId + "." + wbext;
					zip_add_file(zip, cf, write_tcmnt_xml(comments, people, opts));
					ct.threadedcomments.push(cf);
					add_rels(wsrels, -1, "../threadedComments/threadedComment" + rId + "." + wbext, RELS.TCMNT);
				}

				cf = "xl/comments" + rId + "." + wbext;
				zip_add_file(zip, cf, write_comments_xml(comments, opts));
				ct.comments.push(cf);
				add_rels(wsrels, -1, "../comments" + rId + "." + wbext, RELS.CMNT);
				need_vml = true;
			}
			if(ws['!legacy']) {
				if(need_vml) zip_add_file(zip, "xl/drawings/vmlDrawing" + (rId) + ".vml", write_comments_vml(rId, ws['!comments']));
			}
			delete ws['!comments'];
			delete ws['!legacy'];
		}

		if(wsrels['!id'].rId1) zip_add_file(zip, get_rels_path(f), write_rels(wsrels));
	}

	if(opts.Strings != null && opts.Strings.length > 0) {
		f = "xl/sharedStrings." + wbext;
		zip_add_file(zip, f, write_sst_xml(opts.Strings, opts));
		ct.strs.push(f);
		add_rels(opts.wbrels, -1, "sharedStrings." + wbext, RELS.SST);
	}

	f = "xl/workbook." + wbext;
	zip_add_file(zip, f, write_wb_xml(wb, opts));
	ct.workbooks.push(f);
	add_rels(opts.rels, 1, f, RELS.WB);

	/* TODO: something more intelligent with themes */

	f = "xl/theme/theme1.xml";
	zip_add_file(zip, f, write_theme(wb.Themes, opts));
	ct.themes.push(f);
	add_rels(opts.wbrels, -1, "theme/theme1.xml", RELS.THEME);

	/* TODO: something more intelligent with styles */

	f = "xl/styles." + wbext;
	zip_add_file(zip, f, write_sty_xml(wb, opts));
	ct.styles.push(f);
	add_rels(opts.wbrels, -1, "styles." + wbext, RELS.STY);

	if(wb.vbaraw && vbafmt) {
		f = "xl/vbaProject.bin";
		zip_add_file(zip, f, wb.vbaraw);
		ct.vba.push(f);
		add_rels(opts.wbrels, -1, "vbaProject.bin", RELS.VBA);
	}

	f = "xl/metadata." + wbext;
	zip_add_file(zip, f, write_xlmeta_xml());
	ct.metadata.push(f);
	add_rels(opts.wbrels, -1, "metadata." + wbext, RELS.XLMETA);

	if(people.length > 1) {
		f = "xl/persons/person.xml";
		zip_add_file(zip, f, write_people_xml(people, opts));
		ct.people.push(f);
		add_rels(opts.wbrels, -1, "persons/person.xml", RELS.PEOPLE);
	}

	zip_add_file(zip, "[Content_Types].xml", write_ct(ct, opts));
	zip_add_file(zip, '_rels/.rels', write_rels(opts.rels));
	zip_add_file(zip, 'xl/_rels/workbook.' + wbext + '.rels', write_rels(opts.wbrels));

	delete opts.revssf; delete opts.ssf;
	return zip;
}

function firstbyte(f/*:RawData*/,o/*:?TypeOpts*/)/*:Array<number>*/ {
	var x = "";
	switch((o||{}).type || "base64") {
		case 'buffer': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
		case 'base64': x = Base64_decode(f.slice(0,12)); break;
		case 'binary': x = f; break;
		case 'array':  return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
		default: throw new Error("Unrecognized type " + (o && o.type || "undefined"));
	}
	return [x.charCodeAt(0), x.charCodeAt(1), x.charCodeAt(2), x.charCodeAt(3), x.charCodeAt(4), x.charCodeAt(5), x.charCodeAt(6), x.charCodeAt(7)];
}

function read_cfb(cfb/*:CFBContainer*/, opts/*:?ParseOpts*/)/*:Workbook*/ {
	if(CFB.find(cfb, "EncryptedPackage")) return parse_xlsxcfb(cfb, opts);
	return parse_xlscfb(cfb, opts);
}

function read_zip(data/*:RawData*/, opts/*:?ParseOpts*/)/*:Workbook*/ {
	var zip, d = data;
	var o = opts||{};
	if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
	zip = zip_read(d, o);
	return parse_zip(zip, o);
}

function read_plaintext(data/*:string*/, o/*:ParseOpts*/)/*:Workbook*/ {
	var i = 0;
	main: while(i < data.length) switch(data.charCodeAt(i)) {
		case 0x0A: case 0x0D: case 0x20: ++i; break;
		case 0x3C: return parse_xlml(data.slice(i),o);
		default: break main;
	}
	return PRN.to_workbook(data, o);
}

function read_plaintext_raw(data/*:RawData*/, o/*:ParseOpts*/)/*:Workbook*/ {
	var str = "", bytes = firstbyte(data, o);
	switch(o.type) {
		case 'base64': str = Base64_decode(data); break;
		case 'binary': str = data; break;
		case 'buffer': str = data.toString('binary'); break;
		case 'array': str = cc2str(data); break;
		default: throw new Error("Unrecognized type " + o.type);
	}
	if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str);
	o.type = "binary";
	return read_plaintext(str, o);
}

function read_utf16(data/*:RawData*/, o/*:ParseOpts*/)/*:Workbook*/ {
	var d = data;
	if(o.type == 'base64') d = Base64_decode(d);
	d = $cptable.utils.decode(1200, d.slice(2), 'str');
	o.type = "binary";
	return read_plaintext(d, o);
}

function bstrify(data/*:string*/)/*:string*/ {
	return !data.match(/[^\x00-\x7F]/) ? data : utf8write(data);
}

function read_prn(data, d, o, str) {
	if(str) { o.type = "string"; return PRN.to_workbook(data, o); }
	return PRN.to_workbook(d, o);
}

function readSync(data/*:RawData*/, opts/*:?ParseOpts*/)/*:Workbook*/ {
	reset_cp();
	var o = opts||{};
	if(typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) return readSync(new Uint8Array(data), (o = dup(o), o.type = "array", o));
	if(typeof Uint8Array !== 'undefined' && data instanceof Uint8Array && !o.type) o.type = typeof Deno !== "undefined" ? "buffer" : "array";
	var d = data, n = [0,0,0,0], str = false;
	if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
	_ssfopts = {};
	if(o.dateNF) _ssfopts.dateNF = o.dateNF;
	if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
	if(o.type == "file") { o.type = has_buf ? "buffer" : "binary"; d = read_binary(data); if(typeof Uint8Array !== 'undefined' && !has_buf) o.type = "array"; }
	if(o.type == "string") { str = true; o.type = "binary"; o.codepage = 65001; d = bstrify(data); }
	if(o.type == 'array' && typeof Uint8Array !== 'undefined' && data instanceof Uint8Array && typeof ArrayBuffer !== 'undefined') {
		// $FlowIgnore
		var ab=new ArrayBuffer(3), vu=new Uint8Array(ab); vu.foo="bar";
		// $FlowIgnore
		if(!vu.foo) {o=dup(o); o.type='array'; return readSync(ab2a(d), o);}
	}
	switch((n = firstbyte(d, o))[0]) {
		case 0xD0: if(n[1] === 0xCF && n[2] === 0x11 && n[3] === 0xE0 && n[4] === 0xA1 && n[5] === 0xB1 && n[6] === 0x1A && n[7] === 0xE1) return read_cfb(CFB.read(d, o), o); break;
		case 0x09: if(n[1] <= 0x08) return parse_xlscfb(d, o); break;
		case 0x3C: return parse_xlml(d, o);
		case 0x49:
			if(n[1] === 0x49 && n[2] === 0x2a && n[3] === 0x00) throw new Error("TIFF Image File is not a spreadsheet");
			if(n[1] === 0x44) return read_wb_ID(d, o);
			break;
		case 0x54: if(n[1] === 0x41 && n[2] === 0x42 && n[3] === 0x4C) return DIF.to_workbook(d, o); break;
		case 0x50: return (n[1] === 0x4B && n[2] < 0x09 && n[3] < 0x09) ? read_zip(d, o) : read_prn(data, d, o, str);
		case 0xEF: return n[3] === 0x3C ? parse_xlml(d, o) : read_prn(data, d, o, str);
		case 0xFF:
			if(n[1] === 0xFE) { return read_utf16(d, o); }
			else if(n[1] === 0x00 && n[2] === 0x02 && n[3] === 0x00) return WK_.to_workbook(d, o);
			break;
		case 0x00:
			if(n[1] === 0x00) {
				if(n[2] >= 0x02 && n[3] === 0x00) return WK_.to_workbook(d, o);
				if(n[2] === 0x00 && (n[3] === 0x08 || n[3] === 0x09)) return WK_.to_workbook(d, o);
			}
			break;
		case 0x03: case 0x83: case 0x8B: case 0x8C: return DBF.to_workbook(d, o);
		case 0x7B: if(n[1] === 0x5C && n[2] === 0x72 && n[3] === 0x74) return RTF.to_workbook(d, o); break;
		case 0x0A: case 0x0D: case 0x20: return read_plaintext_raw(d, o);
		case 0x89: if(n[1] === 0x50 && n[2] === 0x4E && n[3] === 0x47) throw new Error("PNG Image File is not a spreadsheet"); break;
	}
	if(DBF_SUPPORTED_VERSIONS.indexOf(n[0]) > -1 && n[2] <= 12 && n[3] <= 31) return DBF.to_workbook(d, o);
	return read_prn(data, d, o, str);
}

function readFileSync(filename/*:string*/, opts/*:?ParseOpts*/)/*:Workbook*/ {
	var o = opts||{}; o.type = 'file';
	return readSync(filename, o);
}
function write_cfb_ctr(cfb/*:CFBContainer*/, o/*:WriteOpts*/)/*:any*/ {
	switch(o.type) {
		case "base64": case "binary": break;
		case "buffer": case "array": o.type = ""; break;
		case "file": return write_dl(o.file, CFB.write(cfb, {type:has_buf ? 'buffer' : ""}));
		case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
		default: throw new Error("Unrecognized type " + o.type);
	}
	return CFB.write(cfb, o);
}

/*:: declare var encrypt_agile:any; */
function write_zip_type(wb/*:Workbook*/, opts/*:?WriteOpts*/)/*:any*/ {
	var o = dup(opts||{});
	var z = write_zip(wb, o);
	return write_zip_denouement(z, o);
}
function write_zip_typeXLSX(wb/*:Workbook*/, opts/*:?WriteOpts*/)/*:any*/ {
	var o = dup(opts||{});
	var z = write_zip_xlsx(wb, o);
	return write_zip_denouement(z, o);
}
function write_zip_denouement(z/*:any*/, o/*:?WriteOpts*/)/*:any*/ {
	var oopts = {};
	var ftype = has_buf ? "nodebuffer" : (typeof Uint8Array !== "undefined" ? "array" : "string");
	if(o.compression) oopts.compression = 'DEFLATE';
	if(o.password) oopts.type = ftype;
	else switch(o.type) {
		case "base64": oopts.type = "base64"; break;
		case "binary": oopts.type = "string"; break;
		case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
		case "buffer":
		case "file": oopts.type = ftype; break;
		default: throw new Error("Unrecognized type " + o.type);
	}
	var out = z.FullPaths ? CFB.write(z, {fileType:"zip", type: /*::(*/{"nodebuffer": "buffer", "string": "binary"}/*:: :any)*/[oopts.type] || oopts.type, compression: !!o.compression}) : z.generate(oopts);
	if(typeof Deno !== "undefined") {
		if(typeof out == "string") {
			if(o.type == "binary" || o.type == "base64") return out;
			out = new Uint8Array(s2ab(out));
		}
	}
/*jshint -W083 */
	if(o.password && typeof encrypt_agile !== 'undefined') return write_cfb_ctr(encrypt_agile(out, o.password), o); // eslint-disable-line no-undef
/*jshint +W083 */
	if(o.type === "file") return write_dl(o.file, out);
	return o.type == "string" ? utf8read(/*::(*/out/*:: :any)*/) : out;
}

function write_cfb_type(wb/*:Workbook*/, opts/*:?WriteOpts*/)/*:any*/ {
	var o = opts||{};
	var cfb/*:CFBContainer*/ = write_xlscfb(wb, o);
	return write_cfb_ctr(cfb, o);
}

function write_string_type(out/*:string*/, opts/*:WriteOpts*/, bom/*:?string*/)/*:any*/ {
	if(!bom) bom = "";
	var o = bom + out;
	switch(opts.type) {
		case "base64": return Base64_encode(utf8write(o));
		case "binary": return utf8write(o);
		case "string": return out;
		case "file": return write_dl(opts.file, o, 'utf8');
		case "buffer": {
			if(has_buf) return Buffer_from(o, 'utf8');
			else if(typeof TextEncoder !== "undefined") return new TextEncoder().encode(o);
			else return write_string_type(o, {type:'binary'}).split("").map(function(c) { return c.charCodeAt(0); });
		}
	}
	throw new Error("Unrecognized type " + opts.type);
}

function write_stxt_type(out/*:string*/, opts/*:WriteOpts*/)/*:any*/ {
	switch(opts.type) {
		case "base64": return Base64_encode(out);
		case "binary": return out;
		case "string": return out; /* override in sheet_to_txt */
		case "file": return write_dl(opts.file, out, 'binary');
		case "buffer": {
			if(has_buf) return Buffer_from(out, 'binary');
			else return out.split("").map(function(c) { return c.charCodeAt(0); });
		}
	}
	throw new Error("Unrecognized type " + opts.type);
}

/* TODO: test consistency */
function write_binary_type(out, opts/*:WriteOpts*/)/*:any*/ {
	switch(opts.type) {
		case "string":
		case "base64":
		case "binary":
			var bstr = "";
			// $FlowIgnore
			for(var i = 0; i < out.length; ++i) bstr += String.fromCharCode(out[i]);
			return opts.type == 'base64' ? Base64_encode(bstr) : opts.type == 'string' ? utf8read(bstr) : bstr;
		case "file": return write_dl(opts.file, out);
		case "buffer": return out;
		default: throw new Error("Unrecognized type " + opts.type);
	}
}

function writeSyncXLSX(wb/*:Workbook*/, opts/*:?WriteOpts*/) {
	reset_cp();
	check_wb(wb);
	var o = dup(opts||{});
	if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
	if(o.type == "array") { o.type = "binary"; var out/*:string*/ = (writeSyncXLSX(wb, o)/*:any*/); o.type = "array"; return s2ab(out); }
	return write_zip_typeXLSX(wb, o);
}

function writeSync(wb/*:Workbook*/, opts/*:?WriteOpts*/) {
	reset_cp();
	check_wb(wb);
	var o = dup(opts||{});
	if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
	if(o.type == "array") { o.type = "binary"; var out/*:string*/ = (writeSync(wb, o)/*:any*/); o.type = "array"; return s2ab(out); }
	var idx = 0;
	if(o.sheet) {
		if(typeof o.sheet == "number") idx = o.sheet;
		else idx = wb.SheetNames.indexOf(o.sheet);
		if(!wb.SheetNames[idx]) throw new Error("Sheet not found: " + o.sheet + " : " + (typeof o.sheet));
	}
	switch(o.bookType || 'xlsb') {
		case 'xml':
		case 'xlml': return write_string_type(write_xlml(wb, o), o);
		case 'slk':
		case 'sylk': return write_string_type(SYLK.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
		case 'htm':
		case 'html': return write_string_type(sheet_to_html(wb.Sheets[wb.SheetNames[idx]], o), o);
		case 'txt': return write_stxt_type(sheet_to_txt(wb.Sheets[wb.SheetNames[idx]], o), o);
		case 'csv': return write_string_type(sheet_to_csv(wb.Sheets[wb.SheetNames[idx]], o), o, "\ufeff");
		case 'dif': return write_string_type(DIF.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
		case 'dbf': return write_binary_type(DBF.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
		case 'prn': return write_string_type(PRN.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
		case 'rtf': return write_string_type(RTF.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
		case 'eth': return write_string_type(ETH.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
		case 'fods': return write_string_type(write_ods(wb, o), o);
		case 'wk1': return write_binary_type(WK_.sheet_to_wk1(wb.Sheets[wb.SheetNames[idx]], o), o);
		case 'wk3': return write_binary_type(WK_.book_to_wk3(wb, o), o);
		case 'biff2': if(!o.biff) o.biff = 2; /* falls through */
		case 'biff3': if(!o.biff) o.biff = 3; /* falls through */
		case 'biff4': if(!o.biff) o.biff = 4; return write_binary_type(write_biff_buf(wb, o), o);
		case 'biff5': if(!o.biff) o.biff = 5; /* falls through */
		case 'biff8':
		case 'xla':
		case 'xls': if(!o.biff) o.biff = 8; return write_cfb_type(wb, o);
		case 'xlsx':
		case 'xlsm':
		case 'xlam':
		case 'xlsb':
		case 'numbers':
		case 'ods': return write_zip_type(wb, o);
		default: throw new Error ("Unrecognized bookType |" + o.bookType + "|");
	}
}

function resolve_book_type(o/*:WriteFileOpts*/) {
	if(o.bookType) return;
	var _BT = {
		"xls": "biff8",
		"htm": "html",
		"slk": "sylk",
		"socialcalc": "eth",
		"Sh33tJS": "WTF"
	};
	var ext = o.file.slice(o.file.lastIndexOf(".")).toLowerCase();
	if(ext.match(/^\.[a-z]+$/)) o.bookType = ext.slice(1);
	o.bookType = _BT[o.bookType] || o.bookType;
}

function writeFileSync(wb/*:Workbook*/, filename/*:string*/, opts/*:?WriteFileOpts*/) {
	var o = opts||{}; o.type = 'file';
	o.file = filename;
	resolve_book_type(o);
	return writeSync(wb, o);
}

function writeFileSyncXLSX(wb/*:Workbook*/, filename/*:string*/, opts/*:?WriteFileOpts*/) {
	var o = opts||{}; o.type = 'file';
	o.file = filename;
	resolve_book_type(o);
	return writeSyncXLSX(wb, o);
}


function writeFileAsync(filename/*:string*/, wb/*:Workbook*/, opts/*:?WriteFileOpts*/, cb/*:?(e?:ErrnoError)=>void*/) {
	var o = opts||{}; o.type = 'file';
	o.file = filename;
	resolve_book_type(o);
	o.type = 'buffer';
	var _cb = cb; if(!(_cb instanceof Function)) _cb = (opts/*:any*/);
	return _fs.writeFile(filename, writeSync(wb, o), _cb);
}
/*::
type MJRObject = {
	row: any;
	isempty: boolean;
};
*/
function make_json_row(sheet/*:Worksheet*/, r/*:Range*/, R/*:number*/, cols/*:Array<string>*/, header/*:number*/, hdr/*:Array<any>*/, dense/*:boolean*/, o/*:Sheet2JSONOpts*/)/*:MJRObject*/ {
	var rr = encode_row(R);
	var defval = o.defval, raw = o.raw || !Object.prototype.hasOwnProperty.call(o, "raw");
	var isempty = true;
	var row/*:any*/ = (header === 1) ? [] : {};
	if(header !== 1) {
		if(Object.defineProperty) try { Object.defineProperty(row, '__rowNum__', {value:R, enumerable:false}); } catch(e) { row.__rowNum__ = R; }
		else row.__rowNum__ = R;
	}
	if(!dense || sheet[R]) for (var C = r.s.c; C <= r.e.c; ++C) {
		var val = dense ? sheet[R][C] : sheet[cols[C] + rr];
		if(val === undefined || val.t === undefined) {
			if(defval === undefined) continue;
			if(hdr[C] != null) { row[hdr[C]] = defval; }
			continue;
		}
		var v = val.v;
		switch(val.t){
			case 'z': if(v == null) break; continue;
			case 'e': v = (v == 0 ? null : void 0); break;
			case 's': case 'd': case 'b': case 'n': break;
			default: throw new Error('unrecognized type ' + val.t);
		}
		if(hdr[C] != null) {
			if(v == null) {
				if(val.t == "e" && v === null) row[hdr[C]] = null;
				else if(defval !== undefined) row[hdr[C]] = defval;
				else if(raw && v === null) row[hdr[C]] = null;
				else continue;
			} else {
				row[hdr[C]] = raw && (val.t !== "n" || (val.t === "n" && o.rawNumbers !== false)) ? v : format_cell(val,v,o);
			}
			if(v != null) isempty = false;
		}
	}
	return { row: row, isempty: isempty };
}


function sheet_to_json(sheet/*:Worksheet*/, opts/*:?Sheet2JSONOpts*/) {
	if(sheet == null || sheet["!ref"] == null) return [];
	var val = {t:'n',v:0}, header = 0, offset = 1, hdr/*:Array<any>*/ = [], v=0, vv="";
	var r = {s:{r:0,c:0},e:{r:0,c:0}};
	var o = opts || {};
	var range = o.range != null ? o.range : sheet["!ref"];
	if(o.header === 1) header = 1;
	else if(o.header === "A") header = 2;
	else if(Array.isArray(o.header)) header = 3;
	else if(o.header == null) header = 0;
	switch(typeof range) {
		case 'string': r = safe_decode_range(range); break;
		case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
		default: r = range;
	}
	if(header > 0) offset = 0;
	var rr = encode_row(r.s.r);
	var cols/*:Array<string>*/ = [];
	var out/*:Array<any>*/ = [];
	var outi = 0, counter = 0;
	var dense = Array.isArray(sheet);
	var R = r.s.r, C = 0;
	var header_cnt = {};
	if(dense && !sheet[R]) sheet[R] = [];
	var colinfo/*:Array<ColInfo>*/ = o.skipHidden && sheet["!cols"] || [];
	var rowinfo/*:Array<ColInfo>*/ = o.skipHidden && sheet["!rows"] || [];
	for(C = r.s.c; C <= r.e.c; ++C) {
		if(((colinfo[C]||{}).hidden)) continue;
		cols[C] = encode_col(C);
		val = dense ? sheet[R][C] : sheet[cols[C] + rr];
		switch(header) {
			case 1: hdr[C] = C - r.s.c; break;
			case 2: hdr[C] = cols[C]; break;
			case 3: hdr[C] = o.header[C - r.s.c]; break;
			default:
				if(val == null) val = {w: "__EMPTY", t: "s"};
				vv = v = format_cell(val, null, o);
				counter = header_cnt[v] || 0;
				if(!counter) header_cnt[v] = 1;
				else {
					do { vv = v + "_" + (counter++); } while(header_cnt[vv]); header_cnt[v] = counter;
					header_cnt[vv] = 1;
				}
				hdr[C] = vv;
		}
	}
	for (R = r.s.r + offset; R <= r.e.r; ++R) {
		if ((rowinfo[R]||{}).hidden) continue;
		var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
		if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) out[outi++] = row.row;
	}
	out.length = outi;
	return out;
}

var qreg = /"/g;
function make_csv_row(sheet/*:Worksheet*/, r/*:Range*/, R/*:number*/, cols/*:Array<string>*/, fs/*:number*/, rs/*:number*/, FS/*:string*/, o/*:Sheet2CSVOpts*/)/*:?string*/ {
	var isempty = true;
	var row/*:Array<string>*/ = [], txt = "", rr = encode_row(R);
	for(var C = r.s.c; C <= r.e.c; ++C) {
		if (!cols[C]) continue;
		var val = o.dense ? (sheet[R]||[])[C]: sheet[cols[C] + rr];
		if(val == null) txt = "";
		else if(val.v != null) {
			isempty = false;
			txt = ''+(o.rawNumbers && val.t == "n" ? val.v : format_cell(val, null, o));
			for(var i = 0, cc = 0; i !== txt.length; ++i) if((cc = txt.charCodeAt(i)) === fs || cc === rs || cc === 34 || o.forceQuotes) {txt = "\"" + txt.replace(qreg, '""') + "\""; break; }
			if(txt == "ID") txt = '"ID"';
		} else if(val.f != null && !val.F) {
			isempty = false;
			txt = '=' + val.f; if(txt.indexOf(",") >= 0) txt = '"' + txt.replace(qreg, '""') + '"';
		} else txt = "";
		/* NOTE: Excel CSV does not support array formulae */
		row.push(txt);
	}
	if(o.blankrows === false && isempty) return null;
	return row.join(FS);
}

function sheet_to_csv(sheet/*:Worksheet*/, opts/*:?Sheet2CSVOpts*/)/*:string*/ {
	var out/*:Array<string>*/ = [];
	var o = opts == null ? {} : opts;
	if(sheet == null || sheet["!ref"] == null) return "";
	var r = safe_decode_range(sheet["!ref"]);
	var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
	var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
	var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
	var row = "", cols/*:Array<string>*/ = [];
	o.dense = Array.isArray(sheet);
	var colinfo/*:Array<ColInfo>*/ = o.skipHidden && sheet["!cols"] || [];
	var rowinfo/*:Array<ColInfo>*/ = o.skipHidden && sheet["!rows"] || [];
	for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
	var w = 0;
	for(var R = r.s.r; R <= r.e.r; ++R) {
		if ((rowinfo[R]||{}).hidden) continue;
		row = make_csv_row(sheet, r, R, cols, fs, rs, FS, o);
		if(row == null) { continue; }
		if(o.strip) row = row.replace(endregex,"");
		if(row || (o.blankrows !== false)) out.push((w++ ? RS : "") + row);
	}
	delete o.dense;
	return out.join("");
}

function sheet_to_txt(sheet/*:Worksheet*/, opts/*:?Sheet2CSVOpts*/) {
	if(!opts) opts = {}; opts.FS = "\t"; opts.RS = "\n";
	var s = sheet_to_csv(sheet, opts);
	if(typeof $cptable == 'undefined' || opts.type == 'string') return s;
	var o = $cptable.utils.encode(1200, s, 'str');
	return String.fromCharCode(255) + String.fromCharCode(254) + o;
}

function sheet_to_formulae(sheet/*:Worksheet*/)/*:Array<string>*/ {
	var y = "", x, val="";
	if(sheet == null || sheet["!ref"] == null) return [];
	var r = safe_decode_range(sheet['!ref']), rr = "", cols/*:Array<string>*/ = [], C;
	var cmds/*:Array<string>*/ = [];
	var dense = Array.isArray(sheet);
	for(C = r.s.c; C <= r.e.c; ++C) cols[C] = encode_col(C);
	for(var R = r.s.r; R <= r.e.r; ++R) {
		rr = encode_row(R);
		for(C = r.s.c; C <= r.e.c; ++C) {
			y = cols[C] + rr;
			x = dense ? (sheet[R]||[])[C] : sheet[y];
			val = "";
			if(x === undefined) continue;
			else if(x.F != null) {
				y = x.F;
				if(!x.f) continue;
				val = x.f;
				if(y.indexOf(":") == -1) y = y + ":" + y;
			}
			if(x.f != null) val = x.f;
			else if(x.t == 'z') continue;
			else if(x.t == 'n' && x.v != null) val = "" + x.v;
			else if(x.t == 'b') val = x.v ? "TRUE" : "FALSE";
			else if(x.w !== undefined) val = "'" + x.w;
			else if(x.v === undefined) continue;
			else if(x.t == 's') val = "'" + x.v;
			else val = ""+x.v;
			cmds[cmds.length] = y + "=" + val;
		}
	}
	return cmds;
}

function sheet_add_json(_ws/*:?Worksheet*/, js/*:Array<any>*/, opts)/*:Worksheet*/ {
	var o = opts || {};
	var offset = +!o.skipHeader;
	var ws/*:Worksheet*/ = _ws || ({}/*:any*/);
	var _R = 0, _C = 0;
	if(ws && o.origin != null) {
		if(typeof o.origin == 'number') _R = o.origin;
		else {
			var _origin/*:CellAddress*/ = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
			_R = _origin.r; _C = _origin.c;
		}
	}
	var cell/*:Cell*/;
	var range/*:Range*/ = ({s: {c:0, r:0}, e: {c:_C, r:_R + js.length - 1 + offset}}/*:any*/);
	if(ws['!ref']) {
		var _range = safe_decode_range(ws['!ref']);
		range.e.c = Math.max(range.e.c, _range.e.c);
		range.e.r = Math.max(range.e.r, _range.e.r);
		if(_R == -1) { _R = _range.e.r + 1; range.e.r = _R + js.length - 1 + offset; }
	} else {
		if(_R == -1) { _R = 0; range.e.r = js.length - 1 + offset; }
	}
	var hdr/*:Array<string>*/ = o.header || [], C = 0;

	js.forEach(function (JS, R/*:number*/) {
		keys(JS).forEach(function(k) {
			if((C=hdr.indexOf(k)) == -1) hdr[C=hdr.length] = k;
			var v = JS[k];
			var t = 'z';
			var z = "";
			var ref = encode_cell({c:_C + C,r:_R + R + offset});
			cell = ws_get_cell_stub(ws, ref);
			if(v && typeof v === 'object' && !(v instanceof Date)){
				ws[ref] = v;
			} else {
				if(typeof v == 'number') t = 'n';
				else if(typeof v == 'boolean') t = 'b';
				else if(typeof v == 'string') t = 's';
				else if(v instanceof Date) {
					t = 'd';
					if(!o.cellDates) { t = 'n'; v = datenum(v); }
					z = (o.dateNF || table_fmt[14]);
				}
				else if(v === null && o.nullError) { t = 'e'; v = 0; }
				if(!cell) ws[ref] = cell = ({t:t, v:v}/*:any*/);
				else {
					cell.t = t; cell.v = v;
					delete cell.w; delete cell.R;
					if(z) cell.z = z;
				}
				if(z) cell.z = z;
			}
		});
	});
	range.e.c = Math.max(range.e.c, _C + hdr.length - 1);
	var __R = encode_row(_R);
	if(offset) for(C = 0; C < hdr.length; ++C) ws[encode_col(C + _C) + __R] = {t:'s', v:hdr[C]};
	ws['!ref'] = encode_range(range);
	return ws;
}
function json_to_sheet(js/*:Array<any>*/, opts)/*:Worksheet*/ { return sheet_add_json(null, js, opts); }

/* get cell, creating a stub if necessary */
function ws_get_cell_stub(ws/*:Worksheet*/, R, C/*:?number*/)/*:Cell*/ {
	/* A1 cell address */
	if(typeof R == "string") {
		/* dense */
		if(Array.isArray(ws)) {
			var RC = decode_cell(R);
			if(!ws[RC.r]) ws[RC.r] = [];
			return ws[RC.r][RC.c] || (ws[RC.r][RC.c] = {t:'z'});
		}
		return ws[R] || (ws[R] = {t:'z'});
	}
	/* cell address object */
	if(typeof R != "number") return ws_get_cell_stub(ws, encode_cell(R));
	/* R and C are 0-based indices */
	return ws_get_cell_stub(ws, encode_cell({r:R,c:C||0}));
}

/* find sheet index for given name / validate index */
function wb_sheet_idx(wb/*:Workbook*/, sh/*:number|string*/) {
	if(typeof sh == "number") {
		if(sh >= 0 && wb.SheetNames.length > sh) return sh;
		throw new Error("Cannot find sheet # " + sh);
	} else if(typeof sh == "string") {
		var idx = wb.SheetNames.indexOf(sh);
		if(idx > -1) return idx;
		throw new Error("Cannot find sheet name |" + sh + "|");
	} else throw new Error("Cannot find sheet |" + sh + "|");
}

/* simple blank workbook object */
function book_new()/*:Workbook*/ {
	return { SheetNames: [], Sheets: {} };
}

/* add a worksheet to the end of a given workbook */
function book_append_sheet(wb/*:Workbook*/, ws/*:Worksheet*/, name/*:?string*/, roll/*:?boolean*/)/*:string*/ {
	var i = 1;
	if(!name) for(; i <= 0xFFFF; ++i, name = undefined) if(wb.SheetNames.indexOf(name = "Sheet" + i) == -1) break;
	if(!name || wb.SheetNames.length >= 0xFFFF) throw new Error("Too many worksheets");
	if(roll && wb.SheetNames.indexOf(name) >= 0) {
		var m = name.match(/(^.*?)(\d+)$/);
		i = m && +m[2] || 0;
		var root = m && m[1] || name;
		for(++i; i <= 0xFFFF; ++i) if(wb.SheetNames.indexOf(name = root + i) == -1) break;
	}
	check_ws_name(name);
	if(wb.SheetNames.indexOf(name) >= 0) throw new Error("Worksheet with name |" + name + "| already exists!");

	wb.SheetNames.push(name);
	wb.Sheets[name] = ws;
	return name;
}

/* set sheet visibility (visible/hidden/very hidden) */
function book_set_sheet_visibility(wb/*:Workbook*/, sh/*:number|string*/, vis/*:number*/) {
	if(!wb.Workbook) wb.Workbook = {};
	if(!wb.Workbook.Sheets) wb.Workbook.Sheets = [];

	var idx = wb_sheet_idx(wb, sh);
	// $FlowIgnore
	if(!wb.Workbook.Sheets[idx]) wb.Workbook.Sheets[idx] = {};

	switch(vis) {
		case 0: case 1: case 2: break;
		default: throw new Error("Bad sheet visibility setting " + vis);
	}
	// $FlowIgnore
	wb.Workbook.Sheets[idx].Hidden = vis;
}

/* set number format */
function cell_set_number_format(cell/*:Cell*/, fmt/*:string|number*/) {
	cell.z = fmt;
	return cell;
}

/* set cell hyperlink */
function cell_set_hyperlink(cell/*:Cell*/, target/*:string*/, tooltip/*:?string*/) {
	if(!target) {
		delete cell.l;
	} else {
		cell.l = ({ Target: target }/*:Hyperlink*/);
		if(tooltip) cell.l.Tooltip = tooltip;
	}
	return cell;
}
function cell_set_internal_link(cell/*:Cell*/, range/*:string*/, tooltip/*:?string*/) { return cell_set_hyperlink(cell, "#" + range, tooltip); }

/* add to cell comments */
function cell_add_comment(cell/*:Cell*/, text/*:string*/, author/*:?string*/) {
	if(!cell.c) cell.c = [];
	cell.c.push({t:text, a:author||"SheetJS"});
}

/* set array formula and flush related cells */
function sheet_set_array_formula(ws/*:Worksheet*/, range, formula/*:string*/, dynamic/*:boolean*/) {
	var rng = typeof range != "string" ? range : safe_decode_range(range);
	var rngstr = typeof range == "string" ? range : encode_range(range);
	for(var R = rng.s.r; R <= rng.e.r; ++R) for(var C = rng.s.c; C <= rng.e.c; ++C) {
		var cell = ws_get_cell_stub(ws, R, C);
		cell.t = 'n';
		cell.F = rngstr;
		delete cell.v;
		if(R == rng.s.r && C == rng.s.c) {
			cell.f = formula;
			if(dynamic) cell.D = true;
		}
	}
	return ws;
}

var utils/*:any*/ = {
	encode_col: encode_col,
	encode_row: encode_row,
	encode_cell: encode_cell,
	encode_range: encode_range,
	decode_col: decode_col,
	decode_row: decode_row,
	split_cell: split_cell,
	decode_cell: decode_cell,
	decode_range: decode_range,
	format_cell: format_cell,
	sheet_add_aoa: sheet_add_aoa,
	sheet_add_json: sheet_add_json,
	sheet_add_dom: sheet_add_dom,
	aoa_to_sheet: aoa_to_sheet,
	json_to_sheet: json_to_sheet,
	table_to_sheet: parse_dom_table,
	table_to_book: table_to_book,
	sheet_to_csv: sheet_to_csv,
	sheet_to_txt: sheet_to_txt,
	sheet_to_json: sheet_to_json,
	sheet_to_html: sheet_to_html,
	sheet_to_formulae: sheet_to_formulae,
	sheet_to_row_object_array: sheet_to_json,
	sheet_get_cell: ws_get_cell_stub,
	book_new: book_new,
	book_append_sheet: book_append_sheet,
	book_set_sheet_visibility: book_set_sheet_visibility,
	cell_set_number_format: cell_set_number_format,
	cell_set_hyperlink: cell_set_hyperlink,
	cell_set_internal_link: cell_set_internal_link,
	cell_add_comment: cell_add_comment,
	sheet_set_array_formula: sheet_set_array_formula,
	consts: {
		SHEET_VISIBLE: 0,
		SHEET_HIDDEN: 1,
		SHEET_VERY_HIDDEN: 2
	}
};

var _Readable;
function set_readable(R) { _Readable = R; }

function write_csv_stream(sheet/*:Worksheet*/, opts/*:?Sheet2CSVOpts*/) {
	var stream = _Readable();
	var o = opts == null ? {} : opts;
	if(sheet == null || sheet["!ref"] == null) { stream.push(null); return stream; }
	var r = safe_decode_range(sheet["!ref"]);
	var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
	var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
	var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
	var row/*:?string*/ = "", cols/*:Array<string>*/ = [];
	o.dense = Array.isArray(sheet);
	var colinfo/*:Array<ColInfo>*/ = o.skipHidden && sheet["!cols"] || [];
	var rowinfo/*:Array<RowInfo>*/ = o.skipHidden && sheet["!rows"] || [];
	for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
	var R = r.s.r;
	var BOM = false, w = 0;
	stream._read = function() {
		if(!BOM) { BOM = true; return stream.push("\uFEFF"); }
		while(R <= r.e.r) {
			++R;
			if ((rowinfo[R-1]||{}).hidden) continue;
			row = make_csv_row(sheet, r, R-1, cols, fs, rs, FS, o);
			if(row != null) {
				if(o.strip) row = row.replace(endregex,"");
				if(row || (o.blankrows !== false)) return stream.push((w++ ? RS : "") + row);
			}
		}
		return stream.push(null);
	};
	return stream;
}

function write_html_stream(ws/*:Worksheet*/, opts/*:?Sheet2HTMLOpts*/) {
	var stream = _Readable();

	var o = opts || {};
	var header = o.header != null ? o.header : HTML_BEGIN;
	var footer = o.footer != null ? o.footer : HTML_END;
	stream.push(header);
	var r = decode_range(ws['!ref']);
	o.dense = Array.isArray(ws);
	stream.push(make_html_preamble(ws, r, o));
	var R = r.s.r;
	var end = false;
	stream._read = function() {
		if(R > r.e.r) {
			if(!end) { end = true; stream.push("</table>" + footer); }
			return stream.push(null);
		}
		while(R <= r.e.r) {
			stream.push(make_html_row(ws, r, R, o));
			++R;
			break;
		}
	};
	return stream;
}

function write_json_stream(sheet/*:Worksheet*/, opts/*:?Sheet2CSVOpts*/) {
	var stream = _Readable({objectMode:true});

	if(sheet == null || sheet["!ref"] == null) { stream.push(null); return stream; }
	var val = {t:'n',v:0}, header = 0, offset = 1, hdr/*:Array<any>*/ = [], v=0, vv="";
	var r = {s:{r:0,c:0},e:{r:0,c:0}};
	var o = opts || {};
	var range = o.range != null ? o.range : sheet["!ref"];
	if(o.header === 1) header = 1;
	else if(o.header === "A") header = 2;
	else if(Array.isArray(o.header)) header = 3;
	switch(typeof range) {
		case 'string': r = safe_decode_range(range); break;
		case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
		default: r = range;
	}
	if(header > 0) offset = 0;
	var rr = encode_row(r.s.r);
	var cols/*:Array<string>*/ = [];
	var counter = 0;
	var dense = Array.isArray(sheet);
	var R = r.s.r, C = 0;
	var header_cnt = {};
	if(dense && !sheet[R]) sheet[R] = [];
	var colinfo/*:Array<ColInfo>*/ = o.skipHidden && sheet["!cols"] || [];
	var rowinfo/*:Array<RowInfo>*/ = o.skipHidden && sheet["!rows"] || [];
	for(C = r.s.c; C <= r.e.c; ++C) {
		if(((colinfo[C]||{}).hidden)) continue;
		cols[C] = encode_col(C);
		val = dense ? sheet[R][C] : sheet[cols[C] + rr];
		switch(header) {
			case 1: hdr[C] = C - r.s.c; break;
			case 2: hdr[C] = cols[C]; break;
			case 3: hdr[C] = o.header[C - r.s.c]; break;
			default:
				if(val == null) val = {w: "__EMPTY", t: "s"};
				vv = v = format_cell(val, null, o);
				counter = header_cnt[v] || 0;
				if(!counter) header_cnt[v] = 1;
				else {
					do { vv = v + "_" + (counter++); } while(header_cnt[vv]); header_cnt[v] = counter;
					header_cnt[vv] = 1;
				}
				hdr[C] = vv;
		}
	}
	R = r.s.r + offset;
	stream._read = function() {
		while(R <= r.e.r) {
			if ((rowinfo[R-1]||{}).hidden) continue;
			var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
			++R;
			if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) {
				stream.push(row.row);
				return;
			}
		}
		return stream.push(null);
	};
	return stream;
}

var __stream = {
	to_json: write_json_stream,
	to_html: write_html_stream,
	to_csv: write_csv_stream,
  set_readable: set_readable
};
const version$1 = XLSX.version;

const INVALID_SHEET_NAME_REGEX = /[:\\/?*\[\]]/g;
const INVALID_FILENAME_CHARS_REGEX = /[<>:"/\\|?*\x00-\x1F]/g;

const normalizeExcelValue = (value) => {
  if (value === null || value === undefined) {
    return '';
  }
  if (value instanceof Date) {
    return Number.isNaN(value.getTime()) ? '' : value.toISOString();
  }
  if (Array.isArray(value)) {
    return JSON.stringify(value);
  }
  if (typeof value === 'object') {
    return JSON.stringify(value);
  }
  return value;
};

const normalizeSourceRows = (rows = []) => {
  if (!Array.isArray(rows)) {
    return [];
  }

  return rows.map((row) => {
    if (row && typeof row === 'object' && !Array.isArray(row)) {
      return row;
    }
    if (Array.isArray(row)) {
      return row.reduce((accumulator, value, index) => {
        accumulator[String(index)] = value;
        return accumulator;
      }, {});
    }
    return { value: row };
  });
};

const collectExcelColumns = (rows = []) => {
  const columns = [];
  const seen = new Set();

  normalizeSourceRows(rows).forEach((row) => {
    Object.keys(row).forEach((key) => {
      if (!seen.has(key)) {
        seen.add(key);
        columns.push(key);
      }
    });
  });

  return columns;
};

const normalizeRowsForExcel = (rows = []) => {
  const normalizedSourceRows = normalizeSourceRows(rows);
  const columns = collectExcelColumns(normalizedSourceRows);

  const normalizedRows = normalizedSourceRows.map((row) => {
    const normalized = {};
    columns.forEach((column) => {
      normalized[column] = normalizeExcelValue(row[column]);
    });
    return normalized;
  });

  return {
    columns,
    rows: normalizedRows,
  };
};

const sanitizeSheetName = (sheetName = 'Data') => {
  const baseName = String(sheetName || 'Data').trim();
  const withoutInvalidChars = baseName.replace(INVALID_SHEET_NAME_REGEX, '_');
  const trimmed = withoutInvalidChars.slice(0, 31);
  return trimmed.length ? trimmed : 'Data';
};

const ensureExcelFilename = (filename = 'export.xlsx') => {
  const base = String(filename || 'export.xlsx')
    .trim()
    .replace(INVALID_FILENAME_CHARS_REGEX, '-');

  if (!base.length) {
    return 'export.xlsx';
  }

  return base.toLowerCase().endsWith('.xlsx') ? base : `${base}.xlsx`;
};

const createWorkbookFromRows = (rows = [], options = {}) => {
  const { columns, rows: normalizedRows } = normalizeRowsForExcel(rows);
  const sheetName = sanitizeSheetName(options.sheetName || 'Data');
  const worksheet = columns.length
    ? utils.json_to_sheet(normalizedRows, { header: columns, skipHeader: false })
    : utils.aoa_to_sheet([]);
  const workbook = utils.book_new();

  utils.book_append_sheet(workbook, worksheet, sheetName);

  return {
    workbook,
    sheetName,
    columns,
    rows: normalizedRows,
  };
};

const downloadWorkbook = (workbook, filename = 'export.xlsx') => {
  const safeFilename = ensureExcelFilename(filename);
  writeFileSync(workbook, safeFilename, { compression: true });
  return safeFilename;
};

const exportRowsToExcel = (rows = [], options = {}) => {
  const sourceRows = Array.isArray(rows) ? rows : [];
  const transformedRows = typeof options.transform === 'function'
    ? options.transform([...sourceRows])
    : sourceRows;
  const { workbook } = createWorkbookFromRows(
    Array.isArray(transformedRows) ? transformedRows : [],
    { sheetName: options.sheetName }
  );

  return downloadWorkbook(workbook, options.filename || 'export.xlsx');
};

const PaginatedListKey = Symbol('PaginatedList');
const SEARCH_DEBOUNCE_MS = 250;

/**
 * usePaginatedList composable
 * Returns a new pagination instance
 */
function usePaginatedList() {
  /** The list of items to paginate */
  const list = ref([]);

  /** The meta for the list */
  const metaCurrentPage = ref(1); // The current page
  const metaItemsPerPage = ref(100); // The number of items per page
  const metaTotalItems = ref(0); // The total number of items
  const metaSearch = ref(null); // The search query string
  const filter = ref(null); // The filter (eg. department_id or user_id)
  const lastUpdated = ref(null); // The last updated time
  const endpoint = ref(null); // The endpoint
  const meta = ref(null); // The meta object returned from the API
  const orderBy = ref(null); // The order by (eg. id)
  const orderDirection = ref(null); // The order direction (eg. asc)
  const hideSearchField = ref(false); // Hide the search field

  /** Set the loading state */
  const isLoading = ref(false);

  /** The latest search */
  const latestSearch = ref(null);
  const latestRequestId = ref(0);
  let activeRequestController = null;
  let searchDebounceTimeout = null;

  /** Additional query parameters */
  const additionalQueryParameters = ref({});

  /** Excel export state */
  const isExporting = ref(false);
  const exportTransform = ref(null);

  const resolveRequestLimit = (limit = null) => {
    const parsedLimit = Number.parseInt(limit, 10);
    if (Number.isFinite(parsedLimit) && parsedLimit > 0) {
      return parsedLimit;
    }

    const parsedCurrentLimit = Number.parseInt(metaItemsPerPage.value, 10);
    if (Number.isFinite(parsedCurrentLimit) && parsedCurrentLimit > 0) {
      return parsedCurrentLimit;
    }

    return 100;
  };

  const buildRequestParams = ({ page = metaCurrentPage.value, limit = metaItemsPerPage.value } = {}) => {
    const effectiveOrderBy = orderBy.value || 'id';
    const effectiveOrderDirection = orderDirection.value || 'asc';

    return {
      page: Number.parseInt(page, 10) || 1,
      limit: resolveRequestLimit(limit),
      search: metaSearch.value,
      filters: filter.value,
      order: `${effectiveOrderBy}:${effectiveOrderDirection}`,
      ...additionalQueryParameters.value,
    };
  };

  const buildRequestHeaders = (token) => {
    return {
      Authorization: `Bearer ${token}`,
      // Add X-Customer-Number header if subuser has selected a grant
      'X-Customer-Number': localStorage.getItem('selected_customer_number') || '',
    };
  };

  /**
   * Set the hide search field
   * @param hide true or false
   */
  const setHideSearchField = (hide) => {
    hideSearchField.value = hide;
  };

  /** Set the order */
  const setOrder = (column, direction) => {
    orderBy.value = column;
    orderDirection.value = direction;
  };

  /** Set the last updated time */
  const setLastUpdated = () => {
    lastUpdated.value = new Date();
  };

  /** The pagination functions */
  const setList = (newList) => {
    list.value = newList;
    setLastUpdated();
  };

  const setMeta = (currentPage, itemsPerPage, totalItems) => {
    metaCurrentPage.value = currentPage;
    metaItemsPerPage.value = itemsPerPage;
    metaTotalItems.value = totalItems;
    setLastUpdated();
  };

  const loadSwitch = (bool) => {
    isLoading.value = bool;
  };

  /**
   * isLatestSearch
   * This function is used to check if the search is the latest search,
   * It is used to prevent the results from being overwritten by an older search
   * @param search
   * @returns {boolean}
   */
  const isLatestSearch = (search) => {
    return search === latestSearch.value;
  };

  const clearPendingSearch = () => {
    if (searchDebounceTimeout) {
      clearTimeout(searchDebounceTimeout);
      searchDebounceTimeout = null;
    }
  };

  const abortActiveRequest = () => {
    activeRequestController?.abort();
    activeRequestController = null;
  };

  if (getCurrentScope()) {
    onScopeDispose(() => {
      clearPendingSearch();
      abortActiveRequest();
    });
  }

  const isCanceledRequest = (error) => {
    return error?.code === "ERR_CANCELED"
      || error?.name === "CanceledError"
      || error?.name === "AbortError"
      || (typeof axios.isCancel === "function" && axios.isCancel(error));
  };

  /** The paginated get request */
  const paginatedGetRequest = async () => {
    // Set the latest search
    latestSearch.value = metaSearch.value;
    const tmp_search = metaSearch.value;
    const requestId = latestRequestId.value + 1;
    latestRequestId.value = requestId;
    const token = localStorage.getItem('token');
    if (!token) {
      loadSwitch(false);
      return null;
    }

    abortActiveRequest();
    const requestController = typeof AbortController !== "undefined" ? new AbortController() : null;
    activeRequestController = requestController;

    try {
      const response = await axios.get(API_URL + endpoint.value, {
        params: buildRequestParams(),
        headers: buildRequestHeaders(token),
        ...(requestController ? { signal: requestController.signal } : {}),
      });

      // Check if the search is the latest search
      if (!isLatestSearch(tmp_search) || requestId !== latestRequestId.value) {
        return null;
      }

      setList(response?.data?.data || []);
      setMeta(
        response?.data?.meta?.pagination?.page || 1,
        response?.data?.meta?.pagination?.per_page || resolveRequestLimit(),
        response?.data?.meta?.pagination?.total || 0
      );
      meta.value = response?.data?.meta || null;
      setLastUpdated();
      return response;
    } catch (error) {
      if (!isCanceledRequest(error)) {
        parseError(error, 'paginatedGetRequest');
        console.log(error);
      }
      return null;
    } finally {
      if (activeRequestController === requestController) {
        activeRequestController = null;
      }
      if (requestId === latestRequestId.value) {
        loadSwitch(false);
      }
    }
  };

  /** The load list function */
  const loadList = () => {
    clearPendingSearch();
    loadSwitch(true);
    // clear the list
    return paginatedGetRequest();
  };

  /** Set the page */
  const setPage = (page) => {
    // Make sure the page is within the bounds, if not, return
    if (page < 1 || (metaTotalItems.value > 0 && page > Math.ceil(metaTotalItems.value / metaItemsPerPage.value))) {
      return;
    }
    metaCurrentPage.value = page;
  };

  const setEndpoint = (newEndpoint, autoLoad = true) => {
    endpoint.value = newEndpoint;
    // Reset the errors
    clearErrors();
    // Reset the page to 1
    setPage(1);
    // Clear the list
    list.value = [];
    // Reset the search
    metaSearch.value = null;
    // Reset the meta
    meta.value = null;
    // Reset the filter
    filter.value = null;
    // Reset the order
    setOrder('id', 'asc');
    // Reset the items per page
    metaItemsPerPage.value = 100;
    // Clear the additional query parameters
    additionalQueryParameters.value = {};
    // Load the list (If the endpoint is set)
    if (autoLoad) {
      loadList();
    }
  };

  const setMetaItemsPerPage = (newItemsPerPage, autoload = true) => {
    metaItemsPerPage.value = newItemsPerPage;
    // Reset the page to 1
    setPage(1);
    // Load the list
    if (autoload) {
      loadList();
    }
  };

  /**
   * Set the filter
   * @param newFilter eg. department_id
   * @param value eg. 3
   * @param autoLoad
   */
  const setFilter = (newFilter, value, autoLoad = true) => {
    if (value === '*') {
      // Remove the filter if the value is *
      filter.value = filter.value ? filter.value.split(',').filter(f => !f.startsWith(`${newFilter}:`)).join(',') : null;
    } else if (filter.value && filter.value.includes(`${newFilter}:`)) {
      // If the filter is already set, replace the value
      filter.value = filter.value.split(',').map(f => f.startsWith(`${newFilter}:`) ? `${newFilter}:${value}` : f).join(',');
    } else {
      // If the filter is not set, add it to the filter
      filter.value = filter.value ? `${filter.value},${newFilter}:${value}` : `${newFilter}:${value}`;
    }
    // Remove duplicates
    filter.value = filter.value ? [...new Set(filter.value.split(','))].join(',') : null;
    // If the filter is empty, set it to null
    if (filter.value === '') {
      filter.value = null;
    }
    // Reset the page to 1
    setPage(1);
    // Load the list (If the endpoint is set)
    if (autoLoad) {
      loadList();
    }
  };

  /**
   * Search function
   * @param searchValue
   * @param autoLoad BE AWARE, if autoLoad is set to false, you need to call loadList() manually, but the page will be set to 1 automatically!!!
   */
  const search = (searchValue, autoLoad = true) => {
    // If the search is *, remove the search
    metaSearch.value = searchValue === '*' ? null : searchValue;
    latestSearch.value = metaSearch.value;
    // Reset the page to 1
    setPage(1);
    // Load the list
    if (autoLoad) {
      clearPendingSearch();
      loadSwitch(true);
      searchDebounceTimeout = setTimeout(() => {
        searchDebounceTimeout = null;
        paginatedGetRequest();
      }, SEARCH_DEBOUNCE_MS);
    }
  };

  /** Is the list empty */
  const isEmpty = () => {
    return list.value.length === 0;
  };

  /** Has the list been loaded */
  const isLoaded = () => {
    return lastUpdated.value !== null;
  };

  /** Set additional query parameters */
  const setAdditionalQueryParameters = (params) => {
    additionalQueryParameters.value = params;
  };
  /** Add additional query parameters */
  const addAdditionalQueryParameters = (params) => {
    additionalQueryParameters.value = {...additionalQueryParameters.value, ...params};
  };
  /** Remove additional query parameters */
  const removeAdditionalQueryParameters = (keys) => {
    keys.forEach(key => {
      delete additionalQueryParameters.value[key];
    });
  };
  /** Clear additional query parameters */
  const clearAdditionalQueryParameters = () => {
    additionalQueryParameters.value = {};
  };

  /**
   * Get filter
   * @param filterName
   * @returns {string|null}
   */
  const getFilter = (filterName) => {
    if (filter.value && filter.value.includes(`${filterName}:`)) {
      return filter.value.split(',').find(f => f.startsWith(`${filterName}:`)).split(':')[1];
    }
    return null;
  };

  const applyExportTransform = (rows, transform = null) => {
    const sourceRows = Array.isArray(rows) ? rows : [];
    const effectiveTransform = typeof transform === 'function'
      ? transform
      : exportTransform.value;

    if (typeof effectiveTransform !== 'function') {
      return sourceRows;
    }

    const transformedRows = effectiveTransform([...sourceRows], {
      endpoint: endpoint.value,
      search: metaSearch.value,
      filter: filter.value,
      orderBy: orderBy.value,
      orderDirection: orderDirection.value,
      additionalQueryParameters: { ...additionalQueryParameters.value },
    });

    return Array.isArray(transformedRows) ? transformedRows : sourceRows;
  };

  const setExportTransform = (transform) => {
    exportTransform.value = typeof transform === 'function' ? transform : null;
  };

  const clearExportTransform = () => {
    exportTransform.value = null;
  };

  const fetchPageForExport = async (page = 1, limit = null) => {
    const token = localStorage.getItem('token');
    if (!token || !endpoint.value) {
      return {
        rows: [],
        page: 1,
        perPage: resolveRequestLimit(limit),
        total: 0,
        totalPages: 1,
      };
    }

    const response = await axios.get(API_URL + endpoint.value, {
      params: buildRequestParams({ page, limit }),
      headers: buildRequestHeaders(token),
    });

    const rows = Array.isArray(response?.data?.data) ? response.data.data : [];
    const pagination = response?.data?.meta?.pagination || {};
    const currentPage = Number.parseInt(pagination.page, 10) || Number.parseInt(page, 10) || 1;
    const perPage = Number.parseInt(pagination.per_page, 10) || resolveRequestLimit(limit);
    const total = Number.parseInt(pagination.total, 10);
    const totalItems = Number.isFinite(total) ? total : rows.length;
    const totalPages = Math.max(1, Math.ceil(totalItems / Math.max(1, perPage)));

    return {
      response,
      rows,
      page: currentPage,
      perPage,
      total: totalItems,
      totalPages,
    };
  };

  const fetchAllPagesForExport = async ({ itemsPerPage = null, transform = null } = {}) => {
    const effectiveLimit = resolveRequestLimit(itemsPerPage);
    const firstPage = await fetchPageForExport(1, effectiveLimit);
    const rows = [...firstPage.rows];

    for (let page = 2; page <= firstPage.totalPages; page += 1) {
      const pageResult = await fetchPageForExport(page, effectiveLimit);
      rows.push(...pageResult.rows);
    }

    return applyExportTransform(rows, transform);
  };

  const exportToExcel = async ({
    filename = null,
    sheetName = null,
    transform = null,
    rows = null,
    itemsPerPage = null,
  } = {}) => {
    if (isExporting.value) {
      return false;
    }

    isExporting.value = true;
    try {
      const endpointSlug = String(endpoint.value || 'table')
        .replace(/^\//, '')
        .replace(/[\\/]+/g, '-')
        .replace(/\s+/g, '-')
        .toLowerCase() || 'table';

      const exportRows = Array.isArray(rows)
        ? applyExportTransform(rows, transform)
        : await fetchAllPagesForExport({ itemsPerPage, transform });

      exportRowsToExcel(exportRows, {
        filename: filename || `${endpointSlug}-${new Date().toISOString().slice(0, 10)}.xlsx`,
        sheetName: sheetName || endpointSlug,
      });

      return true;
    } catch (error) {
      parseError(error, 'paginatedExportToExcel');
      console.log(error);
      return false;
    } finally {
      isExporting.value = false;
    }
  };

  return {
    list,
    metaCurrentPage,
    metaItemsPerPage,
    metaTotalItems,
    metaSearch,
    filter,
    lastUpdated,
    endpoint,
    meta,
    orderBy,
    orderDirection,
    hideSearchField,
    isLoading,
    isExporting,
    latestSearch,
    additionalQueryParameters,
    exportTransform,
    setHideSearchField,
    setOrder,
    setEndpoint,
    setLastUpdated,
    setList,
    setMeta,
    setMetaItemsPerPage,
    setFilter,
    search,
    isEmpty,
    isLoaded,
    setPage,
    loadSwitch,
    setAdditionalQueryParameters,
    addAdditionalQueryParameters,
    removeAdditionalQueryParameters,
    clearAdditionalQueryParameters,
    paginatedGetRequest,
    loadList,
    getFilter,
    fetchPageForExport,
    fetchAllPagesForExport,
    setExportTransform,
    clearExportTransform,
    exportToExcel
  };
}

/**
 * Helper to get the paginated list instance via injection or fallback to global
 */
function usePaginatedListInstance() {
  return inject(PaginatedListKey, globalInstance);
}

// Global instance for backward compatibility
const globalInstance = usePaginatedList();

const list = globalInstance.list;
const metaCurrentPage = globalInstance.metaCurrentPage;
const metaItemsPerPage = globalInstance.metaItemsPerPage;
const metaTotalItems = globalInstance.metaTotalItems;
const metaSearch = globalInstance.metaSearch;
const filter = globalInstance.filter;
const lastUpdated = globalInstance.lastUpdated;
const endpoint = globalInstance.endpoint;
const meta = globalInstance.meta;
const orderBy = globalInstance.orderBy;
const orderDirection = globalInstance.orderDirection;
const hideSearchField = globalInstance.hideSearchField;
const isLoading$1 = globalInstance.isLoading;
const isExporting = globalInstance.isExporting;
const latestSearch = globalInstance.latestSearch;
const additionalQueryParameters = globalInstance.additionalQueryParameters;
const exportTransform = globalInstance.exportTransform;

const setHideSearchField = globalInstance.setHideSearchField;
const setOrder = globalInstance.setOrder;
const setEndpoint = globalInstance.setEndpoint;
const setLastUpdated = globalInstance.setLastUpdated;
const setList = globalInstance.setList;
const setMeta = globalInstance.setMeta;
const setMetaItemsPerPage = globalInstance.setMetaItemsPerPage;
const setFilter = globalInstance.setFilter;
const search = globalInstance.search;
const isEmpty = globalInstance.isEmpty;
const isLoaded = globalInstance.isLoaded;
const setPage = globalInstance.setPage;
const loadSwitch = globalInstance.loadSwitch;
const setAdditionalQueryParameters = globalInstance.setAdditionalQueryParameters;
const addAdditionalQueryParameters = globalInstance.addAdditionalQueryParameters;
const removeAdditionalQueryParameters = globalInstance.removeAdditionalQueryParameters;
const clearAdditionalQueryParameters = globalInstance.clearAdditionalQueryParameters;
const paginatedGetRequest = globalInstance.paginatedGetRequest;
const loadList = globalInstance.loadList;
const getFilter = globalInstance.getFilter;
const fetchPageForExport = globalInstance.fetchPageForExport;
const fetchAllPagesForExport = globalInstance.fetchAllPagesForExport;
const setExportTransform = globalInstance.setExportTransform;
const clearExportTransform = globalInstance.clearExportTransform;
const exportToExcel = globalInstance.exportToExcel;


const _sfc_main$2c = {};
const paginatedList = /*#__PURE__*/_export_sfc(_sfc_main$2c, [['__file',"paginatedList.vue"]]);

const paginatedListModule = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  PaginatedListKey,
  addAdditionalQueryParameters,
  additionalQueryParameters,
  clearAdditionalQueryParameters,
  clearExportTransform,
  default: paginatedList,
  endpoint,
  exportToExcel,
  exportTransform,
  fetchAllPagesForExport,
  fetchPageForExport,
  filter,
  getFilter,
  hideSearchField,
  isEmpty,
  isExporting,
  isLoaded,
  isLoading: isLoading$1,
  lastUpdated,
  latestSearch,
  list,
  loadList,
  loadSwitch,
  meta,
  metaCurrentPage,
  metaItemsPerPage,
  metaSearch,
  metaTotalItems,
  orderBy,
  orderDirection,
  paginatedGetRequest,
  removeAdditionalQueryParameters,
  search,
  setAdditionalQueryParameters,
  setEndpoint,
  setExportTransform,
  setFilter,
  setHideSearchField,
  setLastUpdated,
  setList,
  setMeta,
  setMetaItemsPerPage,
  setOrder,
  setPage,
  usePaginatedList,
  usePaginatedListInstance
}, Symbol.toStringTag, { value: 'Module' }));

const _sfc_main$2b = /* @__PURE__ */ defineComponent({
  __name: "PaginationDisplayGeneralSearchReload",
  props: {
    hideSearch: {
      type: Boolean,
      default: false
    },
    searchPlaceholder: {
      type: String,
      default: ""
    }
  },
  setup(__props, { expose: __expose }) {
    __expose();
    const paginatedList = inject(PaginatedListKey, paginatedListModule);
    const { search, metaSearch, isLoading, loadList } = paginatedList;
    const { t } = useI18n();
    const props = __props;
    const canExport = computed(() => typeof paginatedList?.exportToExcel === "function");
    const isExporting = computed(() => Boolean(paginatedList?.isExporting?.value));
    const resolvedSearchPlaceholder = computed(() => props.searchPlaceholder || t("global.search_placeholder"));
    const isActionDropdownOpen = ref(false);
    const actionDropdownRef = ref(null);
    const closeActionDropdown = () => {
      isActionDropdownOpen.value = false;
    };
    const toggleActionDropdown = () => {
      if (Boolean(isLoading?.value) || isExporting.value) {
        return;
      }
      isActionDropdownOpen.value = !isActionDropdownOpen.value;
    };
    const handleReload = async () => {
      if (Boolean(isLoading?.value)) {
        return;
      }
      closeActionDropdown();
      await loadList();
    };
    const handleExportExcel = async () => {
      if (!canExport.value || Boolean(isLoading?.value) || isExporting.value) {
        return;
      }
      closeActionDropdown();
      await paginatedList.exportToExcel();
    };
    const handleDocumentClick = (event) => {
      if (!isActionDropdownOpen.value || !actionDropdownRef.value) {
        return;
      }
      const target = event.target;
      if (!target) {
        return;
      }
      if (!actionDropdownRef.value.contains(target)) {
        closeActionDropdown();
      }
    };
    onMounted(() => {
      document.addEventListener("click", handleDocumentClick);
    });
    onBeforeUnmount(() => {
      document.removeEventListener("click", handleDocumentClick);
    });
    const __returned__ = { paginatedList, search, metaSearch, isLoading, loadList, t, props, canExport, isExporting, resolvedSearchPlaceholder, isActionDropdownOpen, actionDropdownRef, closeActionDropdown, toggleActionDropdown, handleReload, handleExportExcel, handleDocumentClick, SessionUser: SessionUser_default };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$1b = { class: "columns is-vcentered is-multiline pagination-general-search-reload" };
const _hoisted_2$_ = {
  key: 0,
  class: "column pagination-general-search-reload__search-column"
};
const _hoisted_3$T = ["placeholder"];
const _hoisted_4$Q = {
  key: 1,
  class: "column is-narrow pagination-general-search-reload__buttons-column"
};
const _hoisted_5$M = { class: "column is-narrow pl-0 pagination-general-search-reload__action-column" };
const _hoisted_6$I = { class: "dropdown-trigger" };
const _hoisted_7$F = { class: "buttons has-addons action-dropdown-trigger" };
const _hoisted_8$D = ["disabled"];
const _hoisted_9$B = ["disabled"];
const _hoisted_10$A = {
  id: "pagination-actions-menu",
  class: "dropdown-menu",
  role: "menu"
};
const _hoisted_11$v = { class: "dropdown-content" };
function _sfc_render$1n(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock(
    Fragment,
    null,
    [
      createCommentVNode(" Top row: Reload, Search "),
      createBaseVNode("div", _hoisted_1$1b, [
        !$setup.props.hideSearch ? (openBlock(), createElementBlock("div", _hoisted_2$_, [
          withDirectives(createBaseVNode("input", {
            "data-testid": "pagination-search-input",
            class: "input",
            type: "text",
            placeholder: $setup.resolvedSearchPlaceholder,
            "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => $setup.metaSearch = $event),
            onInput: _cache[1] || (_cache[1] = ($event) => $setup.search($event.target.value))
          }, null, 40, _hoisted_3$T), [
            [vModelText, $setup.metaSearch]
          ])
        ])) : createCommentVNode("v-if", true),
        _ctx.$slots.buttons ? (openBlock(), createElementBlock("div", _hoisted_4$Q, [
          createCommentVNode(" Custom buttons slot, passing loadList for convenience "),
          renderSlot(_ctx.$slots, "buttons", { loadList: $setup.loadList }, void 0, true)
        ])) : createCommentVNode("v-if", true),
        createBaseVNode("div", _hoisted_5$M, [
          createBaseVNode(
            "div",
            {
              ref: "actionDropdownRef",
              class: normalizeClass(["dropdown is-right pagination-general-search-reload__dropdown", { "is-active": $setup.isActionDropdownOpen }]),
              "data-testid": "pagination-reload-actions"
            },
            [
              createBaseVNode("div", _hoisted_6$I, [
                createBaseVNode("div", _hoisted_7$F, [
                  createBaseVNode("button", {
                    class: normalizeClass(["button is-dark button-same-width action-dropdown-main", { "is-loading": $setup.isLoading || $setup.isExporting }]),
                    disabled: $setup.isLoading || $setup.isExporting,
                    onClick: $setup.handleReload
                  }, [
                    _cache[2] || (_cache[2] = createBaseVNode(
                      "span",
                      { class: "icon is-small" },
                      [
                        createBaseVNode("i", {
                          class: "fas fa-sync-alt",
                          "aria-hidden": "true"
                        })
                      ],
                      -1
                      /* CACHED */
                    )),
                    createBaseVNode(
                      "span",
                      null,
                      toDisplayString($setup.SessionUser.objects.global.language.reload),
                      1
                      /* TEXT */
                    )
                  ], 10, _hoisted_8$D),
                  createBaseVNode("button", {
                    class: "button is-dark action-dropdown-toggle",
                    disabled: $setup.isLoading || $setup.isExporting,
                    "aria-haspopup": "true",
                    "aria-controls": "pagination-actions-menu",
                    "aria-label": "Open update actions",
                    onClick: withModifiers($setup.toggleActionDropdown, ["stop"])
                  }, [..._cache[3] || (_cache[3] = [
                    createBaseVNode(
                      "span",
                      { class: "icon is-small" },
                      [
                        createBaseVNode("i", {
                          class: "fas fa-angle-down",
                          "aria-hidden": "true"
                        })
                      ],
                      -1
                      /* CACHED */
                    )
                  ])], 8, _hoisted_9$B)
                ])
              ]),
              createBaseVNode("div", _hoisted_10$A, [
                createBaseVNode("div", _hoisted_11$v, [
                  createBaseVNode("a", {
                    class: "dropdown-item action-dropdown-item",
                    href: "#",
                    onClick: withModifiers($setup.handleReload, ["prevent"])
                  }, [
                    _cache[4] || (_cache[4] = createBaseVNode(
                      "i",
                      {
                        class: "fas fa-sync-alt",
                        "aria-hidden": "true"
                      },
                      null,
                      -1
                      /* CACHED */
                    )),
                    createBaseVNode(
                      "span",
                      null,
                      toDisplayString($setup.SessionUser.objects.global.language.reload),
                      1
                      /* TEXT */
                    )
                  ]),
                  $setup.canExport ? (openBlock(), createElementBlock(
                    "a",
                    {
                      key: 0,
                      class: normalizeClass(["dropdown-item action-dropdown-item", { "is-disabled": $setup.isLoading || $setup.isExporting }]),
                      href: "#",
                      onClick: withModifiers($setup.handleExportExcel, ["prevent"])
                    },
                    [
                      _cache[5] || (_cache[5] = createBaseVNode(
                        "i",
                        {
                          class: "fas fa-file-excel",
                          "aria-hidden": "true"
                        },
                        null,
                        -1
                        /* CACHED */
                      )),
                      createBaseVNode(
                        "span",
                        null,
                        toDisplayString($setup.t("pagination.download_excel")),
                        1
                        /* TEXT */
                      )
                    ],
                    2
                    /* CLASS */
                  )) : createCommentVNode("v-if", true)
                ])
              ])
            ],
            2
            /* CLASS */
          )
        ])
      ])
    ],
    2112
    /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
  );
}
const PaginationDisplayGeneralSearchReload = /* @__PURE__ */ _export_sfc(_sfc_main$2b, [["render", _sfc_render$1n], ["__scopeId", "data-v-63b7f233"], ["__file", "PaginationDisplayGeneralSearchReload.vue"]]);

const _sfc_main$2a = {
  __name: 'ShowErrorField',
  props: {
  error: {
    type: [String, Object],
    default: null,
    required: false
  },
  message: {
    type: [String, Function, Object],
    default: null,
    required: false
  },
  template: {
    type: String,
    default: 'is-warning',
  }
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;

const __returned__ = { props, watch, ref, getError, clearErrors };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$1a = {
  key: 0,
  class: "notification is-danger"
};

function _sfc_render$1m(_ctx, _cache, $props, $setup, $data, $options) {
  return ($props.message)
    ? (openBlock(), createElementBlock("div", {
        key: 0,
        class: normalizeClass(["notification", $props.template])
      }, [
        withDirectives(createBaseVNode("button", {
          class: "delete",
          onClick: _cache[0] || (_cache[0] = $event => ($setup.clearErrors()))
        }, null, 512 /* NEED_PATCH */), [
          [vShow, false]
        ]),
        createTextVNode(" " + toDisplayString(typeof $props.message === 'function' ? $props.message() : $props.message), 1 /* TEXT */)
      ], 2 /* CLASS */))
    : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
        ($setup.getError($props.error))
          ? (openBlock(), createElementBlock("div", _hoisted_1$1a, [
              createBaseVNode("button", {
                class: "delete",
                onClick: _cache[1] || (_cache[1] = $event => ($setup.clearErrors()))
              }),
              createTextVNode(" " + toDisplayString($setup.getError($props.error)), 1 /* TEXT */)
            ]))
          : createCommentVNode("v-if", true)
      ], 64 /* STABLE_FRAGMENT */))
}
const ShowErrorField = /*#__PURE__*/_export_sfc(_sfc_main$2a, [['render',_sfc_render$1m],['__file',"ShowErrorField.vue"]]);

const _sfc_main$29 = {
  __name: 'PaginationDisplay',
  props: ['metaItemsPerPage', 'loadFunction', 'isLoading', 'setMetaItemsPerPage', 'allowSmallScreen'],
  setup(__props, { expose: __expose }) {
  __expose();


const { t } = useI18n();

const perPageOptions = ref([5, 10, 15, 20, 25, 50, 100, 500, 1000]);

const selectedPerPage = ref(100); // Default number of items per page

// If the screen is mobile, set the is small variable to true
const isSmall = ref(window.innerWidth < 1024);

// When the window is resized, check if the screen is mobile
window.addEventListener('resize', () => {
  isSmall.value = window.innerWidth < 1024;
});


const __returned__ = { t, perPageOptions, selectedPerPage, isSmall, ref, get useI18n() { return useI18n }, ShowErrorField };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$19 = { class: "py-2" };
const _hoisted_2$Z = { class: "columns is-vcentered is-multiline is-mobile" };
const _hoisted_3$S = { class: "label is-small" };
const _hoisted_4$P = { class: "control" };
const _hoisted_5$L = ["value"];
const _hoisted_6$H = ["value", "selected"];

function _sfc_render$1l(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$19, [
    createBaseVNode("div", _hoisted_2$Z, [
      createCommentVNode(" Change the number of items per page "),
      createBaseVNode("div", {
        class: normalizeClass(["column is-narrow", { 'is-hidden': $setup.isSmall && !$props.allowSmallScreen, 'my-3': !$setup.isSmall }])
      }, [
        createBaseVNode("label", _hoisted_3$S, toDisplayString($setup.t('pagination.per_page')), 1 /* TEXT */),
        createBaseVNode("div", _hoisted_4$P, [
          createBaseVNode("div", {
            class: normalizeClass(["select", { 'is-small': $setup.isSmall }])
          }, [
            withDirectives(createBaseVNode("select", {
              "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (($setup.selectedPerPage) = $event)),
              onChange: _cache[1] || (_cache[1] = $event => {$props.setMetaItemsPerPage($setup.selectedPerPage); $setup.selectedPerPage.valueOf = $setup.selectedPerPage;})
            }, [
              createCommentVNode(" If the selected number of items per page is not in the list, add it to the list "),
              (!$setup.perPageOptions.includes($setup.selectedPerPage))
                ? (openBlock(), createElementBlock("option", {
                    key: 0,
                    value: $setup.selectedPerPage,
                    class: normalizeClass({ 'is-skeleton': $props.isLoading }),
                    selected: ""
                  }, toDisplayString($setup.selectedPerPage), 11 /* TEXT, CLASS, PROPS */, _hoisted_5$L))
                : createCommentVNode("v-if", true),
              createCommentVNode(" Show the options, with the selected option marked as selected "),
              (openBlock(true), createElementBlock(Fragment, null, renderList($setup.perPageOptions, (option) => {
                return (openBlock(), createElementBlock("option", {
                  value: option,
                  class: normalizeClass({ 'is-skeleton': $props.isLoading }),
                  selected: option === $props.metaItemsPerPage.value
                }, toDisplayString(option), 11 /* TEXT, CLASS, PROPS */, _hoisted_6$H))
              }), 256 /* UNKEYED_FRAGMENT */))
            ], 544 /* NEED_HYDRATION, NEED_PATCH */), [
              [vModelSelect, $setup.selectedPerPage]
            ])
          ], 2 /* CLASS */)
        ])
      ], 2 /* CLASS */),
      renderSlot(_ctx.$slots, "paginationColumns")
    ]),
    createCommentVNode(" Display the pagination error, if any "),
    createVNode($setup["ShowErrorField"], { error: "paginatedGetRequest" })
  ]))
}
const PaginationDisplay = /*#__PURE__*/_export_sfc(_sfc_main$29, [['render',_sfc_render$1l],['__file',"PaginationDisplay.vue"]]);

const _sfc_main$28 = {
  __name: 'PaginationNavigation',
  props: ['currentPage', 'totalPages', 'setPage', 'loadFunction', 'isLoading'],
  setup(__props, { expose: __expose }) {
  __expose();



const { t } = useI18n();

const __returned__ = { t, get useI18n() { return useI18n } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$18 = {
  class: "pagination is-centered",
  role: "navigation",
  "aria-label": "pagination"
};
const _hoisted_2$Y = { class: "pagination-list mt-1" };
const _hoisted_3$R = ["onClick"];
const _hoisted_4$O = {
  key: 1,
  class: "pagination-ellipsis"
};
const _hoisted_5$K = {
  key: 10,
  class: "pagination-ellipsis"
};
const _hoisted_6$G = {
  key: 0,
  class: "has-text-centered"
};
const _hoisted_7$E = {
  key: 1,
  class: "has-text-centered"
};

function _sfc_render$1k(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock(Fragment, null, [
    createBaseVNode("nav", _hoisted_1$18, [
      createCommentVNode(" Previous page "),
      ($props.totalPages <= 15)
        ? (openBlock(), createElementBlock("a", {
            key: 0,
            class: normalizeClass(["pagination-previous pagination-button button-same-width", { 'is-disabled': $props.currentPage === 1, 'is-skeleton': $props.isLoading }]),
            onClick: _cache[0] || (_cache[0] = $event => {$props.setPage($props.currentPage - 1); $props.loadFunction();})
          }, toDisplayString($setup.t('pagination.previous')), 3 /* TEXT, CLASS */))
        : createCommentVNode("v-if", true),
      createCommentVNode(" Pagination skeleton while loading "),
      createCommentVNode(" Pagination (IF there's less than 20 pages) "),
      createBaseVNode("ul", _hoisted_2$Y, [
        ($props.totalPages <= 15)
          ? (openBlock(true), createElementBlock(Fragment, { key: 0 }, renderList($props.totalPages, (page) => {
              return (openBlock(), createElementBlock("li", { key: page }, [
                createBaseVNode("a", {
                  class: normalizeClass(["pagination-link", { 'is-skeleton': $props.isLoading, 'is-current': $props.currentPage === page }]),
                  onClick: $event => {$props.setPage(page); $props.loadFunction();}
                }, toDisplayString(page), 11 /* TEXT, CLASS, PROPS */, _hoisted_3$R)
              ]))
            }), 128 /* KEYED_FRAGMENT */))
          : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
              createCommentVNode(" Pagination (IF there's more than 20 pages) "),
              createBaseVNode("li", null, [
                createCommentVNode(" Regular pagination "),
                ($props.currentPage > 3)
                  ? (openBlock(), createElementBlock("a", {
                      key: 0,
                      class: normalizeClass(["pagination-link", { 'is-skeleton': $props.isLoading, 'is-current': $props.currentPage === 1 }]),
                      onClick: _cache[1] || (_cache[1] = $event => {$props.setPage(1); $props.loadFunction();})
                    }, "1", 2 /* CLASS */))
                  : createCommentVNode("v-if", true),
                ($props.currentPage > 3)
                  ? (openBlock(), createElementBlock("span", _hoisted_4$O, "…"))
                  : createCommentVNode("v-if", true),
                createCommentVNode(" If there isn't 2 next pages, show the additional pages to the left, this is done to keep the pagination buttons the same size "),
                ($props.currentPage > 3 && $props.totalPages - $props.currentPage < 1)
                  ? (openBlock(), createElementBlock("a", {
                      key: 2,
                      class: normalizeClass(["pagination-link", { 'is-skeleton': $props.isLoading }]),
                      onClick: _cache[2] || (_cache[2] = $event => {$props.setPage($props.totalPages - 4); $props.loadFunction();})
                    }, toDisplayString($props.currentPage - 4), 3 /* TEXT, CLASS */))
                  : createCommentVNode("v-if", true),
                ($props.currentPage > 2 && $props.totalPages - $props.currentPage < 2)
                  ? (openBlock(), createElementBlock("a", {
                      key: 3,
                      class: normalizeClass(["pagination-link", { 'is-skeleton': $props.isLoading }]),
                      onClick: _cache[3] || (_cache[3] = $event => {$props.setPage($props.totalPages - 3); $props.loadFunction();})
                    }, toDisplayString($props.currentPage - 3), 3 /* TEXT, CLASS */))
                  : createCommentVNode("v-if", true),
                createCommentVNode(" Regular pagination "),
                ($props.currentPage > 2)
                  ? (openBlock(), createElementBlock("a", {
                      key: 4,
                      class: normalizeClass(["pagination-link", { 'is-skeleton': $props.isLoading }]),
                      onClick: _cache[4] || (_cache[4] = $event => {$props.setPage($props.currentPage - 2); $props.loadFunction();})
                    }, toDisplayString($props.currentPage - 2), 3 /* TEXT, CLASS */))
                  : createCommentVNode("v-if", true),
                ($props.currentPage > 1)
                  ? (openBlock(), createElementBlock("a", {
                      key: 5,
                      class: normalizeClass(["pagination-link", { 'is-skeleton': $props.isLoading }]),
                      onClick: _cache[5] || (_cache[5] = $event => {$props.setPage($props.currentPage - 1); $props.loadFunction();})
                    }, toDisplayString($props.currentPage - 1), 3 /* TEXT, CLASS */))
                  : createCommentVNode("v-if", true),
                createBaseVNode("a", {
                  class: normalizeClass(["pagination-link is-current", { 'is-skeleton': $props.isLoading }]),
                  onClick: _cache[6] || (_cache[6] = $event => {$props.setPage($props.currentPage); $props.loadFunction();})
                }, toDisplayString($props.currentPage), 3 /* TEXT, CLASS */),
                ($props.currentPage < $props.totalPages)
                  ? (openBlock(), createElementBlock("a", {
                      key: 6,
                      class: normalizeClass(["pagination-link", { 'is-skeleton': $props.isLoading }]),
                      onClick: _cache[7] || (_cache[7] = $event => {$props.setPage($props.currentPage + 1); $props.loadFunction();})
                    }, toDisplayString($props.currentPage + 1), 3 /* TEXT, CLASS */))
                  : createCommentVNode("v-if", true),
                ($props.currentPage < $props.totalPages - 1)
                  ? (openBlock(), createElementBlock("a", {
                      key: 7,
                      class: normalizeClass(["pagination-link", { 'is-skeleton': $props.isLoading }]),
                      onClick: _cache[8] || (_cache[8] = $event => {$props.setPage($props.currentPage + 2); $props.loadFunction();})
                    }, toDisplayString($props.currentPage + 2), 3 /* TEXT, CLASS */))
                  : createCommentVNode("v-if", true),
                createCommentVNode(" If the current page is less than 3, show the additional pages to the right, this is done to keep the pagination buttons the same size "),
                ($props.currentPage < $props.totalPages - 3 && $props.currentPage < 3)
                  ? (openBlock(), createElementBlock("a", {
                      key: 8,
                      class: normalizeClass(["pagination-link", { 'is-skeleton': $props.isLoading }]),
                      onClick: _cache[9] || (_cache[9] = $event => {$props.setPage($props.totalPages + 3); $props.loadFunction();})
                    }, toDisplayString($props.currentPage + 3), 3 /* TEXT, CLASS */))
                  : createCommentVNode("v-if", true),
                ($props.currentPage < $props.totalPages - 4 && $props.currentPage < 2)
                  ? (openBlock(), createElementBlock("a", {
                      key: 9,
                      class: normalizeClass(["pagination-link", { 'is-skeleton': $props.isLoading }]),
                      onClick: _cache[10] || (_cache[10] = $event => {$props.setPage($props.totalPages + 4); $props.loadFunction();})
                    }, toDisplayString($props.currentPage + 4), 3 /* TEXT, CLASS */))
                  : createCommentVNode("v-if", true),
                ($props.currentPage < $props.totalPages - 2)
                  ? (openBlock(), createElementBlock("span", _hoisted_5$K, "…"))
                  : createCommentVNode("v-if", true),
                ($props.currentPage < $props.totalPages - 2)
                  ? (openBlock(), createElementBlock("a", {
                      key: 11,
                      class: normalizeClass(["pagination-link", { 'is-skeleton': $props.isLoading, 'is-current': $props.currentPage === $props.totalPages }]),
                      onClick: _cache[11] || (_cache[11] = $event => {$props.setPage($props.totalPages); $props.loadFunction();})
                    }, toDisplayString($props.totalPages), 3 /* TEXT, CLASS */))
                  : createCommentVNode("v-if", true)
              ])
            ], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */))
      ]),
      ($props.totalPages <= 15)
        ? (openBlock(), createElementBlock("a", {
            key: 1,
            class: normalizeClass(["pagination-next pagination-button button-same-width", { 'is-disabled': $props.currentPage === $props.totalPages, 'is-skeleton': $props.isLoading }]),
            onClick: _cache[12] || (_cache[12] = $event => {$props.setPage($props.currentPage + 1); $props.loadFunction();})
          }, toDisplayString($setup.t('pagination.next')), 3 /* TEXT, CLASS */))
        : createCommentVNode("v-if", true),
      createCommentVNode(" Navigation when there's more than 15 pages "),
      ($props.totalPages > 15)
        ? (openBlock(), createElementBlock("a", {
            key: 2,
            class: normalizeClass(["pagination-previous pagination-button", { 'is-disabled': $props.currentPage === 1, 'is-skeleton': $props.isLoading }]),
            onClick: _cache[13] || (_cache[13] = $event => {$props.setPage($props.currentPage - 1); $props.loadFunction();})
          }, toDisplayString($setup.t('pagination.previous')), 3 /* TEXT, CLASS */))
        : createCommentVNode("v-if", true),
      ($props.totalPages > 15)
        ? (openBlock(), createElementBlock("a", {
            key: 3,
            class: normalizeClass(["pagination-next pagination-button", { 'is-disabled': $props.currentPage === $props.totalPages, 'is-skeleton': $props.isLoading }]),
            onClick: _cache[14] || (_cache[14] = $event => {$props.setPage($props.currentPage + 1); $props.loadFunction();})
          }, toDisplayString($setup.t('pagination.next')), 3 /* TEXT, CLASS */))
        : createCommentVNode("v-if", true)
    ]),
    ($props.totalPages > 0)
      ? (openBlock(), createElementBlock("p", _hoisted_6$G, toDisplayString($setup.t('pagination.page_of', { current: $props.currentPage, total: $props.totalPages })), 1 /* TEXT */))
      : (openBlock(), createElementBlock("p", _hoisted_7$E, toDisplayString($setup.t('pagination.loading')), 1 /* TEXT */))
  ], 64 /* STABLE_FRAGMENT */))
}
const PaginationNavigation = /*#__PURE__*/_export_sfc(_sfc_main$28, [['render',_sfc_render$1k],['__scopeId',"data-v-bba717f9"],['__file',"PaginationNavigation.vue"]]);

const _sfc_main$27 = {
  __name: 'TableLabeledPagination',
  props: {
  label: {
    type: String,
    required: true,
  },
  showFilters: {
    type: Boolean,
    default: true,
  },
  hideSearch: {
    type: Boolean,
    default: false,
  },
  searchPlaceholder: {
    type: String,
    default: "",
  },
  hidePagination: {
    type: Boolean,
    default: false,
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const paginatedList = inject(PaginatedListKey, paginatedListModule);
const { isLoading, loadList, metaCurrentPage, metaItemsPerPage, metaTotalItems, setMetaItemsPerPage, setPage } =
  paginatedList;

const props = __props;
const isSmall = ref(window.innerWidth < 1024);

const __returned__ = { paginatedList, isLoading, loadList, metaCurrentPage, metaItemsPerPage, metaTotalItems, setMetaItemsPerPage, setPage, props, isSmall, ref, inject, paginatedListModule, PaginationDisplayGeneralSearchReload, PaginationDisplay, PaginationNavigation };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$17 = { "data-disable-auto-excel-export": "1" };
const _hoisted_2$X = { class: "title is-4 mb-4" };
const _hoisted_3$Q = {
  key: 0,
  class: "column is-auto-fill my-3"
};
const _hoisted_4$N = { class: "columns is-multiline" };
const _hoisted_5$J = { class: "mb-6" };

function _sfc_render$1j(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$17, [
    createCommentVNode(" Label "),
    createBaseVNode("h2", _hoisted_2$X, toDisplayString($props.label), 1 /* TEXT */),
    renderSlot(_ctx.$slots, "description"),
    createCommentVNode(" Search & reload "),
    (!$setup.props.hideSearch || _ctx.$slots.buttons)
      ? (openBlock(), createBlock($setup["PaginationDisplayGeneralSearchReload"], {
          key: 0,
          "hide-search": $setup.props.hideSearch,
          "search-placeholder": $setup.props.searchPlaceholder
        }, createSlots({ _: 2 /* DYNAMIC */ }, [
          (_ctx.$slots.buttons)
            ? {
                name: "buttons",
                fn: withCtx(({ loadList }) => [
                  renderSlot(_ctx.$slots, "buttons", { loadList: loadList })
                ]),
                key: "0"
              }
            : undefined
        ]), 1032 /* PROPS, DYNAMIC_SLOTS */, ["hide-search", "search-placeholder"]))
      : createCommentVNode("v-if", true),
    renderSlot(_ctx.$slots, "afterSearch"),
    createCommentVNode(" Filters "),
    ($props.showFilters)
      ? (openBlock(), createBlock($setup["PaginationDisplay"], {
          key: 1,
          "data-testid": "table-labeled-pagination-filters",
          metaItemsPerPage: $setup.metaItemsPerPage,
          loadFunction: $setup.loadList,
          isLoading: $setup.isLoading,
          setMetaItemsPerPage: $setup.setMetaItemsPerPage
        }, {
          paginationColumns: withCtx(() => [
            renderSlot(_ctx.$slots, "paginationDisplayFiltersElement"),
            renderSlot(_ctx.$slots, "leftPaginationColumns"),
            (!$setup.isSmall)
              ? (openBlock(), createElementBlock("div", _hoisted_3$Q))
              : createCommentVNode("v-if", true),
            renderSlot(_ctx.$slots, "rightFilterActions"),
            createBaseVNode("div", _hoisted_4$N, [
              _cache[0] || (_cache[0] = createBaseVNode("div", { class: "column is-12 p-1 m-0" }, null, -1 /* CACHED */)),
              renderSlot(_ctx.$slots, "rightPaginationColumns")
            ])
          ]),
          _: 3 /* FORWARDED */
        }, 8 /* PROPS */, ["metaItemsPerPage", "loadFunction", "isLoading", "setMetaItemsPerPage"]))
      : createCommentVNode("v-if", true),
    createCommentVNode(" Table "),
    createBaseVNode("section", _hoisted_5$J, [
      renderSlot(_ctx.$slots, "default")
    ]),
    createCommentVNode(" Pagination "),
    (!$setup.props.hidePagination)
      ? (openBlock(), createBlock($setup["PaginationNavigation"], {
          key: 2,
          currentPage: $setup.metaCurrentPage,
          totalPages: Math.ceil($setup.metaTotalItems / $setup.metaItemsPerPage),
          loadFunction: $setup.loadList,
          setPage: $setup.setPage,
          isLoading: $setup.isLoading
        }, null, 8 /* PROPS */, ["currentPage", "totalPages", "loadFunction", "setPage", "isLoading"]))
      : createCommentVNode("v-if", true)
  ]))
}
const TableLabeledPagination = /*#__PURE__*/_export_sfc(_sfc_main$27, [['render',_sfc_render$1j],['__file',"TableLabeledPagination.vue"]]);

/*!
 * vue-router v4.6.4
 * (c) 2025 Eduardo San Martin Morote
 * @license MIT
 */
const isBrowser = typeof document !== "undefined";
const identityFn = (v) => v;
function isRouteComponent(component) {
  return typeof component === "object" || "displayName" in component || "props" in component || "__vccOpts" in component;
}
function isESModule(obj) {
  return obj.__esModule || obj[Symbol.toStringTag] === "Module" || obj.default && isRouteComponent(obj.default);
}
const assign = Object.assign;
function applyToParams(fn, params) {
  const newParams = {};
  for (const key in params) {
    const value = params[key];
    newParams[key] = isArray$1(value) ? value.map(fn) : fn(value);
  }
  return newParams;
}
const noop$1 = () => {
};
const isArray$1 = Array.isArray;
function mergeOptions(defaults, partialOptions) {
  const options = {};
  for (const key in defaults) options[key] = key in partialOptions ? partialOptions[key] : defaults[key];
  return options;
}
function warn$1(msg) {
  const args = Array.from(arguments).slice(1);
  console.warn.apply(console, ["[Vue Router warn]: " + msg].concat(args));
}
const HASH_RE = /#/g;
const AMPERSAND_RE = /&/g;
const SLASH_RE = /\//g;
const EQUAL_RE = /=/g;
const IM_RE = /\?/g;
const PLUS_RE = /\+/g;
const ENC_BRACKET_OPEN_RE = /%5B/g;
const ENC_BRACKET_CLOSE_RE = /%5D/g;
const ENC_CARET_RE = /%5E/g;
const ENC_BACKTICK_RE = /%60/g;
const ENC_CURLY_OPEN_RE = /%7B/g;
const ENC_PIPE_RE = /%7C/g;
const ENC_CURLY_CLOSE_RE = /%7D/g;
const ENC_SPACE_RE = /%20/g;
function commonEncode(text) {
  return text == null ? "" : encodeURI("" + text).replace(ENC_PIPE_RE, "|").replace(ENC_BRACKET_OPEN_RE, "[").replace(ENC_BRACKET_CLOSE_RE, "]");
}
function encodeHash(text) {
  return commonEncode(text).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^");
}
function encodeQueryValue(text) {
  return commonEncode(text).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^");
}
function encodeQueryKey(text) {
  return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
}
function encodePath(text) {
  return commonEncode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F");
}
function encodeParam(text) {
  return encodePath(text).replace(SLASH_RE, "%2F");
}
function decode(text) {
  if (text == null) return null;
  try {
    return decodeURIComponent("" + text);
  } catch (err) {
  }
  return "" + text;
}
const TRAILING_SLASH_RE = /\/$/;
const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, "");
function parseURL(parseQuery$1, location, currentLocation = "/") {
  let path, query = {}, searchString = "", hash = "";
  const hashPos = location.indexOf("#");
  let searchPos = location.indexOf("?");
  searchPos = hashPos >= 0 && searchPos > hashPos ? -1 : searchPos;
  if (searchPos >= 0) {
    path = location.slice(0, searchPos);
    searchString = location.slice(searchPos, hashPos > 0 ? hashPos : location.length);
    query = parseQuery$1(searchString.slice(1));
  }
  if (hashPos >= 0) {
    path = path || location.slice(0, hashPos);
    hash = location.slice(hashPos, location.length);
  }
  path = resolveRelativePath(path != null ? path : location, currentLocation);
  return {
    fullPath: path + searchString + hash,
    path,
    query,
    hash: decode(hash)
  };
}
function NEW_stringifyURL(stringifyQuery$1, path, query, hash = "") {
  const searchText = stringifyQuery$1(query);
  return path + (searchText && "?") + searchText + encodeHash(hash);
}
function stringifyURL(stringifyQuery$1, location) {
  const query = location.query ? stringifyQuery$1(location.query) : "";
  return location.path + (query && "?") + query + (location.hash || "");
}
function stripBase(pathname, base) {
  if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase())) return pathname;
  return pathname.slice(base.length) || "/";
}
function isSameRouteLocation(stringifyQuery$1, a, b) {
  const aLastIndex = a.matched.length - 1;
  const bLastIndex = b.matched.length - 1;
  return aLastIndex > -1 && aLastIndex === bLastIndex && isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) && isSameRouteLocationParams(a.params, b.params) && stringifyQuery$1(a.query) === stringifyQuery$1(b.query) && a.hash === b.hash;
}
function isSameRouteRecord(a, b) {
  return (a.aliasOf || a) === (b.aliasOf || b);
}
function isSameRouteLocationParams(a, b) {
  if (Object.keys(a).length !== Object.keys(b).length) return false;
  for (var key in a) if (!isSameRouteLocationParamsValue(a[key], b[key])) return false;
  return true;
}
function isSameRouteLocationParamsValue(a, b) {
  return isArray$1(a) ? isEquivalentArray(a, b) : isArray$1(b) ? isEquivalentArray(b, a) : a?.valueOf() === b?.valueOf();
}
function isEquivalentArray(a, b) {
  return isArray$1(b) ? a.length === b.length && a.every((value, i) => value === b[i]) : a.length === 1 && a[0] === b;
}
function resolveRelativePath(to, from) {
  if (to.startsWith("/")) return to;
  if (false) {
    warn$1(`Cannot resolve a relative location without an absolute path. Trying to resolve "${to}" from "${from}". It should look like "/${from}".`);
    return to;
  }
  if (!to) return from;
  const fromSegments = from.split("/");
  const toSegments = to.split("/");
  const lastToSegment = toSegments[toSegments.length - 1];
  if (lastToSegment === ".." || lastToSegment === ".") toSegments.push("");
  let position = fromSegments.length - 1;
  let toPosition;
  let segment;
  for (toPosition = 0; toPosition < toSegments.length; toPosition++) {
    segment = toSegments[toPosition];
    if (segment === ".") continue;
    if (segment === "..") {
      if (position > 1) position--;
    } else break;
  }
  return fromSegments.slice(0, position).join("/") + "/" + toSegments.slice(toPosition).join("/");
}
const START_LOCATION_NORMALIZED = {
  path: "/",
  name: void 0,
  params: {},
  query: {},
  hash: "",
  fullPath: "/",
  matched: [],
  meta: {},
  redirectedFrom: void 0
};
let NavigationType = /* @__PURE__ */ (function(NavigationType$1) {
  NavigationType$1["pop"] = "pop";
  NavigationType$1["push"] = "push";
  return NavigationType$1;
})({});
let NavigationDirection = /* @__PURE__ */ (function(NavigationDirection$1) {
  NavigationDirection$1["back"] = "back";
  NavigationDirection$1["forward"] = "forward";
  NavigationDirection$1["unknown"] = "";
  return NavigationDirection$1;
})({});
const START = "";
function normalizeBase(base) {
  if (!base) if (isBrowser) {
    const baseEl = document.querySelector("base");
    base = baseEl && baseEl.getAttribute("href") || "/";
    base = base.replace(/^\w+:\/\/[^\/]+/, "");
  } else base = "/";
  if (base[0] !== "/" && base[0] !== "#") base = "/" + base;
  return removeTrailingSlash(base);
}
const BEFORE_HASH_RE = /^[^#]+#/;
function createHref(base, location) {
  return base.replace(BEFORE_HASH_RE, "#") + location;
}
function getElementPosition(el, offset) {
  const docRect = document.documentElement.getBoundingClientRect();
  const elRect = el.getBoundingClientRect();
  return {
    behavior: offset.behavior,
    left: elRect.left - docRect.left - (offset.left || 0),
    top: elRect.top - docRect.top - (offset.top || 0)
  };
}
const computeScrollPosition = () => ({
  left: window.scrollX,
  top: window.scrollY
});
function scrollToPosition(position) {
  let scrollToOptions;
  if ("el" in position) {
    const positionEl = position.el;
    const isIdSelector = typeof positionEl === "string" && positionEl.startsWith("#");
    if (false) {
      if (!isIdSelector || !document.getElementById(position.el.slice(1))) try {
        const foundEl = document.querySelector(position.el);
        if (isIdSelector && foundEl) {
          warn$1(`The selector "${position.el}" should be passed as "el: document.querySelector('${position.el}')" because it starts with "#".`);
          return;
        }
      } catch (err) {
        warn$1(`The selector "${position.el}" is invalid. If you are using an id selector, make sure to escape it. You can find more information about escaping characters in selectors at https://mathiasbynens.be/notes/css-escapes or use CSS.escape (https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape).`);
        return;
      }
    }
    const el = typeof positionEl === "string" ? isIdSelector ? document.getElementById(positionEl.slice(1)) : document.querySelector(positionEl) : positionEl;
    if (!el) {
      return;
    }
    scrollToOptions = getElementPosition(el, position);
  } else scrollToOptions = position;
  if ("scrollBehavior" in document.documentElement.style) window.scrollTo(scrollToOptions);
  else window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.scrollX, scrollToOptions.top != null ? scrollToOptions.top : window.scrollY);
}
function getScrollKey(path, delta) {
  return (history.state ? history.state.position - delta : -1) + path;
}
const scrollPositions = /* @__PURE__ */ new Map();
function saveScrollPosition(key, scrollPosition) {
  scrollPositions.set(key, scrollPosition);
}
function getSavedScrollPosition(key) {
  const scroll = scrollPositions.get(key);
  scrollPositions.delete(key);
  return scroll;
}
function isRouteLocation(route) {
  return typeof route === "string" || route && typeof route === "object";
}
function isRouteName(name) {
  return typeof name === "string" || typeof name === "symbol";
}
let ErrorTypes = /* @__PURE__ */ (function(ErrorTypes$1) {
  ErrorTypes$1[ErrorTypes$1["MATCHER_NOT_FOUND"] = 1] = "MATCHER_NOT_FOUND";
  ErrorTypes$1[ErrorTypes$1["NAVIGATION_GUARD_REDIRECT"] = 2] = "NAVIGATION_GUARD_REDIRECT";
  ErrorTypes$1[ErrorTypes$1["NAVIGATION_ABORTED"] = 4] = "NAVIGATION_ABORTED";
  ErrorTypes$1[ErrorTypes$1["NAVIGATION_CANCELLED"] = 8] = "NAVIGATION_CANCELLED";
  ErrorTypes$1[ErrorTypes$1["NAVIGATION_DUPLICATED"] = 16] = "NAVIGATION_DUPLICATED";
  return ErrorTypes$1;
})({});
const NavigationFailureSymbol = Symbol(false ? "navigation failure" : "");
let NavigationFailureType = /* @__PURE__ */ (function(NavigationFailureType$1) {
  NavigationFailureType$1[NavigationFailureType$1["aborted"] = 4] = "aborted";
  NavigationFailureType$1[NavigationFailureType$1["cancelled"] = 8] = "cancelled";
  NavigationFailureType$1[NavigationFailureType$1["duplicated"] = 16] = "duplicated";
  return NavigationFailureType$1;
})({});
const ErrorTypeMessages = {
  [ErrorTypes.MATCHER_NOT_FOUND]({ location, currentLocation }) {
    return `No match for
 ${JSON.stringify(location)}${currentLocation ? "\nwhile being at\n" + JSON.stringify(currentLocation) : ""}`;
  },
  [ErrorTypes.NAVIGATION_GUARD_REDIRECT]({ from, to }) {
    return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`;
  },
  [ErrorTypes.NAVIGATION_ABORTED]({ from, to }) {
    return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`;
  },
  [ErrorTypes.NAVIGATION_CANCELLED]({ from, to }) {
    return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`;
  },
  [ErrorTypes.NAVIGATION_DUPLICATED]({ from, to }) {
    return `Avoided redundant navigation to current location: "${from.fullPath}".`;
  }
};
function createRouterError(type, params) {
  if (false) return assign(new Error(ErrorTypeMessages[type](params)), {
    type,
    [NavigationFailureSymbol]: true
  }, params);
  else return assign(/* @__PURE__ */ new Error(), {
    type,
    [NavigationFailureSymbol]: true
  }, params);
}
function isNavigationFailure(error, type) {
  return error instanceof Error && NavigationFailureSymbol in error && (type == null || !!(error.type & type));
}
const propertiesToLog = [
  "params",
  "query",
  "hash"
];
function stringifyRoute(to) {
  if (typeof to === "string") return to;
  if (to.path != null) return to.path;
  const location = {};
  for (const key of propertiesToLog) if (key in to) location[key] = to[key];
  return JSON.stringify(location, null, 2);
}
function parseQuery(search) {
  const query = {};
  if (search === "" || search === "?") return query;
  const searchParams = (search[0] === "?" ? search.slice(1) : search).split("&");
  for (let i = 0; i < searchParams.length; ++i) {
    const searchParam = searchParams[i].replace(PLUS_RE, " ");
    const eqPos = searchParam.indexOf("=");
    const key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
    const value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
    if (key in query) {
      let currentValue = query[key];
      if (!isArray$1(currentValue)) currentValue = query[key] = [currentValue];
      currentValue.push(value);
    } else query[key] = value;
  }
  return query;
}
function stringifyQuery(query) {
  let search = "";
  for (let key in query) {
    const value = query[key];
    key = encodeQueryKey(key);
    if (value == null) {
      if (value !== void 0) search += (search.length ? "&" : "") + key;
      continue;
    }
    (isArray$1(value) ? value.map((v) => v && encodeQueryValue(v)) : [value && encodeQueryValue(value)]).forEach((value$1) => {
      if (value$1 !== void 0) {
        search += (search.length ? "&" : "") + key;
        if (value$1 != null) search += "=" + value$1;
      }
    });
  }
  return search;
}
function normalizeQuery(query) {
  const normalizedQuery = {};
  for (const key in query) {
    const value = query[key];
    if (value !== void 0) normalizedQuery[key] = isArray$1(value) ? value.map((v) => v == null ? null : "" + v) : value == null ? value : "" + value;
  }
  return normalizedQuery;
}
const matchedRouteKey = Symbol(false ? "router view location matched" : "");
const viewDepthKey = Symbol(false ? "router view depth" : "");
const routerKey = Symbol(false ? "router" : "");
const routeLocationKey = Symbol(false ? "route location" : "");
const routerViewLocationKey = Symbol(false ? "router view location" : "");
function useCallbacks() {
  let handlers = [];
  function add(handler) {
    handlers.push(handler);
    return () => {
      const i = handlers.indexOf(handler);
      if (i > -1) handlers.splice(i, 1);
    };
  }
  function reset() {
    handlers = [];
  }
  return {
    add,
    list: () => handlers.slice(),
    reset
  };
}
function registerGuard(record, name, guard) {
  const removeFromList = () => {
    record[name].delete(guard);
  };
  onUnmounted(removeFromList);
  onDeactivated(removeFromList);
  onActivated(() => {
    record[name].add(guard);
  });
  record[name].add(guard);
}
function onBeforeRouteLeave(leaveGuard) {
  if (false) {
    warn$1("getCurrentInstance() returned null. onBeforeRouteLeave() must be called at the top of a setup function");
    return;
  }
  const activeRecord = inject(matchedRouteKey, {}).value;
  if (!activeRecord) {
    return;
  }
  registerGuard(activeRecord, "leaveGuards", leaveGuard);
}
function onBeforeRouteUpdate(updateGuard) {
  if (false) {
    warn$1("getCurrentInstance() returned null. onBeforeRouteUpdate() must be called at the top of a setup function");
    return;
  }
  const activeRecord = inject(matchedRouteKey, {}).value;
  if (!activeRecord) {
    return;
  }
  registerGuard(activeRecord, "updateGuards", updateGuard);
}
function guardToPromiseFn(guard, to, from, record, name, runWithContext = (fn) => fn()) {
  const enterCallbackArray = record && (record.enterCallbacks[name] = record.enterCallbacks[name] || []);
  return () => new Promise((resolve, reject) => {
    const next = (valid) => {
      if (valid === false) reject(createRouterError(ErrorTypes.NAVIGATION_ABORTED, {
        from,
        to
      }));
      else if (valid instanceof Error) reject(valid);
      else if (isRouteLocation(valid)) reject(createRouterError(ErrorTypes.NAVIGATION_GUARD_REDIRECT, {
        from: to,
        to: valid
      }));
      else {
        if (enterCallbackArray && record.enterCallbacks[name] === enterCallbackArray && typeof valid === "function") enterCallbackArray.push(valid);
        resolve();
      }
    };
    const guardReturn = runWithContext(() => guard.call(record && record.instances[name], to, from, false ? canOnlyBeCalledOnce(next, to, from) : next));
    let guardCall = Promise.resolve(guardReturn);
    if (guard.length < 3) guardCall = guardCall.then(next);
    if (false) {
      const message = `The "next" callback was never called inside of ${guard.name ? '"' + guard.name + '"' : ""}:
${guard.toString()}
. If you are returning a value instead of calling "next", make sure to remove the "next" parameter from your function.`;
      if (typeof guardReturn === "object" && "then" in guardReturn) guardCall = guardCall.then((resolvedValue) => {
        if (!next._called) {
          warn$1(message);
          return Promise.reject(/* @__PURE__ */ new Error("Invalid navigation guard"));
        }
        return resolvedValue;
      });
      else if (guardReturn !== void 0) {
        if (!next._called) {
          warn$1(message);
          reject(/* @__PURE__ */ new Error("Invalid navigation guard"));
          return;
        }
      }
    }
    guardCall.catch((err) => reject(err));
  });
}
function canOnlyBeCalledOnce(next, to, from) {
  let called = 0;
  return function() {
    if (called++ === 1) warn$1(`The "next" callback was called more than once in one navigation guard when going from "${from.fullPath}" to "${to.fullPath}". It should be called exactly one time in each navigation guard. This will fail in production.`);
    next._called = true;
    if (called === 1) next.apply(null, arguments);
  };
}
function extractComponentsGuards(matched, guardType, to, from, runWithContext = (fn) => fn()) {
  const guards = [];
  for (const record of matched) {
    if (false) warn$1(`Record with path "${record.path}" is either missing a "component(s)" or "children" property.`);
    for (const name in record.components) {
      let rawComponent = record.components[name];
      if (false) {
        if (!rawComponent || typeof rawComponent !== "object" && typeof rawComponent !== "function") {
          warn$1(`Component "${name}" in record with path "${record.path}" is not a valid component. Received "${String(rawComponent)}".`);
          throw new Error("Invalid route component");
        } else if ("then" in rawComponent) {
          warn$1(`Component "${name}" in record with path "${record.path}" is a Promise instead of a function that returns a Promise. Did you write "import('./MyPage.vue')" instead of "() => import('./MyPage.vue')" ? This will break in production if not fixed.`);
          const promise = rawComponent;
          rawComponent = () => promise;
        } else if (rawComponent.__asyncLoader && !rawComponent.__warnedDefineAsync) {
          rawComponent.__warnedDefineAsync = true;
          warn$1(`Component "${name}" in record with path "${record.path}" is defined using "defineAsyncComponent()". Write "() => import('./MyPage.vue')" instead of "defineAsyncComponent(() => import('./MyPage.vue'))".`);
        }
      }
      if (guardType !== "beforeRouteEnter" && !record.instances[name]) continue;
      if (isRouteComponent(rawComponent)) {
        const guard = (rawComponent.__vccOpts || rawComponent)[guardType];
        guard && guards.push(guardToPromiseFn(guard, to, from, record, name, runWithContext));
      } else {
        let componentPromise = rawComponent();
        if (false) {
          warn$1(`Component "${name}" in record with path "${record.path}" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.`);
          componentPromise = Promise.resolve(componentPromise);
        }
        guards.push(() => componentPromise.then((resolved) => {
          if (!resolved) throw new Error(`Couldn't resolve component "${name}" at "${record.path}"`);
          const resolvedComponent = isESModule(resolved) ? resolved.default : resolved;
          record.mods[name] = resolved;
          record.components[name] = resolvedComponent;
          const guard = (resolvedComponent.__vccOpts || resolvedComponent)[guardType];
          return guard && guardToPromiseFn(guard, to, from, record, name, runWithContext)();
        }));
      }
    }
  }
  return guards;
}
function loadRouteLocation(route) {
  return route.matched.every((record) => record.redirect) ? Promise.reject(/* @__PURE__ */ new Error("Cannot load a route that redirects.")) : Promise.all(route.matched.map((record) => record.components && Promise.all(Object.keys(record.components).reduce((promises, name) => {
    const rawComponent = record.components[name];
    if (typeof rawComponent === "function" && !("displayName" in rawComponent)) promises.push(rawComponent().then((resolved) => {
      if (!resolved) return Promise.reject(/* @__PURE__ */ new Error(`Couldn't resolve component "${name}" at "${record.path}". Ensure you passed a function that returns a promise.`));
      const resolvedComponent = isESModule(resolved) ? resolved.default : resolved;
      record.mods[name] = resolved;
      record.components[name] = resolvedComponent;
    }));
    return promises;
  }, [])))).then(() => route);
}
function extractChangingRecords(to, from) {
  const leavingRecords = [];
  const updatingRecords = [];
  const enteringRecords = [];
  const len = Math.max(from.matched.length, to.matched.length);
  for (let i = 0; i < len; i++) {
    const recordFrom = from.matched[i];
    if (recordFrom) if (to.matched.find((record) => isSameRouteRecord(record, recordFrom))) updatingRecords.push(recordFrom);
    else leavingRecords.push(recordFrom);
    const recordTo = to.matched[i];
    if (recordTo) {
      if (!from.matched.find((record) => isSameRouteRecord(record, recordTo))) enteringRecords.push(recordTo);
    }
  }
  return [
    leavingRecords,
    updatingRecords,
    enteringRecords
  ];
}
function formatRouteLocation(routeLocation, tooltip) {
  const copy = assign({}, routeLocation, { matched: routeLocation.matched.map((matched) => omit(matched, [
    "instances",
    "children",
    "aliasOf"
  ])) });
  return { _custom: {
    type: null,
    readOnly: true,
    display: routeLocation.fullPath,
    tooltip,
    value: copy
  } };
}
function formatDisplay(display) {
  return { _custom: { display } };
}
let routerId = 0;
function addDevtools(app, router, matcher) {
  if (router.__hasDevtools) return;
  router.__hasDevtools = true;
  const id = routerId++;
  setupDevtoolsPlugin({
    id: "org.vuejs.router" + (id ? "." + id : ""),
    label: "Vue Router",
    packageName: "vue-router",
    homepage: "https://router.vuejs.org",
    logo: "https://router.vuejs.org/logo.png",
    componentStateTypes: ["Routing"],
    app
  }, (api) => {
    if (typeof api.now !== "function") warn$1("[Vue Router]: You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.");
    api.on.inspectComponent((payload, ctx) => {
      if (payload.instanceData) payload.instanceData.state.push({
        type: "Routing",
        key: "$route",
        editable: false,
        value: formatRouteLocation(router.currentRoute.value, "Current Route")
      });
    });
    api.on.visitComponentTree(({ treeNode: node, componentInstance }) => {
      if (componentInstance.__vrv_devtools) {
        const info = componentInstance.__vrv_devtools;
        node.tags.push({
          label: (info.name ? `${info.name.toString()}: ` : "") + info.path,
          textColor: 0,
          tooltip: "This component is rendered by &lt;router-view&gt;",
          backgroundColor: PINK_500
        });
      }
      if (isArray$1(componentInstance.__vrl_devtools)) {
        componentInstance.__devtoolsApi = api;
        componentInstance.__vrl_devtools.forEach((devtoolsData) => {
          let label = devtoolsData.route.path;
          let backgroundColor = ORANGE_400;
          let tooltip = "";
          let textColor = 0;
          if (devtoolsData.error) {
            label = devtoolsData.error;
            backgroundColor = RED_100;
            textColor = RED_700;
          } else if (devtoolsData.isExactActive) {
            backgroundColor = LIME_500;
            tooltip = "This is exactly active";
          } else if (devtoolsData.isActive) {
            backgroundColor = BLUE_600;
            tooltip = "This link is active";
          }
          node.tags.push({
            label,
            textColor,
            tooltip,
            backgroundColor
          });
        });
      }
    });
    watch(router.currentRoute, () => {
      refreshRoutesView();
      api.notifyComponentUpdate();
      api.sendInspectorTree(routerInspectorId);
      api.sendInspectorState(routerInspectorId);
    });
    const navigationsLayerId = "router:navigations:" + id;
    api.addTimelineLayer({
      id: navigationsLayerId,
      label: `Router${id ? " " + id : ""} Navigations`,
      color: 4237508
    });
    router.onError((error, to) => {
      api.addTimelineEvent({
        layerId: navigationsLayerId,
        event: {
          title: "Error during Navigation",
          subtitle: to.fullPath,
          logType: "error",
          time: api.now(),
          data: { error },
          groupId: to.meta.__navigationId
        }
      });
    });
    let navigationId = 0;
    router.beforeEach((to, from) => {
      const data = {
        guard: formatDisplay("beforeEach"),
        from: formatRouteLocation(from, "Current Location during this navigation"),
        to: formatRouteLocation(to, "Target location")
      };
      Object.defineProperty(to.meta, "__navigationId", { value: navigationId++ });
      api.addTimelineEvent({
        layerId: navigationsLayerId,
        event: {
          time: api.now(),
          title: "Start of navigation",
          subtitle: to.fullPath,
          data,
          groupId: to.meta.__navigationId
        }
      });
    });
    router.afterEach((to, from, failure) => {
      const data = { guard: formatDisplay("afterEach") };
      if (failure) {
        data.failure = { _custom: {
          type: Error,
          readOnly: true,
          display: failure ? failure.message : "",
          tooltip: "Navigation Failure",
          value: failure
        } };
        data.status = formatDisplay("❌");
      } else data.status = formatDisplay("✅");
      data.from = formatRouteLocation(from, "Current Location during this navigation");
      data.to = formatRouteLocation(to, "Target location");
      api.addTimelineEvent({
        layerId: navigationsLayerId,
        event: {
          title: "End of navigation",
          subtitle: to.fullPath,
          time: api.now(),
          data,
          logType: failure ? "warning" : "default",
          groupId: to.meta.__navigationId
        }
      });
    });
    const routerInspectorId = "router-inspector:" + id;
    api.addInspector({
      id: routerInspectorId,
      label: "Routes" + (id ? " " + id : ""),
      icon: "book",
      treeFilterPlaceholder: "Search routes"
    });
    function refreshRoutesView() {
      if (!activeRoutesPayload) return;
      const payload = activeRoutesPayload;
      let routes = matcher.getRoutes().filter((route) => !route.parent || !route.parent.record.components);
      routes.forEach(resetMatchStateOnRouteRecord);
      if (payload.filter) routes = routes.filter((route) => isRouteMatching(route, payload.filter.toLowerCase()));
      routes.forEach((route) => markRouteRecordActive(route, router.currentRoute.value));
      payload.rootNodes = routes.map(formatRouteRecordForInspector);
    }
    let activeRoutesPayload;
    api.on.getInspectorTree((payload) => {
      activeRoutesPayload = payload;
      if (payload.app === app && payload.inspectorId === routerInspectorId) refreshRoutesView();
    });
    api.on.getInspectorState((payload) => {
      if (payload.app === app && payload.inspectorId === routerInspectorId) {
        const route = matcher.getRoutes().find((route$1) => route$1.record.__vd_id === payload.nodeId);
        if (route) payload.state = { options: formatRouteRecordMatcherForStateInspector(route) };
      }
    });
    api.sendInspectorTree(routerInspectorId);
    api.sendInspectorState(routerInspectorId);
  });
}
function modifierForKey(key) {
  if (key.optional) return key.repeatable ? "*" : "?";
  else return key.repeatable ? "+" : "";
}
function formatRouteRecordMatcherForStateInspector(route) {
  const { record } = route;
  const fields = [{
    editable: false,
    key: "path",
    value: record.path
  }];
  if (record.name != null) fields.push({
    editable: false,
    key: "name",
    value: record.name
  });
  fields.push({
    editable: false,
    key: "regexp",
    value: route.re
  });
  if (route.keys.length) fields.push({
    editable: false,
    key: "keys",
    value: { _custom: {
      type: null,
      readOnly: true,
      display: route.keys.map((key) => `${key.name}${modifierForKey(key)}`).join(" "),
      tooltip: "Param keys",
      value: route.keys
    } }
  });
  if (record.redirect != null) fields.push({
    editable: false,
    key: "redirect",
    value: record.redirect
  });
  if (route.alias.length) fields.push({
    editable: false,
    key: "aliases",
    value: route.alias.map((alias) => alias.record.path)
  });
  if (Object.keys(route.record.meta).length) fields.push({
    editable: false,
    key: "meta",
    value: route.record.meta
  });
  fields.push({
    key: "score",
    editable: false,
    value: { _custom: {
      type: null,
      readOnly: true,
      display: route.score.map((score) => score.join(", ")).join(" | "),
      tooltip: "Score used to sort routes",
      value: route.score
    } }
  });
  return fields;
}
const PINK_500 = 15485081;
const BLUE_600 = 2450411;
const LIME_500 = 8702998;
const CYAN_400 = 2282478;
const ORANGE_400 = 16486972;
const DARK = 6710886;
const RED_100 = 16704226;
const RED_700 = 12131356;
function formatRouteRecordForInspector(route) {
  const tags = [];
  const { record } = route;
  if (record.name != null) tags.push({
    label: String(record.name),
    textColor: 0,
    backgroundColor: CYAN_400
  });
  if (record.aliasOf) tags.push({
    label: "alias",
    textColor: 0,
    backgroundColor: ORANGE_400
  });
  if (route.__vd_match) tags.push({
    label: "matches",
    textColor: 0,
    backgroundColor: PINK_500
  });
  if (route.__vd_exactActive) tags.push({
    label: "exact",
    textColor: 0,
    backgroundColor: LIME_500
  });
  if (route.__vd_active) tags.push({
    label: "active",
    textColor: 0,
    backgroundColor: BLUE_600
  });
  if (record.redirect) tags.push({
    label: typeof record.redirect === "string" ? `redirect: ${record.redirect}` : "redirects",
    textColor: 16777215,
    backgroundColor: DARK
  });
  let id = record.__vd_id;
  if (id == null) {
    id = String(routeRecordId++);
    record.__vd_id = id;
  }
  return {
    id,
    label: record.path,
    tags,
    children: route.children.map(formatRouteRecordForInspector)
  };
}
let routeRecordId = 0;
const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/;
function markRouteRecordActive(route, currentRoute) {
  const isExactActive = currentRoute.matched.length && isSameRouteRecord(currentRoute.matched[currentRoute.matched.length - 1], route.record);
  route.__vd_exactActive = route.__vd_active = isExactActive;
  if (!isExactActive) route.__vd_active = currentRoute.matched.some((match) => isSameRouteRecord(match, route.record));
  route.children.forEach((childRoute) => markRouteRecordActive(childRoute, currentRoute));
}
function resetMatchStateOnRouteRecord(route) {
  route.__vd_match = false;
  route.children.forEach(resetMatchStateOnRouteRecord);
}
function isRouteMatching(route, filter) {
  const found = String(route.re).match(EXTRACT_REGEXP_RE);
  route.__vd_match = false;
  if (!found || found.length < 3) return false;
  if (new RegExp(found[1].replace(/\$$/, ""), found[2]).test(filter)) {
    route.children.forEach((child) => isRouteMatching(child, filter));
    if (route.record.path !== "/" || filter === "/") {
      route.__vd_match = route.re.test(filter);
      return true;
    }
    return false;
  }
  const path = route.record.path.toLowerCase();
  const decodedPath = decode(path);
  if (!filter.startsWith("/") && (decodedPath.includes(filter) || path.includes(filter))) return true;
  if (decodedPath.startsWith(filter) || path.startsWith(filter)) return true;
  if (route.record.name && String(route.record.name).includes(filter)) return true;
  return route.children.some((child) => isRouteMatching(child, filter));
}
function omit(obj, keys) {
  const ret = {};
  for (const key in obj) if (!keys.includes(key)) ret[key] = obj[key];
  return ret;
}

/*!
 * vue-router v4.6.4
 * (c) 2025 Eduardo San Martin Morote
 * @license MIT
 */
let createBaseLocation = () => location.protocol + "//" + location.host;
function createCurrentLocation(base, location$1) {
  const { pathname, search, hash } = location$1;
  const hashPos = base.indexOf("#");
  if (hashPos > -1) {
    let slicePos = hash.includes(base.slice(hashPos)) ? base.slice(hashPos).length : 1;
    let pathFromHash = hash.slice(slicePos);
    if (pathFromHash[0] !== "/") pathFromHash = "/" + pathFromHash;
    return stripBase(pathFromHash, "");
  }
  return stripBase(pathname, base) + search + hash;
}
function useHistoryListeners(base, historyState, currentLocation, replace) {
  let listeners = [];
  let teardowns = [];
  let pauseState = null;
  const popStateHandler = ({ state }) => {
    const to = createCurrentLocation(base, location);
    const from = currentLocation.value;
    const fromState = historyState.value;
    let delta = 0;
    if (state) {
      currentLocation.value = to;
      historyState.value = state;
      if (pauseState && pauseState === from) {
        pauseState = null;
        return;
      }
      delta = fromState ? state.position - fromState.position : 0;
    } else replace(to);
    listeners.forEach((listener) => {
      listener(currentLocation.value, from, {
        delta,
        type: NavigationType.pop,
        direction: delta ? delta > 0 ? NavigationDirection.forward : NavigationDirection.back : NavigationDirection.unknown
      });
    });
  };
  function pauseListeners() {
    pauseState = currentLocation.value;
  }
  function listen(callback) {
    listeners.push(callback);
    const teardown = () => {
      const index = listeners.indexOf(callback);
      if (index > -1) listeners.splice(index, 1);
    };
    teardowns.push(teardown);
    return teardown;
  }
  function beforeUnloadListener() {
    if (document.visibilityState === "hidden") {
      const { history: history$1 } = window;
      if (!history$1.state) return;
      history$1.replaceState(assign({}, history$1.state, { scroll: computeScrollPosition() }), "");
    }
  }
  function destroy() {
    for (const teardown of teardowns) teardown();
    teardowns = [];
    window.removeEventListener("popstate", popStateHandler);
    window.removeEventListener("pagehide", beforeUnloadListener);
    document.removeEventListener("visibilitychange", beforeUnloadListener);
  }
  window.addEventListener("popstate", popStateHandler);
  window.addEventListener("pagehide", beforeUnloadListener);
  document.addEventListener("visibilitychange", beforeUnloadListener);
  return {
    pauseListeners,
    listen,
    destroy
  };
}
function buildState(back, current, forward, replaced = false, computeScroll = false) {
  return {
    back,
    current,
    forward,
    replaced,
    position: window.history.length,
    scroll: computeScroll ? computeScrollPosition() : null
  };
}
function useHistoryStateNavigation(base) {
  const { history: history$1, location: location$1 } = window;
  const currentLocation = { value: createCurrentLocation(base, location$1) };
  const historyState = { value: history$1.state };
  if (!historyState.value) changeLocation(currentLocation.value, {
    back: null,
    current: currentLocation.value,
    forward: null,
    position: history$1.length - 1,
    replaced: true,
    scroll: null
  }, true);
  function changeLocation(to, state, replace$1) {
    const hashIndex = base.indexOf("#");
    const url = hashIndex > -1 ? (location$1.host && document.querySelector("base") ? base : base.slice(hashIndex)) + to : createBaseLocation() + base + to;
    try {
      history$1[replace$1 ? "replaceState" : "pushState"](state, "", url);
      historyState.value = state;
    } catch (err) {
      if (false) warn$1("Error with push/replace State", err);
      else console.error(err);
      location$1[replace$1 ? "replace" : "assign"](url);
    }
  }
  function replace(to, data) {
    changeLocation(to, assign({}, history$1.state, buildState(historyState.value.back, to, historyState.value.forward, true), data, { position: historyState.value.position }), true);
    currentLocation.value = to;
  }
  function push(to, data) {
    const currentState = assign({}, historyState.value, history$1.state, {
      forward: to,
      scroll: computeScrollPosition()
    });
    if (false) warn$1("history.state seems to have been manually replaced without preserving the necessary values. Make sure to preserve existing history state if you are manually calling history.replaceState:\n\nhistory.replaceState(history.state, '', url)\n\nYou can find more information at https://router.vuejs.org/guide/migration/#Usage-of-history-state");
    changeLocation(currentState.current, currentState, true);
    changeLocation(to, assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data), false);
    currentLocation.value = to;
  }
  return {
    location: currentLocation,
    state: historyState,
    push,
    replace
  };
}
function createWebHistory(base) {
  base = normalizeBase(base);
  const historyNavigation = useHistoryStateNavigation(base);
  const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace);
  function go(delta, triggerListeners = true) {
    if (!triggerListeners) historyListeners.pauseListeners();
    history.go(delta);
  }
  const routerHistory = assign({
    location: "",
    base,
    go,
    createHref: createHref.bind(null, base)
  }, historyNavigation, historyListeners);
  Object.defineProperty(routerHistory, "location", {
    enumerable: true,
    get: () => historyNavigation.location.value
  });
  Object.defineProperty(routerHistory, "state", {
    enumerable: true,
    get: () => historyNavigation.state.value
  });
  return routerHistory;
}
function createMemoryHistory(base = "") {
  let listeners = [];
  let queue = [[START, {}]];
  let position = 0;
  base = normalizeBase(base);
  function setLocation(location$1, state = {}) {
    position++;
    if (position !== queue.length) queue.splice(position);
    queue.push([location$1, state]);
  }
  function triggerListeners(to, from, { direction, delta }) {
    const info = {
      direction,
      delta,
      type: NavigationType.pop
    };
    for (const callback of listeners) callback(to, from, info);
  }
  const routerHistory = {
    location: START,
    state: {},
    base,
    createHref: createHref.bind(null, base),
    replace(to, state) {
      queue.splice(position--, 1);
      setLocation(to, state);
    },
    push(to, state) {
      setLocation(to, state);
    },
    listen(callback) {
      listeners.push(callback);
      return () => {
        const index = listeners.indexOf(callback);
        if (index > -1) listeners.splice(index, 1);
      };
    },
    destroy() {
      listeners = [];
      queue = [[START, {}]];
      position = 0;
    },
    go(delta, shouldTrigger = true) {
      const from = this.location;
      const direction = delta < 0 ? NavigationDirection.back : NavigationDirection.forward;
      position = Math.max(0, Math.min(position + delta, queue.length - 1));
      if (shouldTrigger) triggerListeners(this.location, from, {
        direction,
        delta
      });
    }
  };
  Object.defineProperty(routerHistory, "location", {
    enumerable: true,
    get: () => queue[position][0]
  });
  Object.defineProperty(routerHistory, "state", {
    enumerable: true,
    get: () => queue[position][1]
  });
  return routerHistory;
}
function createWebHashHistory(base) {
  base = location.host ? base || location.pathname + location.search : "";
  if (!base.includes("#")) base += "#";
  if (false) warn$1(`A hash base must end with a "#":
"${base}" should be "${base.replace(/#.*$/, "#")}".`);
  return createWebHistory(base);
}
let TokenType = /* @__PURE__ */ (function(TokenType$1) {
  TokenType$1[TokenType$1["Static"] = 0] = "Static";
  TokenType$1[TokenType$1["Param"] = 1] = "Param";
  TokenType$1[TokenType$1["Group"] = 2] = "Group";
  return TokenType$1;
})({});
var TokenizerState = /* @__PURE__ */ (function(TokenizerState$1) {
  TokenizerState$1[TokenizerState$1["Static"] = 0] = "Static";
  TokenizerState$1[TokenizerState$1["Param"] = 1] = "Param";
  TokenizerState$1[TokenizerState$1["ParamRegExp"] = 2] = "ParamRegExp";
  TokenizerState$1[TokenizerState$1["ParamRegExpEnd"] = 3] = "ParamRegExpEnd";
  TokenizerState$1[TokenizerState$1["EscapeNext"] = 4] = "EscapeNext";
  return TokenizerState$1;
})(TokenizerState || {});
const ROOT_TOKEN = {
  type: TokenType.Static,
  value: ""
};
const VALID_PARAM_RE = /[a-zA-Z0-9_]/;
function tokenizePath(path) {
  if (!path) return [[]];
  if (path === "/") return [[ROOT_TOKEN]];
  if (!path.startsWith("/")) throw new Error(false ? `Route paths should start with a "/": "${path}" should be "/${path}".` : `Invalid path "${path}"`);
  function crash(message) {
    throw new Error(`ERR (${state})/"${buffer}": ${message}`);
  }
  let state = TokenizerState.Static;
  let previousState = state;
  const tokens = [];
  let segment;
  function finalizeSegment() {
    if (segment) tokens.push(segment);
    segment = [];
  }
  let i = 0;
  let char;
  let buffer = "";
  let customRe = "";
  function consumeBuffer() {
    if (!buffer) return;
    if (state === TokenizerState.Static) segment.push({
      type: TokenType.Static,
      value: buffer
    });
    else if (state === TokenizerState.Param || state === TokenizerState.ParamRegExp || state === TokenizerState.ParamRegExpEnd) {
      if (segment.length > 1 && (char === "*" || char === "+")) crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`);
      segment.push({
        type: TokenType.Param,
        value: buffer,
        regexp: customRe,
        repeatable: char === "*" || char === "+",
        optional: char === "*" || char === "?"
      });
    } else crash("Invalid state to consume buffer");
    buffer = "";
  }
  function addCharToBuffer() {
    buffer += char;
  }
  while (i < path.length) {
    char = path[i++];
    if (char === "\\" && state !== TokenizerState.ParamRegExp) {
      previousState = state;
      state = TokenizerState.EscapeNext;
      continue;
    }
    switch (state) {
      case TokenizerState.Static:
        if (char === "/") {
          if (buffer) consumeBuffer();
          finalizeSegment();
        } else if (char === ":") {
          consumeBuffer();
          state = TokenizerState.Param;
        } else addCharToBuffer();
        break;
      case TokenizerState.EscapeNext:
        addCharToBuffer();
        state = previousState;
        break;
      case TokenizerState.Param:
        if (char === "(") state = TokenizerState.ParamRegExp;
        else if (VALID_PARAM_RE.test(char)) addCharToBuffer();
        else {
          consumeBuffer();
          state = TokenizerState.Static;
          if (char !== "*" && char !== "?" && char !== "+") i--;
        }
        break;
      case TokenizerState.ParamRegExp:
        if (char === ")") if (customRe[customRe.length - 1] == "\\") customRe = customRe.slice(0, -1) + char;
        else state = TokenizerState.ParamRegExpEnd;
        else customRe += char;
        break;
      case TokenizerState.ParamRegExpEnd:
        consumeBuffer();
        state = TokenizerState.Static;
        if (char !== "*" && char !== "?" && char !== "+") i--;
        customRe = "";
        break;
      default:
        crash("Unknown state");
        break;
    }
  }
  if (state === TokenizerState.ParamRegExp) crash(`Unfinished custom RegExp for param "${buffer}"`);
  consumeBuffer();
  finalizeSegment();
  return tokens;
}
const BASE_PARAM_PATTERN = "[^/]+?";
const BASE_PATH_PARSER_OPTIONS = {
  sensitive: false,
  strict: false,
  start: true,
  end: true
};
var PathScore = /* @__PURE__ */ (function(PathScore$1) {
  PathScore$1[PathScore$1["_multiplier"] = 10] = "_multiplier";
  PathScore$1[PathScore$1["Root"] = 90] = "Root";
  PathScore$1[PathScore$1["Segment"] = 40] = "Segment";
  PathScore$1[PathScore$1["SubSegment"] = 30] = "SubSegment";
  PathScore$1[PathScore$1["Static"] = 40] = "Static";
  PathScore$1[PathScore$1["Dynamic"] = 20] = "Dynamic";
  PathScore$1[PathScore$1["BonusCustomRegExp"] = 10] = "BonusCustomRegExp";
  PathScore$1[PathScore$1["BonusWildcard"] = -50] = "BonusWildcard";
  PathScore$1[PathScore$1["BonusRepeatable"] = -20] = "BonusRepeatable";
  PathScore$1[PathScore$1["BonusOptional"] = -8] = "BonusOptional";
  PathScore$1[PathScore$1["BonusStrict"] = 0.7000000000000001] = "BonusStrict";
  PathScore$1[PathScore$1["BonusCaseSensitive"] = 0.25] = "BonusCaseSensitive";
  return PathScore$1;
})(PathScore || {});
const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g;
function tokensToParser(segments, extraOptions) {
  const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions);
  const score = [];
  let pattern = options.start ? "^" : "";
  const keys = [];
  for (const segment of segments) {
    const segmentScores = segment.length ? [] : [PathScore.Root];
    if (options.strict && !segment.length) pattern += "/";
    for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) {
      const token = segment[tokenIndex];
      let subSegmentScore = PathScore.Segment + (options.sensitive ? PathScore.BonusCaseSensitive : 0);
      if (token.type === TokenType.Static) {
        if (!tokenIndex) pattern += "/";
        pattern += token.value.replace(REGEX_CHARS_RE, "\\$&");
        subSegmentScore += PathScore.Static;
      } else if (token.type === TokenType.Param) {
        const { value, repeatable, optional, regexp } = token;
        keys.push({
          name: value,
          repeatable,
          optional
        });
        const re$1 = regexp ? regexp : BASE_PARAM_PATTERN;
        if (re$1 !== BASE_PARAM_PATTERN) {
          subSegmentScore += PathScore.BonusCustomRegExp;
          try {
            `${re$1}`;
          } catch (err) {
            throw new Error(`Invalid custom RegExp for param "${value}" (${re$1}): ` + err.message);
          }
        }
        let subPattern = repeatable ? `((?:${re$1})(?:/(?:${re$1}))*)` : `(${re$1})`;
        if (!tokenIndex) subPattern = optional && segment.length < 2 ? `(?:/${subPattern})` : "/" + subPattern;
        if (optional) subPattern += "?";
        pattern += subPattern;
        subSegmentScore += PathScore.Dynamic;
        if (optional) subSegmentScore += PathScore.BonusOptional;
        if (repeatable) subSegmentScore += PathScore.BonusRepeatable;
        if (re$1 === ".*") subSegmentScore += PathScore.BonusWildcard;
      }
      segmentScores.push(subSegmentScore);
    }
    score.push(segmentScores);
  }
  if (options.strict && options.end) {
    const i = score.length - 1;
    score[i][score[i].length - 1] += PathScore.BonusStrict;
  }
  if (!options.strict) pattern += "/?";
  if (options.end) pattern += "$";
  else if (options.strict && !pattern.endsWith("/")) pattern += "(?:/|$)";
  const re = new RegExp(pattern, options.sensitive ? "" : "i");
  function parse(path) {
    const match = path.match(re);
    const params = {};
    if (!match) return null;
    for (let i = 1; i < match.length; i++) {
      const value = match[i] || "";
      const key = keys[i - 1];
      params[key.name] = value && key.repeatable ? value.split("/") : value;
    }
    return params;
  }
  function stringify(params) {
    let path = "";
    let avoidDuplicatedSlash = false;
    for (const segment of segments) {
      if (!avoidDuplicatedSlash || !path.endsWith("/")) path += "/";
      avoidDuplicatedSlash = false;
      for (const token of segment) if (token.type === TokenType.Static) path += token.value;
      else if (token.type === TokenType.Param) {
        const { value, repeatable, optional } = token;
        const param = value in params ? params[value] : "";
        if (isArray$1(param) && !repeatable) throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`);
        const text = isArray$1(param) ? param.join("/") : param;
        if (!text) if (optional) {
          if (segment.length < 2) if (path.endsWith("/")) path = path.slice(0, -1);
          else avoidDuplicatedSlash = true;
        } else throw new Error(`Missing required param "${value}"`);
        path += text;
      }
    }
    return path || "/";
  }
  return {
    re,
    score,
    keys,
    parse,
    stringify
  };
}
function compareScoreArray(a, b) {
  let i = 0;
  while (i < a.length && i < b.length) {
    const diff = b[i] - a[i];
    if (diff) return diff;
    i++;
  }
  if (a.length < b.length) return a.length === 1 && a[0] === PathScore.Static + PathScore.Segment ? -1 : 1;
  else if (a.length > b.length) return b.length === 1 && b[0] === PathScore.Static + PathScore.Segment ? 1 : -1;
  return 0;
}
function comparePathParserScore(a, b) {
  let i = 0;
  const aScore = a.score;
  const bScore = b.score;
  while (i < aScore.length && i < bScore.length) {
    const comp = compareScoreArray(aScore[i], bScore[i]);
    if (comp) return comp;
    i++;
  }
  if (Math.abs(bScore.length - aScore.length) === 1) {
    if (isLastScoreNegative(aScore)) return 1;
    if (isLastScoreNegative(bScore)) return -1;
  }
  return bScore.length - aScore.length;
}
function isLastScoreNegative(score) {
  const last = score[score.length - 1];
  return score.length > 0 && last[last.length - 1] < 0;
}
const PATH_PARSER_OPTIONS_DEFAULTS = {
  strict: false,
  end: true,
  sensitive: false
};
function createRouteRecordMatcher(record, parent, options) {
  const parser = tokensToParser(tokenizePath(record.path), options);
  if (false) {
    const existingKeys = /* @__PURE__ */ new Set();
    for (const key of parser.keys) {
      if (existingKeys.has(key.name)) warn$1(`Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".`);
      existingKeys.add(key.name);
    }
  }
  const matcher = assign(parser, {
    record,
    parent,
    children: [],
    alias: []
  });
  if (parent) {
    if (!matcher.record.aliasOf === !parent.record.aliasOf) parent.children.push(matcher);
  }
  return matcher;
}
function createRouterMatcher(routes, globalOptions) {
  const matchers = [];
  const matcherMap = /* @__PURE__ */ new Map();
  globalOptions = mergeOptions(PATH_PARSER_OPTIONS_DEFAULTS, globalOptions);
  function getRecordMatcher(name) {
    return matcherMap.get(name);
  }
  function addRoute(record, parent, originalRecord) {
    const isRootAdd = !originalRecord;
    const mainNormalizedRecord = normalizeRouteRecord(record);
    if (false) checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent);
    mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record;
    const options = mergeOptions(globalOptions, record);
    const normalizedRecords = [mainNormalizedRecord];
    if ("alias" in record) {
      const aliases = typeof record.alias === "string" ? [record.alias] : record.alias;
      for (const alias of aliases) normalizedRecords.push(normalizeRouteRecord(assign({}, mainNormalizedRecord, {
        components: originalRecord ? originalRecord.record.components : mainNormalizedRecord.components,
        path: alias,
        aliasOf: originalRecord ? originalRecord.record : mainNormalizedRecord
      })));
    }
    let matcher;
    let originalMatcher;
    for (const normalizedRecord of normalizedRecords) {
      const { path } = normalizedRecord;
      if (parent && path[0] !== "/") {
        const parentPath = parent.record.path;
        const connectingSlash = parentPath[parentPath.length - 1] === "/" ? "" : "/";
        normalizedRecord.path = parent.record.path + (path && connectingSlash + path);
      }
      if (false) throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\nSee more at https://router.vuejs.org/guide/migration/#Removed-star-or-catch-all-routes.');
      matcher = createRouteRecordMatcher(normalizedRecord, parent, options);
      if (false) checkMissingParamsInAbsolutePath(matcher, parent);
      if (originalRecord) {
        originalRecord.alias.push(matcher);
        if (false) checkSameParams(originalRecord, matcher);
      } else {
        originalMatcher = originalMatcher || matcher;
        if (originalMatcher !== matcher) originalMatcher.alias.push(matcher);
        if (isRootAdd && record.name && !isAliasRecord(matcher)) {
          if (false) checkSameNameAsAncestor(record, parent);
          removeRoute(record.name);
        }
      }
      if (isMatchable(matcher)) insertMatcher(matcher);
      if (mainNormalizedRecord.children) {
        const children = mainNormalizedRecord.children;
        for (let i = 0; i < children.length; i++) addRoute(children[i], matcher, originalRecord && originalRecord.children[i]);
      }
      originalRecord = originalRecord || matcher;
    }
    return originalMatcher ? () => {
      removeRoute(originalMatcher);
    } : noop$1;
  }
  function removeRoute(matcherRef) {
    if (isRouteName(matcherRef)) {
      const matcher = matcherMap.get(matcherRef);
      if (matcher) {
        matcherMap.delete(matcherRef);
        matchers.splice(matchers.indexOf(matcher), 1);
        matcher.children.forEach(removeRoute);
        matcher.alias.forEach(removeRoute);
      }
    } else {
      const index = matchers.indexOf(matcherRef);
      if (index > -1) {
        matchers.splice(index, 1);
        if (matcherRef.record.name) matcherMap.delete(matcherRef.record.name);
        matcherRef.children.forEach(removeRoute);
        matcherRef.alias.forEach(removeRoute);
      }
    }
  }
  function getRoutes() {
    return matchers;
  }
  function insertMatcher(matcher) {
    const index = findInsertionIndex(matcher, matchers);
    matchers.splice(index, 0, matcher);
    if (matcher.record.name && !isAliasRecord(matcher)) matcherMap.set(matcher.record.name, matcher);
  }
  function resolve(location$1, currentLocation) {
    let matcher;
    let params = {};
    let path;
    let name;
    if ("name" in location$1 && location$1.name) {
      matcher = matcherMap.get(location$1.name);
      if (!matcher) throw createRouterError(ErrorTypes.MATCHER_NOT_FOUND, { location: location$1 });
      if (false) {
        const invalidParams = Object.keys(location$1.params || {}).filter((paramName) => !matcher.keys.find((k) => k.name === paramName));
        if (invalidParams.length) warn$1(`Discarded invalid param(s) "${invalidParams.join('", "')}" when navigating. See https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22 for more details.`);
      }
      name = matcher.record.name;
      params = assign(pickParams(currentLocation.params, matcher.keys.filter((k) => !k.optional).concat(matcher.parent ? matcher.parent.keys.filter((k) => k.optional) : []).map((k) => k.name)), location$1.params && pickParams(location$1.params, matcher.keys.map((k) => k.name)));
      path = matcher.stringify(params);
    } else if (location$1.path != null) {
      path = location$1.path;
      if (false) warn$1(`The Matcher cannot resolve relative paths but received "${path}". Unless you directly called \`matcher.resolve("${path}")\`, this is probably a bug in vue-router. Please open an issue at https://github.com/vuejs/router/issues/new/choose.`);
      matcher = matchers.find((m) => m.re.test(path));
      if (matcher) {
        params = matcher.parse(path);
        name = matcher.record.name;
      }
    } else {
      matcher = currentLocation.name ? matcherMap.get(currentLocation.name) : matchers.find((m) => m.re.test(currentLocation.path));
      if (!matcher) throw createRouterError(ErrorTypes.MATCHER_NOT_FOUND, {
        location: location$1,
        currentLocation
      });
      name = matcher.record.name;
      params = assign({}, currentLocation.params, location$1.params);
      path = matcher.stringify(params);
    }
    const matched = [];
    let parentMatcher = matcher;
    while (parentMatcher) {
      matched.unshift(parentMatcher.record);
      parentMatcher = parentMatcher.parent;
    }
    return {
      name,
      path,
      params,
      matched,
      meta: mergeMetaFields(matched)
    };
  }
  routes.forEach((route) => addRoute(route));
  function clearRoutes() {
    matchers.length = 0;
    matcherMap.clear();
  }
  return {
    addRoute,
    resolve,
    removeRoute,
    clearRoutes,
    getRoutes,
    getRecordMatcher
  };
}
function pickParams(params, keys) {
  const newParams = {};
  for (const key of keys) if (key in params) newParams[key] = params[key];
  return newParams;
}
function normalizeRouteRecord(record) {
  const normalized = {
    path: record.path,
    redirect: record.redirect,
    name: record.name,
    meta: record.meta || {},
    aliasOf: record.aliasOf,
    beforeEnter: record.beforeEnter,
    props: normalizeRecordProps(record),
    children: record.children || [],
    instances: {},
    leaveGuards: /* @__PURE__ */ new Set(),
    updateGuards: /* @__PURE__ */ new Set(),
    enterCallbacks: {},
    components: "components" in record ? record.components || null : record.component && { default: record.component }
  };
  Object.defineProperty(normalized, "mods", { value: {} });
  return normalized;
}
function normalizeRecordProps(record) {
  const propsObject = {};
  const props = record.props || false;
  if ("component" in record) propsObject.default = props;
  else for (const name in record.components) propsObject[name] = typeof props === "object" ? props[name] : props;
  return propsObject;
}
function isAliasRecord(record) {
  while (record) {
    if (record.record.aliasOf) return true;
    record = record.parent;
  }
  return false;
}
function mergeMetaFields(matched) {
  return matched.reduce((meta, record) => assign(meta, record.meta), {});
}
function isSameParam(a, b) {
  return a.name === b.name && a.optional === b.optional && a.repeatable === b.repeatable;
}
function checkSameParams(a, b) {
  for (const key of a.keys) if (!key.optional && !b.keys.find(isSameParam.bind(null, key))) return warn$1(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`);
  for (const key of b.keys) if (!key.optional && !a.keys.find(isSameParam.bind(null, key))) return warn$1(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`);
}
function checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent) {
  if (parent && parent.record.name && !mainNormalizedRecord.name && !mainNormalizedRecord.path) warn$1(`The route named "${String(parent.record.name)}" has a child without a name and an empty path. Using that name won't render the empty path child so you probably want to move the name to the child instead. If this is intentional, add a name to the child route to remove the warning.`);
}
function checkSameNameAsAncestor(record, parent) {
  for (let ancestor = parent; ancestor; ancestor = ancestor.parent) if (ancestor.record.name === record.name) throw new Error(`A route named "${String(record.name)}" has been added as a ${parent === ancestor ? "child" : "descendant"} of a route with the same name. Route names must be unique and a nested route cannot use the same name as an ancestor.`);
}
function checkMissingParamsInAbsolutePath(record, parent) {
  for (const key of parent.keys) if (!record.keys.find(isSameParam.bind(null, key))) return warn$1(`Absolute path "${record.record.path}" must have the exact same param named "${key.name}" as its parent "${parent.record.path}".`);
}
function findInsertionIndex(matcher, matchers) {
  let lower = 0;
  let upper = matchers.length;
  while (lower !== upper) {
    const mid = lower + upper >> 1;
    if (comparePathParserScore(matcher, matchers[mid]) < 0) upper = mid;
    else lower = mid + 1;
  }
  const insertionAncestor = getInsertionAncestor(matcher);
  if (insertionAncestor) {
    upper = matchers.lastIndexOf(insertionAncestor, upper - 1);
    if (false) warn$1(`Finding ancestor route "${insertionAncestor.record.path}" failed for "${matcher.record.path}"`);
  }
  return upper;
}
function getInsertionAncestor(matcher) {
  let ancestor = matcher;
  while (ancestor = ancestor.parent) if (isMatchable(ancestor) && comparePathParserScore(matcher, ancestor) === 0) return ancestor;
}
function isMatchable({ record }) {
  return !!(record.name || record.components && Object.keys(record.components).length || record.redirect);
}
function useLink(props) {
  const router = inject(routerKey);
  const currentRoute = inject(routeLocationKey);
  let hasPrevious = false;
  let previousTo = null;
  const route = computed(() => {
    const to = unref(props.to);
    if (false) {
      if (!isRouteLocation(to)) if (hasPrevious) warn$1(`Invalid value for prop "to" in useLink()
- to:`, to, `
- previous to:`, previousTo, `
- props:`, props);
      else warn$1(`Invalid value for prop "to" in useLink()
- to:`, to, `
- props:`, props);
      previousTo = to;
      hasPrevious = true;
    }
    return router.resolve(to);
  });
  const activeRecordIndex = computed(() => {
    const { matched } = route.value;
    const { length } = matched;
    const routeMatched = matched[length - 1];
    const currentMatched = currentRoute.matched;
    if (!routeMatched || !currentMatched.length) return -1;
    const index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched));
    if (index > -1) return index;
    const parentRecordPath = getOriginalPath(matched[length - 2]);
    return length > 1 && getOriginalPath(routeMatched) === parentRecordPath && currentMatched[currentMatched.length - 1].path !== parentRecordPath ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2])) : index;
  });
  const isActive = computed(() => activeRecordIndex.value > -1 && includesParams(currentRoute.params, route.value.params));
  const isExactActive = computed(() => activeRecordIndex.value > -1 && activeRecordIndex.value === currentRoute.matched.length - 1 && isSameRouteLocationParams(currentRoute.params, route.value.params));
  function navigate(e = {}) {
    if (guardEvent(e)) {
      const p = router[unref(props.replace) ? "replace" : "push"](unref(props.to)).catch(noop$1);
      if (props.viewTransition && typeof document !== "undefined" && "startViewTransition" in document) document.startViewTransition(() => p);
      return p;
    }
    return Promise.resolve();
  }
  if (isBrowser) {
    const instance = getCurrentInstance();
    if (instance) {
      const linkContextDevtools = {
        route: route.value,
        isActive: isActive.value,
        isExactActive: isExactActive.value,
        error: null
      };
      instance.__vrl_devtools = instance.__vrl_devtools || [];
      instance.__vrl_devtools.push(linkContextDevtools);
      watchEffect(() => {
        linkContextDevtools.route = route.value;
        linkContextDevtools.isActive = isActive.value;
        linkContextDevtools.isExactActive = isExactActive.value;
        linkContextDevtools.error = isRouteLocation(unref(props.to)) ? null : 'Invalid "to" value';
      }, { flush: "post" });
    }
  }
  return {
    route,
    href: computed(() => route.value.href),
    isActive,
    isExactActive,
    navigate
  };
}
function preferSingleVNode(vnodes) {
  return vnodes.length === 1 ? vnodes[0] : vnodes;
}
const RouterLinkImpl = /* @__PURE__ */ defineComponent({
  name: "RouterLink",
  compatConfig: { MODE: 3 },
  props: {
    to: {
      type: [String, Object],
      required: true
    },
    replace: Boolean,
    activeClass: String,
    exactActiveClass: String,
    custom: Boolean,
    ariaCurrentValue: {
      type: String,
      default: "page"
    },
    viewTransition: Boolean
  },
  useLink,
  setup(props, { slots }) {
    const link = reactive(useLink(props));
    const { options } = inject(routerKey);
    const elClass = computed(() => ({
      [getLinkClass(props.activeClass, options.linkActiveClass, "router-link-active")]: link.isActive,
      [getLinkClass(props.exactActiveClass, options.linkExactActiveClass, "router-link-exact-active")]: link.isExactActive
    }));
    return () => {
      const children = slots.default && preferSingleVNode(slots.default(link));
      return props.custom ? children : h("a", {
        "aria-current": link.isExactActive ? props.ariaCurrentValue : null,
        href: link.href,
        onClick: link.navigate,
        class: elClass.value
      }, children);
    };
  }
});
const RouterLink = RouterLinkImpl;
function guardEvent(e) {
  if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return;
  if (e.defaultPrevented) return;
  if (e.button !== void 0 && e.button !== 0) return;
  if (e.currentTarget && e.currentTarget.getAttribute) {
    const target = e.currentTarget.getAttribute("target");
    if (/\b_blank\b/i.test(target)) return;
  }
  if (e.preventDefault) e.preventDefault();
  return true;
}
function includesParams(outer, inner) {
  for (const key in inner) {
    const innerValue = inner[key];
    const outerValue = outer[key];
    if (typeof innerValue === "string") {
      if (innerValue !== outerValue) return false;
    } else if (!isArray$1(outerValue) || outerValue.length !== innerValue.length || innerValue.some((value, i) => value.valueOf() !== outerValue[i].valueOf())) return false;
  }
  return true;
}
function getOriginalPath(record) {
  return record ? record.aliasOf ? record.aliasOf.path : record.path : "";
}
const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null ? propClass : globalClass != null ? globalClass : defaultClass;
const RouterViewImpl = /* @__PURE__ */ defineComponent({
  name: "RouterView",
  inheritAttrs: false,
  props: {
    name: {
      type: String,
      default: "default"
    },
    route: Object
  },
  compatConfig: { MODE: 3 },
  setup(props, { attrs, slots }) {
    const injectedRoute = inject(routerViewLocationKey);
    const routeToDisplay = computed(() => props.route || injectedRoute.value);
    const injectedDepth = inject(viewDepthKey, 0);
    const depth = computed(() => {
      let initialDepth = unref(injectedDepth);
      const { matched } = routeToDisplay.value;
      let matchedRoute;
      while ((matchedRoute = matched[initialDepth]) && !matchedRoute.components) initialDepth++;
      return initialDepth;
    });
    const matchedRouteRef = computed(() => routeToDisplay.value.matched[depth.value]);
    provide(viewDepthKey, computed(() => depth.value + 1));
    provide(matchedRouteKey, matchedRouteRef);
    provide(routerViewLocationKey, routeToDisplay);
    const viewRef = ref();
    watch(() => [
      viewRef.value,
      matchedRouteRef.value,
      props.name
    ], ([instance, to, name], [oldInstance, from, oldName]) => {
      if (to) {
        to.instances[name] = instance;
        if (from && from !== to && instance && instance === oldInstance) {
          if (!to.leaveGuards.size) to.leaveGuards = from.leaveGuards;
          if (!to.updateGuards.size) to.updateGuards = from.updateGuards;
        }
      }
      if (instance && to && (!from || !isSameRouteRecord(to, from) || !oldInstance)) (to.enterCallbacks[name] || []).forEach((callback) => callback(instance));
    }, { flush: "post" });
    return () => {
      const route = routeToDisplay.value;
      const currentName = props.name;
      const matchedRoute = matchedRouteRef.value;
      const ViewComponent = matchedRoute && matchedRoute.components[currentName];
      if (!ViewComponent) return normalizeSlot(slots.default, {
        Component: ViewComponent,
        route
      });
      const routePropsOption = matchedRoute.props[currentName];
      const routeProps = routePropsOption ? routePropsOption === true ? route.params : typeof routePropsOption === "function" ? routePropsOption(route) : routePropsOption : null;
      const onVnodeUnmounted = (vnode) => {
        if (vnode.component.isUnmounted) matchedRoute.instances[currentName] = null;
      };
      const component = h(ViewComponent, assign({}, routeProps, attrs, {
        onVnodeUnmounted,
        ref: viewRef
      }));
      if (isBrowser && component.ref) {
        const info = {
          depth: depth.value,
          name: matchedRoute.name,
          path: matchedRoute.path,
          meta: matchedRoute.meta
        };
        (isArray$1(component.ref) ? component.ref.map((r) => r.i) : [component.ref.i]).forEach((instance) => {
          instance.__vrv_devtools = info;
        });
      }
      return normalizeSlot(slots.default, {
        Component: component,
        route
      }) || component;
    };
  }
});
function normalizeSlot(slot, data) {
  if (!slot) return null;
  const slotContent = slot(data);
  return slotContent.length === 1 ? slotContent[0] : slotContent;
}
const RouterView = RouterViewImpl;
function warnDeprecatedUsage() {
  const instance = getCurrentInstance();
  const parentName = instance.parent && instance.parent.type.name;
  const parentSubTreeType = instance.parent && instance.parent.subTree && instance.parent.subTree.type;
  if (parentName && (parentName === "KeepAlive" || parentName.includes("Transition")) && typeof parentSubTreeType === "object" && parentSubTreeType.name === "RouterView") {
    const comp = parentName === "KeepAlive" ? "keep-alive" : "transition";
    warn$1(`<router-view> can no longer be used directly inside <transition> or <keep-alive>.
Use slot props instead:

<router-view v-slot="{ Component }">
  <${comp}>
    <component :is="Component" />
  </${comp}>
</router-view>`);
  }
}
function createRouter(options) {
  const matcher = createRouterMatcher(options.routes, options);
  const parseQuery$1 = options.parseQuery || parseQuery;
  const stringifyQuery$1 = options.stringifyQuery || stringifyQuery;
  const routerHistory = options.history;
  if (false) throw new Error('Provide the "history" option when calling "createRouter()": https://router.vuejs.org/api/interfaces/RouterOptions.html#history');
  const beforeGuards = useCallbacks();
  const beforeResolveGuards = useCallbacks();
  const afterGuards = useCallbacks();
  const currentRoute = shallowRef(START_LOCATION_NORMALIZED);
  let pendingLocation = START_LOCATION_NORMALIZED;
  if (isBrowser && options.scrollBehavior && "scrollRestoration" in history) history.scrollRestoration = "manual";
  const normalizeParams = applyToParams.bind(null, (paramValue) => "" + paramValue);
  const encodeParams = applyToParams.bind(null, encodeParam);
  const decodeParams = applyToParams.bind(null, decode);
  function addRoute(parentOrRoute, route) {
    let parent;
    let record;
    if (isRouteName(parentOrRoute)) {
      parent = matcher.getRecordMatcher(parentOrRoute);
      if (false) warn$1(`Parent route "${String(parentOrRoute)}" not found when adding child route`, route);
      record = route;
    } else record = parentOrRoute;
    return matcher.addRoute(record, parent);
  }
  function removeRoute(name) {
    const recordMatcher = matcher.getRecordMatcher(name);
    if (recordMatcher) matcher.removeRoute(recordMatcher);
    else if (false) warn$1(`Cannot remove non-existent route "${String(name)}"`);
  }
  function getRoutes() {
    return matcher.getRoutes().map((routeMatcher) => routeMatcher.record);
  }
  function hasRoute(name) {
    return !!matcher.getRecordMatcher(name);
  }
  function resolve(rawLocation, currentLocation) {
    currentLocation = assign({}, currentLocation || currentRoute.value);
    if (typeof rawLocation === "string") {
      const locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path);
      const matchedRoute$1 = matcher.resolve({ path: locationNormalized.path }, currentLocation);
      const href$1 = routerHistory.createHref(locationNormalized.fullPath);
      if (false) {
        if (href$1.startsWith("//")) warn$1(`Location "${rawLocation}" resolved to "${href$1}". A resolved location cannot start with multiple slashes.`);
        else if (!matchedRoute$1.matched.length) warn$1(`No match found for location with path "${rawLocation}"`);
      }
      return assign(locationNormalized, matchedRoute$1, {
        params: decodeParams(matchedRoute$1.params),
        hash: decode(locationNormalized.hash),
        redirectedFrom: void 0,
        href: href$1
      });
    }
    if (false) {
      warn$1(`router.resolve() was passed an invalid location. This will fail in production.
- Location:`, rawLocation);
      return resolve({});
    }
    let matcherLocation;
    if (rawLocation.path != null) {
      if (false) warn$1(`Path "${rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`);
      matcherLocation = assign({}, rawLocation, { path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path });
    } else {
      const targetParams = assign({}, rawLocation.params);
      for (const key in targetParams) if (targetParams[key] == null) delete targetParams[key];
      matcherLocation = assign({}, rawLocation, { params: encodeParams(targetParams) });
      currentLocation.params = encodeParams(currentLocation.params);
    }
    const matchedRoute = matcher.resolve(matcherLocation, currentLocation);
    const hash = rawLocation.hash || "";
    if (false) warn$1(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`);
    matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params));
    const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, {
      hash: encodeHash(hash),
      path: matchedRoute.path
    }));
    const href = routerHistory.createHref(fullPath);
    if (false) {
      if (href.startsWith("//")) warn$1(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
      else if (!matchedRoute.matched.length) warn$1(`No match found for location with path "${rawLocation.path != null ? rawLocation.path : rawLocation}"`);
    }
    return assign({
      fullPath,
      hash,
      query: stringifyQuery$1 === stringifyQuery ? normalizeQuery(rawLocation.query) : rawLocation.query || {}
    }, matchedRoute, {
      redirectedFrom: void 0,
      href
    });
  }
  function locationAsObject(to) {
    return typeof to === "string" ? parseURL(parseQuery$1, to, currentRoute.value.path) : assign({}, to);
  }
  function checkCanceledNavigation(to, from) {
    if (pendingLocation !== to) return createRouterError(ErrorTypes.NAVIGATION_CANCELLED, {
      from,
      to
    });
  }
  function push(to) {
    return pushWithRedirect(to);
  }
  function replace(to) {
    return push(assign(locationAsObject(to), { replace: true }));
  }
  function handleRedirectRecord(to, from) {
    const lastMatched = to.matched[to.matched.length - 1];
    if (lastMatched && lastMatched.redirect) {
      const { redirect } = lastMatched;
      let newTargetLocation = typeof redirect === "function" ? redirect(to, from) : redirect;
      if (typeof newTargetLocation === "string") {
        newTargetLocation = newTargetLocation.includes("?") || newTargetLocation.includes("#") ? newTargetLocation = locationAsObject(newTargetLocation) : { path: newTargetLocation };
        newTargetLocation.params = {};
      }
      if (false) {
        warn$1(`Invalid redirect found:
${JSON.stringify(newTargetLocation, null, 2)}
 when navigating to "${to.fullPath}". A redirect must contain a name or path. This will break in production.`);
        throw new Error("Invalid redirect");
      }
      return assign({
        query: to.query,
        hash: to.hash,
        params: newTargetLocation.path != null ? {} : to.params
      }, newTargetLocation);
    }
  }
  function pushWithRedirect(to, redirectedFrom) {
    const targetLocation = pendingLocation = resolve(to);
    const from = currentRoute.value;
    const data = to.state;
    const force = to.force;
    const replace$1 = to.replace === true;
    const shouldRedirect = handleRedirectRecord(targetLocation, from);
    if (shouldRedirect) return pushWithRedirect(assign(locationAsObject(shouldRedirect), {
      state: typeof shouldRedirect === "object" ? assign({}, data, shouldRedirect.state) : data,
      force,
      replace: replace$1
    }), redirectedFrom || targetLocation);
    const toLocation = targetLocation;
    toLocation.redirectedFrom = redirectedFrom;
    let failure;
    if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) {
      failure = createRouterError(ErrorTypes.NAVIGATION_DUPLICATED, {
        to: toLocation,
        from
      });
      handleScroll(from, from, true, false);
    }
    return (failure ? Promise.resolve(failure) : navigate(toLocation, from)).catch((error) => isNavigationFailure(error) ? isNavigationFailure(error, ErrorTypes.NAVIGATION_GUARD_REDIRECT) ? error : markAsReady(error) : triggerError(error, toLocation, from)).then((failure$1) => {
      if (failure$1) {
        if (isNavigationFailure(failure$1, ErrorTypes.NAVIGATION_GUARD_REDIRECT)) {
          if (false) {
            warn$1(`Detected a possibly infinite redirection in a navigation guard when going from "${from.fullPath}" to "${toLocation.fullPath}". Aborting to avoid a Stack Overflow.
 Are you always returning a new location within a navigation guard? That would lead to this error. Only return when redirecting or aborting, that should fix this. This might break in production if not fixed.`);
            return Promise.reject(/* @__PURE__ */ new Error("Infinite redirect in navigation guard"));
          }
          return pushWithRedirect(assign({ replace: replace$1 }, locationAsObject(failure$1.to), {
            state: typeof failure$1.to === "object" ? assign({}, data, failure$1.to.state) : data,
            force
          }), redirectedFrom || toLocation);
        }
      } else failure$1 = finalizeNavigation(toLocation, from, true, replace$1, data);
      triggerAfterEach(toLocation, from, failure$1);
      return failure$1;
    });
  }
  function checkCanceledNavigationAndReject(to, from) {
    const error = checkCanceledNavigation(to, from);
    return error ? Promise.reject(error) : Promise.resolve();
  }
  function runWithContext(fn) {
    const app = installedApps.values().next().value;
    return app && typeof app.runWithContext === "function" ? app.runWithContext(fn) : fn();
  }
  function navigate(to, from) {
    let guards;
    const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from);
    guards = extractComponentsGuards(leavingRecords.reverse(), "beforeRouteLeave", to, from);
    for (const record of leavingRecords) record.leaveGuards.forEach((guard) => {
      guards.push(guardToPromiseFn(guard, to, from));
    });
    const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from);
    guards.push(canceledNavigationCheck);
    return runGuardQueue(guards).then(() => {
      guards = [];
      for (const guard of beforeGuards.list()) guards.push(guardToPromiseFn(guard, to, from));
      guards.push(canceledNavigationCheck);
      return runGuardQueue(guards);
    }).then(() => {
      guards = extractComponentsGuards(updatingRecords, "beforeRouteUpdate", to, from);
      for (const record of updatingRecords) record.updateGuards.forEach((guard) => {
        guards.push(guardToPromiseFn(guard, to, from));
      });
      guards.push(canceledNavigationCheck);
      return runGuardQueue(guards);
    }).then(() => {
      guards = [];
      for (const record of enteringRecords) if (record.beforeEnter) if (isArray$1(record.beforeEnter)) for (const beforeEnter of record.beforeEnter) guards.push(guardToPromiseFn(beforeEnter, to, from));
      else guards.push(guardToPromiseFn(record.beforeEnter, to, from));
      guards.push(canceledNavigationCheck);
      return runGuardQueue(guards);
    }).then(() => {
      to.matched.forEach((record) => record.enterCallbacks = {});
      guards = extractComponentsGuards(enteringRecords, "beforeRouteEnter", to, from, runWithContext);
      guards.push(canceledNavigationCheck);
      return runGuardQueue(guards);
    }).then(() => {
      guards = [];
      for (const guard of beforeResolveGuards.list()) guards.push(guardToPromiseFn(guard, to, from));
      guards.push(canceledNavigationCheck);
      return runGuardQueue(guards);
    }).catch((err) => isNavigationFailure(err, ErrorTypes.NAVIGATION_CANCELLED) ? err : Promise.reject(err));
  }
  function triggerAfterEach(to, from, failure) {
    afterGuards.list().forEach((guard) => runWithContext(() => guard(to, from, failure)));
  }
  function finalizeNavigation(toLocation, from, isPush, replace$1, data) {
    const error = checkCanceledNavigation(toLocation, from);
    if (error) return error;
    const isFirstNavigation = from === START_LOCATION_NORMALIZED;
    const state = !isBrowser ? {} : history.state;
    if (isPush) if (replace$1 || isFirstNavigation) routerHistory.replace(toLocation.fullPath, assign({ scroll: isFirstNavigation && state && state.scroll }, data));
    else routerHistory.push(toLocation.fullPath, data);
    currentRoute.value = toLocation;
    handleScroll(toLocation, from, isPush, isFirstNavigation);
    markAsReady();
  }
  let removeHistoryListener;
  function setupListeners() {
    if (removeHistoryListener) return;
    removeHistoryListener = routerHistory.listen((to, _from, info) => {
      if (!router.listening) return;
      const toLocation = resolve(to);
      const shouldRedirect = handleRedirectRecord(toLocation, router.currentRoute.value);
      if (shouldRedirect) {
        pushWithRedirect(assign(shouldRedirect, {
          replace: true,
          force: true
        }), toLocation).catch(noop$1);
        return;
      }
      pendingLocation = toLocation;
      const from = currentRoute.value;
      if (isBrowser) saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition());
      navigate(toLocation, from).catch((error) => {
        if (isNavigationFailure(error, ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_CANCELLED)) return error;
        if (isNavigationFailure(error, ErrorTypes.NAVIGATION_GUARD_REDIRECT)) {
          pushWithRedirect(assign(locationAsObject(error.to), { force: true }), toLocation).then((failure) => {
            if (isNavigationFailure(failure, ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_DUPLICATED) && !info.delta && info.type === NavigationType.pop) routerHistory.go(-1, false);
          }).catch(noop$1);
          return Promise.reject();
        }
        if (info.delta) routerHistory.go(-info.delta, false);
        return triggerError(error, toLocation, from);
      }).then((failure) => {
        failure = failure || finalizeNavigation(toLocation, from, false);
        if (failure) {
          if (info.delta && !isNavigationFailure(failure, ErrorTypes.NAVIGATION_CANCELLED)) routerHistory.go(-info.delta, false);
          else if (info.type === NavigationType.pop && isNavigationFailure(failure, ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_DUPLICATED)) routerHistory.go(-1, false);
        }
        triggerAfterEach(toLocation, from, failure);
      }).catch(noop$1);
    });
  }
  let readyHandlers = useCallbacks();
  let errorListeners = useCallbacks();
  let ready;
  function triggerError(error, to, from) {
    markAsReady(error);
    const list = errorListeners.list();
    if (list.length) list.forEach((handler) => handler(error, to, from));
    else {
      if (false) warn$1("uncaught error during route navigation:");
      console.error(error);
    }
    return Promise.reject(error);
  }
  function isReady() {
    if (ready && currentRoute.value !== START_LOCATION_NORMALIZED) return Promise.resolve();
    return new Promise((resolve$1, reject) => {
      readyHandlers.add([resolve$1, reject]);
    });
  }
  function markAsReady(err) {
    if (!ready) {
      ready = !err;
      setupListeners();
      readyHandlers.list().forEach(([resolve$1, reject]) => err ? reject(err) : resolve$1());
      readyHandlers.reset();
    }
    return err;
  }
  function handleScroll(to, from, isPush, isFirstNavigation) {
    const { scrollBehavior } = options;
    if (!isBrowser || !scrollBehavior) return Promise.resolve();
    const scrollPosition = !isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0)) || (isFirstNavigation || !isPush) && history.state && history.state.scroll || null;
    return nextTick().then(() => scrollBehavior(to, from, scrollPosition)).then((position) => position && scrollToPosition(position)).catch((err) => triggerError(err, to, from));
  }
  const go = (delta) => routerHistory.go(delta);
  let started;
  const installedApps = /* @__PURE__ */ new Set();
  const router = {
    currentRoute,
    listening: true,
    addRoute,
    removeRoute,
    clearRoutes: matcher.clearRoutes,
    hasRoute,
    getRoutes,
    resolve,
    options,
    push,
    replace,
    go,
    back: () => go(-1),
    forward: () => go(1),
    beforeEach: beforeGuards.add,
    beforeResolve: beforeResolveGuards.add,
    afterEach: afterGuards.add,
    onError: errorListeners.add,
    isReady,
    install(app) {
      app.component("RouterLink", RouterLink);
      app.component("RouterView", RouterView);
      app.config.globalProperties.$router = router;
      Object.defineProperty(app.config.globalProperties, "$route", {
        enumerable: true,
        get: () => unref(currentRoute)
      });
      if (isBrowser && !started && currentRoute.value === START_LOCATION_NORMALIZED) {
        started = true;
        push(routerHistory.location).catch((err) => {
          if (false) warn$1("Unexpected error when starting the router:", err);
        });
      }
      const reactiveRoute = {};
      for (const key in START_LOCATION_NORMALIZED) Object.defineProperty(reactiveRoute, key, {
        get: () => currentRoute.value[key],
        enumerable: true
      });
      app.provide(routerKey, router);
      app.provide(routeLocationKey, shallowReactive(reactiveRoute));
      app.provide(routerViewLocationKey, currentRoute);
      const unmountApp = app.unmount;
      installedApps.add(app);
      app.unmount = function() {
        installedApps.delete(app);
        if (installedApps.size < 1) {
          pendingLocation = START_LOCATION_NORMALIZED;
          removeHistoryListener && removeHistoryListener();
          removeHistoryListener = null;
          currentRoute.value = START_LOCATION_NORMALIZED;
          started = false;
          ready = false;
        }
        unmountApp();
      };
      if (isBrowser) addDevtools(app, router, matcher);
    }
  };
  function runGuardQueue(guards) {
    return guards.reduce((promise, guard) => promise.then(() => runWithContext(guard)), Promise.resolve());
  }
  return router;
}
function useRouter() {
  return inject(routerKey);
}
function useRoute(_name) {
  return inject(routeLocationKey);
}

const _sfc_main$26 = {
  __name: 'ActionSettingsWheelItem',
  props: {
  clickAction: Function,
  icon: String,
  label: String,
  detailValue: {
    type: [String, Number],
    default: "",
  },
  disabled: Boolean,
  testId: {
    type: String,
    default: "",
  },
  template: String // The style of the button (default, danger, success, warning, info, light)
},
  emits: ['selected'],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const props = __props;
const emit = __emit;

const styles = {
  default: {
    button: 'button is-small is-dark',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-black'
    },
    label: {
      color: 'has-text-black'
    },
  },
  danger: {
    button: 'button is-small is-danger',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-danger'
    },
    label: {
      color: 'has-text-danger'
    },
  },
  success: {
    button: 'button is-small is-success',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-success'
    },
    label: {
      color: 'has-text-success'
    },
  },
  warning: {
    button: 'button is-small is-warning',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-warning'
    },
    label: {
      color: 'has-text-warning'
    },
  },
  info: {
    button: 'button is-small is-info',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-info'
    },
    label: {
      color: 'has-text-info'
    },
  },
  light: {
    button: 'button is-small is-light',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-black'
    },
    label: {
      color: 'has-text-black'
    },
  },
};

const isProcessing = ref(false);
const click = async (event) => {
  if (isDisabled() || isProcessing.value) {
    return;
  }

  isProcessing.value = true;
  try {
    if (props.clickAction) {
      await props.clickAction();
    }
  } finally {
    isProcessing.value = false;
    emit('selected');
    event?.currentTarget?.dispatchEvent(new CustomEvent('dropdown-action-selected', { bubbles: true }));
  }
};

const isDisabled = () => {
  return props.disabled ?? false;
};

const getIcon = () => {
  return props.icon ?? 'fas fa-cog';
};

const getLabel = () => {
  return props.label ?? 'Unavngivet handling';
};

const hasDetailValue = () => {
  return props.detailValue !== undefined && props.detailValue !== null && String(props.detailValue).length > 0;
};

const getStyle = () => {
  return styles[props.template] ?? styles.default;
};

const getButtonClass = () => {
  return getStyle().button;
};

const getIconClass = () => {
  return getStyle().icon.icon;
};

const getIconColor = () => {
  return getStyle().icon.color;
};

const getLabelColor = () => {
  return getStyle().label.color;
};

const __returned__ = { props, emit, styles, isProcessing, click, isDisabled, getIcon, getLabel, hasDetailValue, getStyle, getButtonClass, getIconClass, getIconColor, getLabelColor, ref };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$16 = ["disabled", "data-testid"];
const _hoisted_2$W = { class: "icon" };
const _hoisted_3$P = {
  key: 0,
  class: "dropdown-item-action__detail"
};

function _sfc_render$1i(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("button", {
    type: "button",
    class: normalizeClass(["dropdown-item dropdown-item-action", {'is-disabled': $setup.isDisabled()}]),
    onClick: withModifiers($setup.click, ["stop","prevent"]),
    disabled: $setup.isDisabled(),
    "data-testid": $setup.props.testId || undefined
  }, [
    createBaseVNode("span", _hoisted_2$W, [
      createBaseVNode("i", {
        class: normalizeClass($setup.getIcon() + ' ' + $setup.getIconColor())
      }, null, 2 /* CLASS */)
    ]),
    createBaseVNode("span", {
      class: normalizeClass(["dropdown-item-action__label ml-1", $setup.getLabelColor()])
    }, toDisplayString($setup.getLabel()), 3 /* TEXT, CLASS */),
    ($setup.hasDetailValue())
      ? (openBlock(), createElementBlock("span", _hoisted_3$P, toDisplayString($setup.props.detailValue), 1 /* TEXT */))
      : createCommentVNode("v-if", true)
  ], 10 /* CLASS, PROPS */, _hoisted_1$16))
}
const ActionSettingsWheelItem = /*#__PURE__*/_export_sfc(_sfc_main$26, [['render',_sfc_render$1i],['__scopeId',"data-v-4d841bfb"],['__file',"ActionSettingsWheelItem.vue"]]);

const _sfc_main$25 = {
  __name: 'ActionSettingsWheelToggleItem',
  props: {
  checked: {
    type: Boolean,
    default: false,
  },
  clickAction: {
    type: Function,
    default: null,
  },
  description: {
    type: String,
    default: "",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  label: {
    type: String,
    default: "",
  },
  testId: {
    type: String,
    default: "",
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;

const isProcessing = ref(false);

const isDisabled = computed(() => props.disabled || isProcessing.value);
const title = computed(() => props.description || props.label);

const onClick = async () => {
  if (isDisabled.value || !props.clickAction) {
    return;
  }

  isProcessing.value = true;

  try {
    await props.clickAction();
  } finally {
    isProcessing.value = false;
  }
};

const __returned__ = { props, isProcessing, isDisabled, title, onClick, computed, ref };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$15 = ["aria-pressed", "data-testid", "disabled", "title"];
const _hoisted_2$V = { class: "action-settings-wheel-toggle-item__label" };

function _sfc_render$1h(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("button", {
    type: "button",
    class: normalizeClass(["dropdown-item dropdown-item-action action-settings-wheel-toggle-item", {
      'is-active': $props.checked,
      'is-disabled': $setup.isDisabled,
    }]),
    "aria-pressed": $props.checked ? 'true' : 'false',
    "data-testid": $props.testId || undefined,
    disabled: $setup.isDisabled,
    title: $setup.title,
    onClick: withModifiers($setup.onClick, ["stop","prevent"])
  }, [
    createBaseVNode("span", _hoisted_2$V, [
      renderSlot(_ctx.$slots, "label", { label: $props.label }, () => [
        createTextVNode(toDisplayString($props.label), 1 /* TEXT */)
      ], true)
    ]),
    createBaseVNode("span", {
      class: normalizeClass(["action-settings-wheel-toggle-item__switch", { 'is-checked': $props.checked }]),
      "aria-hidden": "true"
    }, [...(_cache[0] || (_cache[0] = [
      createBaseVNode("span", { class: "action-settings-wheel-toggle-item__knob" }, null, -1 /* CACHED */)
    ]))], 2 /* CLASS */)
  ], 10 /* CLASS, PROPS */, _hoisted_1$15))
}
const ActionSettingsWheelToggleItem = /*#__PURE__*/_export_sfc(_sfc_main$25, [['render',_sfc_render$1h],['__scopeId',"data-v-dfc6df5a"],['__file',"ActionSettingsWheelToggleItem.vue"]]);

const _sfc_main$24 = {
  __name: 'ActionSettingsWheelSelectItem',
  props: {
  changeAction: {
    type: Function,
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  icon: {
    type: String,
    default: "fas fa-cog",
  },
  label: {
    type: String,
    default: "",
  },
  options: {
    type: Array,
    default: () => [],
  },
  testId: {
    type: String,
    default: "",
  },
  value: {
    type: [String, Number, Boolean],
    default: "",
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;

const root = ref(null);
const normalizeSelectValue = (value) => String(value);
const localValue = ref(normalizeSelectValue(props.value));
const isProcessing = ref(false);

watch(
  () => props.value,
  (value) => {
    localValue.value = normalizeSelectValue(value);
  }
);

const isDisabled = computed(() => props.disabled || isProcessing.value);

const optionKey = (option) => `${typeof option?.value}:${normalizeSelectValue(option?.value)}`;
const getInputValue = (value) => value?.target?.value ?? value;

const onInput = async (value) => {
  const nextValue = normalizeSelectValue(getInputValue(value));

  if (isDisabled.value || nextValue === normalizeSelectValue(props.value)) {
    return;
  }

  isProcessing.value = true;
  try {
    if (props.changeAction) {
      await props.changeAction(nextValue);
    }
    root.value?.dispatchEvent(new CustomEvent("dropdown-action-selected", { bubbles: true }));
  } finally {
    isProcessing.value = false;
  }
};

const __returned__ = { props, root, normalizeSelectValue, localValue, isProcessing, isDisabled, optionKey, getInputValue, onInput, computed, ref, watch };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$14 = ["data-testid"];
const _hoisted_2$U = { class: "icon action-settings-wheel-select-item__icon" };
const _hoisted_3$O = { class: "action-settings-wheel-select-item__label" };
const _hoisted_4$M = ["value"];

function _sfc_render$1g(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_b_select = resolveComponent("b-select");

  return (openBlock(), createElementBlock("div", {
    ref: "root",
    class: normalizeClass(["dropdown-item action-settings-wheel-select-item", { 'is-disabled': $setup.isDisabled }]),
    "data-testid": $setup.props.testId || undefined
  }, [
    createBaseVNode("span", _hoisted_2$U, [
      createBaseVNode("i", {
        class: normalizeClass($setup.props.icon)
      }, null, 2 /* CLASS */)
    ]),
    createBaseVNode("span", _hoisted_3$O, toDisplayString($setup.props.label), 1 /* TEXT */),
    createVNode(_component_b_select, {
      modelValue: $setup.localValue,
      "onUpdate:modelValue": [
        _cache[0] || (_cache[0] = $event => (($setup.localValue) = $event)),
        $setup.onInput
      ],
      size: "is-small",
      disabled: $setup.isDisabled,
      "aria-label": $setup.props.label,
      "data-testid": $setup.props.testId ? `${$setup.props.testId}-select` : undefined,
      onClick: _cache[1] || (_cache[1] = withModifiers(() => {}, ["stop"])),
      onMousedown: _cache[2] || (_cache[2] = withModifiers(() => {}, ["stop"]))
    }, {
      default: withCtx(() => [
        (openBlock(true), createElementBlock(Fragment, null, renderList($setup.props.options, (option) => {
          return (openBlock(), createElementBlock("option", {
            key: $setup.optionKey(option),
            value: $setup.normalizeSelectValue(option.value)
          }, toDisplayString(option.label), 9 /* TEXT, PROPS */, _hoisted_4$M))
        }), 128 /* KEYED_FRAGMENT */))
      ]),
      _: 1 /* STABLE */
    }, 8 /* PROPS */, ["modelValue", "disabled", "aria-label", "data-testid"])
  ], 10 /* CLASS, PROPS */, _hoisted_1$14))
}
const ActionSettingsWheelSelectItem = /*#__PURE__*/_export_sfc(_sfc_main$24, [['render',_sfc_render$1g],['__scopeId',"data-v-5923074f"],['__file',"ActionSettingsWheelSelectItem.vue"]]);

const _sfc_main$23 = {
  __name: 'ElementTabsBox',
  props: {
  /**
   * The tabs to display
   * @example
   * [
   *  { name: 'Tab 1', slot: 'tab1', icon: 'fas fa-home' }
   *  { name: 'Tab 2', slot: 'tab2', icon: 'fas fa-user', hidden: true }
   *  { name: 'Tab 3', slot: 'tab3', hidden: () => { return false; } }
   *  ]
   */
  tabs: {
    type: Array,
    required: true,
    default: []
  },
  /**
   * The default active tab (slot name)
   * @example 'tab1'
   */
  defaultActiveTab: {
    type: String,
    required: true
  },
  /**
   * Allow the tabs to be compact when there is only one tab
   * @default false
   */
  allowCompactWhenOneTab: {
    type: Boolean,
    default: false
  },
  /**
   * Forcefully set the active tab
   * @default null
   * @type String
   */
  forceActiveTab: {
    type: String,
    default: null
  },
},
  emits: ['update:activeTab'],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const props = __props;

const slots = useSlots();
const emit = __emit;
const visibleTabs = ref([]);
/**
 * The active tab
 * The is by default the prop defaultActiveTab, but can be changed by the user and won't be emitted, as it is not a prop.
 */
const activeTab = ref(props.defaultActiveTab);

const isHidden = (tab) => {
  if (typeof tab.hidden === 'function') {
    return tab.hidden();
  }
  return !!tab.hidden;
};
/**
 * Update the visible tabs
 * This checks if the tab is hidden or not, and returns the visible tabs
 */
const updateVisibleTabs = () => {
  visibleTabs.value = props.tabs.filter((tab) => !isHidden(tab));
  // If the active tab is not visible, set the active tab to the first visible tab
  if (!visibleTabs.value.find((tab) => tab.slot === activeTab.value)) {
    activeTab.value = visibleTabs.value[0]?.slot ?? null;
  }
};
// Update the visible tabs every time the slot changes (If the tabs is a reactive object)
if (typeof props.tabs === 'object' && props.tabs.value !== undefined) {
  watch(props.tabs, () => {
    updateVisibleTabs();
  });
}

// Update the visible tabs when the component is mounted
onMounted(() => {
  updateVisibleTabs();
});

// Update the visible tabs when the current active tab changes "Hidden" status
watch(activeTab, () => {
  updateVisibleTabs();
});

const isTabVisible = (tab) => {
  const tmp_visible = !isHidden(tab);
  // If the tab is the current active tab, and the tab is not visible, set the active tab to the first visible tab
  if (tab.slot === activeTab.value && !tmp_visible) {
    activeTab.value = visibleTabs.value[0]?.slot ?? null;
  }
  return tmp_visible;
};

const onClickTab = (tab) => {
  // If the tab is not visible, do nothing
  if (!isTabVisible(tab)) {
    return;
  }
  // Set the active tab to the clicked tab
  if (props.forceActiveTab === null || props.forceActiveTab === undefined) {
    activeTab.value = tab;
  }
  // Emit the active tab
  emit('update:activeTab', tab);
};

// Watch the forceActiveTab prop and set the active tab to the forceActiveTab value
watch(() => props.forceActiveTab, (newValue) => {
  if (newValue !== null && newValue !== undefined) {
    activeTab.value = newValue;
  }
});

if (props.forceActiveTab !== null && props.forceActiveTab !== undefined) {
  activeTab.value = props.forceActiveTab;
}


const __returned__ = { props, slots, emit, visibleTabs, activeTab, isHidden, updateVisibleTabs, isTabVisible, onClickTab, onMounted, ref, watch };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$13 = {
  key: 0,
  class: "tabs is-centered is-fullwidth"
};
const _hoisted_2$T = ["onClick"];
const _hoisted_3$N = {
  key: 0,
  class: "icon is-small"
};

function _sfc_render$1f(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", null, [
    createCommentVNode(" Display the tabs, if there are more than one tab (and the compact mode is not allowed) "),
    ($setup.props.allowCompactWhenOneTab)
      ? (openBlock(), createElementBlock("div", _hoisted_1$13, [
          createBaseVNode("ul", null, [
            ($setup.props.tabs)
              ? (openBlock(true), createElementBlock(Fragment, { key: 0 }, renderList($setup.props.tabs, (tab, index) => {
                  return (openBlock(), createElementBlock(Fragment, { key: index }, [
                    ($setup.isTabVisible(tab))
                      ? (openBlock(), createElementBlock("li", {
                          key: 0,
                          class: normalizeClass({ 'is-active': tab.slot === $setup.activeTab })
                        }, [
                          createBaseVNode("a", {
                            onClick: $event => ($setup.onClickTab(tab.slot))
                          }, [
                            createCommentVNode(" Display the tab icon (if any) "),
                            (tab.icon)
                              ? (openBlock(), createElementBlock("span", _hoisted_3$N, [
                                  createBaseVNode("i", {
                                    class: normalizeClass(tab.icon)
                                  }, null, 2 /* CLASS */)
                                ]))
                              : createCommentVNode("v-if", true),
                            createCommentVNode(" Display the tab name "),
                            createBaseVNode("span", null, toDisplayString(tab.name), 1 /* TEXT */)
                          ], 8 /* PROPS */, _hoisted_2$T)
                        ], 2 /* CLASS */))
                      : createCommentVNode("v-if", true)
                  ], 64 /* STABLE_FRAGMENT */))
                }), 128 /* KEYED_FRAGMENT */))
              : createCommentVNode("v-if", true)
          ])
        ]))
      : createCommentVNode("v-if", true),
    createCommentVNode(" Display the content of the active tab "),
    createBaseVNode("div", null, [
      (openBlock(true), createElementBlock(Fragment, null, renderList($setup.props.tabs, (tab, index) => {
        return (openBlock(), createElementBlock(Fragment, { key: index }, [
          ($setup.slots[tab.slot] && tab.slot === $setup.activeTab)
            ? renderSlot(_ctx.$slots, tab.slot, { key: 0 })
            : createCommentVNode("v-if", true)
        ], 64 /* STABLE_FRAGMENT */))
      }), 128 /* KEYED_FRAGMENT */))
    ])
  ]))
}
const ElementTabsBox = /*#__PURE__*/_export_sfc(_sfc_main$23, [['render',_sfc_render$1f],['__file',"ElementTabsBox.vue"]]);

const _sfc_main$22 = {
  __name: 'InvoiceProcessorOverviewBox',
  props: {
  options: {
    type: Object,
    required: true,
  },
  count: {
    type: Object,
    required: true,
  },
  loading: {
    type: Boolean,
    required: true,
    default: false,
  },
  onClick: {
    type: Function|undefined,
    required: false,
    default: undefined,
  },
},
  emits: ['refresh'],
  setup(__props, { expose: __expose }) {
  __expose();

const default_options = {
  module: {
    name: SessionUser.objects.global.language.no_data,
    icon: 'fas fa-file-invoice-dollar',
    link: '#',
    color: 'has-text-grey',
  },
};

const default_count = {
  /**
   * @property {string} label - Label for the count
   * @property {number} value - Value of the count
   * @property {string} icon - Icon class for the count
   * @property {string} color - Color class for the count
   */
    label: 'Total',
    value: 0,
    icon: 'fas fa-file-invoice-dollar',
    color: 'has-text-info',
};

// Define props
const props = __props;

// Emit refresh event


// Has click action
const hasClickAction = () => {
  return props.onClick !== undefined;
};

// Define the click event
const click = () => {
  if (hasClickAction()) {
    props.onClick();
  }
};

const options = computed(() => ({
  ...default_options,
  ...props.options,
  module: {
    ...default_options.module,
    ...(props.options?.module || {}),
  },
}));

const getCounts = () => ({
    ...default_count,
    ...props.count,
  });

const getCountValue = () => {
  return unref(getCounts().value);
};


const __returned__ = { default_options, default_count, props, hasClickAction, click, options, getCounts, getCountValue, computed, unref, SessionUser };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$12 = { class: "card" };
const _hoisted_2$S = { class: "card-header" };
const _hoisted_3$M = { class: "card-header-title" };
const _hoisted_4$L = {
  class: "breadcrumb has-dot-separator",
  "aria-label": "breadcrumbs"
};
const _hoisted_5$I = ["href"];
const _hoisted_6$F = { class: "icon is-small" };
const _hoisted_7$D = { class: "is-hidden-mobile" };
const _hoisted_8$C = ["href"];
const _hoisted_9$A = { class: "is-hidden-mobile" };
const _hoisted_10$z = { class: "card-header-icon" };
const _hoisted_11$u = {
  key: 0,
  class: "icon is-small"
};
const _hoisted_12$s = { class: "icon is-small" };
const _hoisted_13$p = { class: "card-content" };
const _hoisted_14$n = { class: "content" };
const _hoisted_15$m = { class: "card-footer" };
const _hoisted_16$k = {
  key: 1,
  href: "#",
  class: "card-footer-item"
};

function _sfc_render$1e(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$12, [
    createBaseVNode("header", _hoisted_2$S, [
      createBaseVNode("div", _hoisted_3$M, [
        createBaseVNode("nav", _hoisted_4$L, [
          createBaseVNode("ul", null, [
            createBaseVNode("li", null, [
              createBaseVNode("a", {
                href: $setup.options.module.link,
                class: normalizeClass($setup.getCounts().color)
              }, [
                createBaseVNode("span", _hoisted_6$F, [
                  createBaseVNode("i", {
                    class: normalizeClass($setup.getCounts().icon)
                  }, null, 2 /* CLASS */)
                ]),
                createBaseVNode("span", _hoisted_7$D, toDisplayString($setup.getCounts().label), 1 /* TEXT */)
              ], 10 /* CLASS, PROPS */, _hoisted_5$I)
            ]),
            createBaseVNode("li", null, [
              createBaseVNode("a", {
                href: $setup.options.module.link,
                class: normalizeClass($setup.options.module.color)
              }, [
                createCommentVNode("<span class=\"icon is-small\">\n                  <i :class=\"options.module.icon\"></i>\n                </span>"),
                createBaseVNode("span", _hoisted_9$A, toDisplayString($setup.options.module.name), 1 /* TEXT */)
              ], 10 /* CLASS, PROPS */, _hoisted_8$C)
            ])
          ])
        ])
      ]),
      createBaseVNode("span", _hoisted_10$z, [
        createCommentVNode(" Loading spinner "),
        ($props.loading)
          ? (openBlock(), createElementBlock("span", _hoisted_11$u, [...(_cache[2] || (_cache[2] = [
              createBaseVNode("i", { class: "fas fa-spinner fa-spin" }, null, -1 /* CACHED */)
            ]))]))
          : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
              createCommentVNode(" Click to refresh icon "),
              createBaseVNode("span", _hoisted_12$s, [
                createBaseVNode("i", {
                  class: "fas fa-sync-alt",
                  onClick: _cache[0] || (_cache[0] = $event => (_ctx.$emit('refresh')))
                })
              ])
            ], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */))
      ])
    ]),
    createBaseVNode("div", _hoisted_13$p, [
      createBaseVNode("div", _hoisted_14$n, [
        createBaseVNode("p", {
          class: normalizeClass($setup.getCounts().color)
        }, [
          createBaseVNode("span", {
            class: normalizeClass($setup.getCounts().icon)
          }, null, 2 /* CLASS */),
          createTextVNode(" " + toDisplayString($setup.getCounts().label) + ": " + toDisplayString($setup.getCountValue()), 1 /* TEXT */)
        ], 2 /* CLASS */)
      ])
    ]),
    createBaseVNode("footer", _hoisted_15$m, [
      ($setup.hasClickAction())
        ? (openBlock(), createElementBlock("a", {
            key: 0,
            href: "#",
            class: "card-footer-item",
            onClick: _cache[1] || (_cache[1] = $event => ($setup.click()))
          }, " View "))
        : createCommentVNode("v-if", true),
      (!$setup.hasClickAction())
        ? (openBlock(), createElementBlock("a", _hoisted_16$k, toDisplayString($setup.SessionUser.objects.global.language.no_data), 1 /* TEXT */))
        : createCommentVNode("v-if", true)
    ])
  ]))
}
const InvoiceProcessorOverviewBox = /*#__PURE__*/_export_sfc(_sfc_main$22, [['render',_sfc_render$1e],['__file',"InvoiceProcessorOverviewBox.vue"]]);

const _sfc_main$21 = {
  __name: 'InvoicesOverviewEconomic',
  setup(__props, { expose: __expose }) {
  __expose();

const { t } = useI18n();

const errors = ref([]);

const getErrorMessage = (message) => {
  if (typeof message === "object" && Object.prototype.hasOwnProperty.call(message, "data")) {
    if (message?.data?.data?.message) {
      return message.data.data.message;
    }
    if (message?.statusText) {
      return message.statusText;
    }
    return t("invoices.economic.load_error");
  }
  return message;
};

const addErrorMessage = (message, httpStatusCode = null) => {
  errors.value.push({
    type: 'error',
    message: getErrorMessage(message),
    httpStatusCode: httpStatusCode,
  });
};

const removeErrorMessage = (index) => {
  errors.value.splice(index, 1);
};
const clearErrorMessages = () => {
  errors.value = [];
};
const hasErrorMessages = () => {
  return errors.value.length > 0;
};

// Define the dynamic data properties
const loading = ref(false);
const total = ref(0);
const paid = ref(0);
const unpaid = ref(0);
const overdue = ref(0);
const booked = ref(0);
const draft = ref(0);
const sent = ref(0);
const error = ref(0);

const refresh = async () => {
  loading.value = true;
  try {
    const response = await SessionUser.request(
      '/collected-invoices/economic/overview',
      'GET',
      {}
    );

    if (response.status === 200) {
      const result = response.data.data;
      total.value = result.total;
      paid.value = result.paid;
      unpaid.value = result.unpaid;
      overdue.value = result.overdue;
      booked.value = result.booked;
      draft.value = result.draft;
      sent.value = result.sent;
      error.value = result.error;
    } else {
      addErrorMessage(response, response.status);
    }
  } catch (requestError) {
    if (requestError?.response) {
      addErrorMessage(requestError.response, requestError.response.status);
    } else {
      addErrorMessage(t('invoices.economic.load_error'));
    }
  } finally {
    loading.value = false;
  }
};

const options = ref({
  module: {
    name: 'Economic',
    icon: 'fas fa-file-invoice-dollar',
    color: 'has-text-grey',
  },
  actions: [
    {
      label: t('invoices.economic.update_draft_status'),
      icon: 'fas fa-sync-alt',
      action: async () => {
        try {
          await SessionUser.objects.collectedOrderInvoices.functions.economic.runCheckDrafts();
          await refresh();
        } catch (requestError) {
          addErrorMessage(requestError);
        }
      },
      disabled: false,
    },
    {
      label: t('invoices.economic.check_errors'),
      icon: 'fas fa-sync-alt',
      action: async () => {
        try {
          await SessionUser.objects.collectedOrderInvoices.functions.economic.runCheckErrors();
          await refresh();
        } catch (requestError) {
          addErrorMessage(requestError);
        }
      },
      disabled: false,
    },
  ],
});

const counts = computed(() => ({
  total: {
    label: t('invoices.economic.total'),
    value: total.value,
    icon: 'fas fa-file-invoice-dollar',
    color: 'has-text-grey',
  },
  /**
  paid: {
    label: 'Betalt',
    value: paid,
    icon: 'fas fa-check-circle',
    color: 'has-text-grey-darker',
  },
  unpaid: {
    label: 'Ikke betalt',
    value: unpaid,
    icon: 'fas fa-times-circle',
    color: 'has-text-danger',
  },
  overdue: {
    label: 'Forsinket',
    value: overdue,
    icon: 'fas fa-clock',
    color: 'has-text-warning',
  },
  */
  booked: {
    label: t('invoices.economic.booked'),
    value: booked.value,
    icon: 'fas fa-book',
    color: 'has-text-success',
  },
  unbooked: {
    label: t('invoices.economic.draft'),
    value: draft.value,
    icon: 'fas fa-file-invoice',
    color: 'has-text-warning',
  },
  /**
  sent: {
    label: 'Sendt',
    value: sent,
    icon: 'fas fa-paper-plane',
    color: 'has-text-grey-dark',
  },
  */
  error: {
    label: t('common.error'),
    value: error.value,
    icon: 'fas fa-exclamation-triangle',
    color: 'has-text-danger',
  },
}));

// Fetch data on mounted
refresh();

const __returned__ = { t, errors, getErrorMessage, addErrorMessage, removeErrorMessage, clearErrorMessages, hasErrorMessages, loading, total, paid, unpaid, overdue, booked, draft, sent, error, refresh, options, counts, computed, ref, InvoiceProcessorOverviewBox, SessionUser, get useI18n() { return useI18n } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$11 = { class: "columns is-multiline is-mobile" };
const _hoisted_2$R = { class: "column is-full" };
const _hoisted_3$L = { class: "card" };
const _hoisted_4$K = { class: "card-header" };
const _hoisted_5$H = { class: "card-header-title" };
const _hoisted_6$E = { class: "card-content" };
const _hoisted_7$C = { class: "buttons" };
const _hoisted_8$B = ["onClick", "disabled"];
const _hoisted_9$z = { class: "icon" };
const _hoisted_10$y = {
  key: 0,
  class: "column is-full"
};
const _hoisted_11$t = { key: 0 };
const _hoisted_12$r = ["onClick"];

function _sfc_render$1d(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock(Fragment, null, [
    createBaseVNode("div", _hoisted_1$11, [
      createCommentVNode(" Display the available actions "),
      createBaseVNode("div", _hoisted_2$R, [
        createBaseVNode("div", _hoisted_3$L, [
          createBaseVNode("div", _hoisted_4$K, [
            _cache[0] || (_cache[0] = createBaseVNode("div", { class: "card-header-icon" }, [
              createBaseVNode("span", { class: "icon" }, [
                createBaseVNode("i", { class: "fas fa-cogs" })
              ])
            ], -1 /* CACHED */)),
            createBaseVNode("p", _hoisted_5$H, toDisplayString(_ctx.$t('common.actions')), 1 /* TEXT */)
          ]),
          createCommentVNode(" Display the available action buttons "),
          createBaseVNode("div", _hoisted_6$E, [
            createBaseVNode("div", _hoisted_7$C, [
              (openBlock(true), createElementBlock(Fragment, null, renderList($setup.options.actions, (action, index) => {
                return (openBlock(), createElementBlock("button", {
                  key: index,
                  class: "button is-dark is-outlined",
                  onClick: $event => (action.action()),
                  disabled: action.disabled
                }, [
                  createBaseVNode("span", _hoisted_9$z, [
                    createBaseVNode("i", {
                      class: normalizeClass(action.icon)
                    }, null, 2 /* CLASS */)
                  ]),
                  createBaseVNode("span", null, toDisplayString(action.label), 1 /* TEXT */)
                ], 8 /* PROPS */, _hoisted_8$B))
              }), 128 /* KEYED_FRAGMENT */))
            ])
          ])
        ])
      ]),
      createCommentVNode(" Display error messages if any "),
      ($setup.hasErrorMessages())
        ? (openBlock(), createElementBlock("div", _hoisted_10$y, [
            (openBlock(true), createElementBlock(Fragment, null, renderList($setup.errors, (error, index) => {
              return (openBlock(), createElementBlock("div", {
                key: index,
                class: "notification is-danger"
              }, [
                createCommentVNode(" Display the error code if available "),
                (error.httpStatusCode)
                  ? (openBlock(), createElementBlock("strong", _hoisted_11$t, "Error " + toDisplayString(error.httpStatusCode) + ":", 1 /* TEXT */))
                  : createCommentVNode("v-if", true),
                createCommentVNode(" Display the error message "),
                createTextVNode(" " + toDisplayString(error.message) + " ", 1 /* TEXT */),
                createBaseVNode("button", {
                  class: "delete",
                  onClick: $event => ($setup.removeErrorMessage(index))
                }, null, 8 /* PROPS */, _hoisted_12$r)
              ]))
            }), 128 /* KEYED_FRAGMENT */))
          ]))
        : createCommentVNode("v-if", true),
      createCommentVNode(" Display the overview boxes "),
      (openBlock(true), createElementBlock(Fragment, null, renderList($setup.counts, (count, countKey) => {
        return (openBlock(), createElementBlock("div", {
          key: countKey,
          class: "column is-3-desktop"
        }, [
          createVNode($setup["InvoiceProcessorOverviewBox"], {
            options: $setup.options,
            count: count,
            loading: $setup.loading,
            onRefresh: $setup.refresh
          }, null, 8 /* PROPS */, ["options", "count", "loading"])
        ]))
      }), 128 /* KEYED_FRAGMENT */))
    ]),
    createCommentVNode(" Other content can be added here ")
  ], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */))
}
const InvoicesOverviewEconomic = /*#__PURE__*/_export_sfc(_sfc_main$21, [['render',_sfc_render$1d],['__file',"InvoicesOverviewEconomic.vue"]]);

const _sfc_main$20 = {
  __name: 'CollectedOrderInvoicesOverview',
  setup(__props, { expose: __expose }) {
  __expose();


const __returned__ = { ref, InvoicesOverviewEconomic };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

function _sfc_render$1c(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock(Fragment, null, [
    createCommentVNode(" Invoice processing overview "),
    createVNode($setup["InvoicesOverviewEconomic"]),
    createCommentVNode(" Recently added invoices ")
  ], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */))
}
const CollectedOrderInvoicesOverview = /*#__PURE__*/_export_sfc(_sfc_main$20, [['render',_sfc_render$1c],['__file',"CollectedOrderInvoicesOverview.vue"]]);

const getScans$1 = () => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.get(API_URL + '/numberplatescans', {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const getScansDepartmentPagination = (department_id, page, limit) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.post(API_URL + '/numberplatescans/department', {
    department_id,
    page,
    limit
  }, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const createScan = (scanner_api_key, numberplate) => {
  if (!scanner_api_key) {
    return null;
  }
  return axios.post(API_URL + '/numberplatescans', {
    plate: numberplate
  }
  , {
    headers: {
      Authorization: `Bearer ${scanner_api_key}`
    }
  });
};

const _sfc_main$1$ = {};
const Scans = /*#__PURE__*/_export_sfc(_sfc_main$1$, [['__file',"Scans.vue"]]);

const getNotes = (customer_number) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.get(API_URL + '/customer/notes?customer_number=' + customer_number, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const createNote = (customer_number, note) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.post(API_URL + '/customer/notes', {
    customer_number,
    note
  }, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const deleteNote = (id) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.delete(API_URL + '/customer/notes?id=' + id, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const _sfc_main$1_ = {};
const CustomerNotes = /*#__PURE__*/_export_sfc(_sfc_main$1_, [['__file',"CustomerNotes.vue"]]);

const getOrderItems = (order_id) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.get(API_URL + '/order/items?order_id=' + order_id, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const createOrderItem = (order_id, product_id, quantity, related_item_id = null, notes = null, forcePrice = null) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  const normalizedOrderId = Number(order_id);
  if (!Number.isInteger(normalizedOrderId) || normalizedOrderId <= 0) {
    return Promise.reject(new Error('Order ID is required'));
  }
  const payload = {
    order_id: normalizedOrderId,
    product_id,
    quantity,
    related_item_id,
    notes
  };
  if (forcePrice !== null && forcePrice !== undefined) {
    payload.price = forcePrice;
  }
  return axios.post(API_URL + '/order/items', payload, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const removeOrderItem = (id) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.delete(API_URL + '/order/items?id=' + id, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const editOrderItem = (id, price, notes, reference, quantity) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.put(API_URL + '/order/items', {
    id,
    price,
    notes,
    reference,
    quantity
  }, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const _sfc_main$1Z = {};
const OrdersItems = /*#__PURE__*/_export_sfc(_sfc_main$1Z, [['__file',"OrdersItems.vue"]]);

const getAuthHeaders = () => {
  const token = window.localStorage.getItem("token");
  if (!token) {
    return null;
  }

  return {
    Authorization: `Bearer ${token}`,
  };
};

const normalizePositiveInteger$3 = (value) => {
  const parsed = Number.parseInt(String(value ?? ""), 10);
  return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
};

const normalizeCustomerAttributeTarget = (target = {}) => {
  const userId = normalizePositiveInteger$3(target.userId ?? target.user_id);
  const customerNumber = normalizePositiveInteger$3(target.customerNumber ?? target.customer_number);

  return {
    userId,
    customerNumber,
  };
};

const hasCustomerAttributeTarget = (target = {}) => {
  const normalizedTarget = normalizeCustomerAttributeTarget(target);
  return Boolean(normalizedTarget.userId || normalizedTarget.customerNumber);
};

const buildCustomerAttributeTargetPayload = (target = {}) => {
  const normalizedTarget = normalizeCustomerAttributeTarget(target);
  if (normalizedTarget.userId) {
    return {
      user_id: normalizedTarget.userId,
    };
  }

  if (normalizedTarget.customerNumber) {
    return {
      customer_number: normalizedTarget.customerNumber,
    };
  }

  return {};
};

const extractCustomerAttributesData = (response) => {
  if (Array.isArray(response?.data?.data)) {
    return response.data.data;
  }

  if (Array.isArray(response?.data)) {
    return response.data;
  }

  if (Array.isArray(response)) {
    return response;
  }

  return [];
};

const listCustomerAttributes = (target = {}) => {
  const headers = getAuthHeaders();
  if (!headers || !hasCustomerAttributeTarget(target)) {
    return null;
  }

  return axios.get(`${API_URL}/customer/attributes`, {
    params: buildCustomerAttributeTargetPayload(target),
    headers,
  });
};

const createCustomerAttribute = (target = {}, attribute) => {
  const headers = getAuthHeaders();
  if (!headers || !hasCustomerAttributeTarget(target) || !attribute) {
    return null;
  }

  return axios.post(
    `${API_URL}/customer/attributes`,
    {
      ...buildCustomerAttributeTargetPayload(target),
      attribute,
    },
    {
      headers,
    }
  );
};

const deleteCustomerAttribute = (target = {}, attribute) => {
  const headers = getAuthHeaders();
  if (!headers || !hasCustomerAttributeTarget(target) || !attribute) {
    return null;
  }

  return axios.delete(`${API_URL}/customer/attributes`, {
    params: {
      ...buildCustomerAttributeTargetPayload(target),
      attribute,
    },
    headers,
  });
};

const getAttributes = (customer_number) => {
  return listCustomerAttributes({ customerNumber: customer_number });
};

const isAttributesLoading = ref(false);

const createAttribute = (customer_number, attribute) => {
  // If the loading state is true, return null
  if (isAttributesLoading.value) {
    return null;
  }
  // Set the loading state to true
  isAttributesLoading.value = true;
  return createCustomerAttribute({ customerNumber: customer_number }, attribute).then(
    () => {
      isAttributesLoading.value = false;
    }
  ).catch(
    () => {
      isAttributesLoading.value = false;
    }
  );
};

const deleteAttribute = (customer_number, attribute) => {
  // If the loading state is true, return null
  if (isAttributesLoading.value) {
    return null;
  }
  // Set the loading state to true
  isAttributesLoading.value = true;
  return deleteCustomerAttribute({ customerNumber: customer_number }, attribute).then(
    () => {
      isAttributesLoading.value = false;
    }
  ).catch(
    () => {
      isAttributesLoading.value = false;
    }
  );
};

const _sfc_main$1Y = {};
const CustomerAttributes = /*#__PURE__*/_export_sfc(_sfc_main$1Y, [['__file',"CustomerAttributes.vue"]]);

const WASH_CERTIFICATE_PRODUCT_ID = 41;

const LEGACY_WASH_CERTIFICATE_NAME_PATTERN = /vaskecertifikat|wash certificate|safety seal/i;

const toInteger = (value) => {
  const parsed = Number.parseInt(String(value ?? ""), 10);
  return Number.isInteger(parsed) ? parsed : null;
};

const getCandidateName = (candidate) => {
  return String(candidate?.product?.name ?? candidate?.name ?? candidate?.product_name ?? "").trim();
};

const hasActiveQuantity = (candidate) => {
  const quantity = Number(candidate?.quantity ?? candidate?.product?.quantity ?? 1);
  return Number.isFinite(quantity) ? quantity > 0 : false;
};

const hasActiveAddonQuantity = (candidate) => {
  const quantity = Number(candidate?.quantity ?? candidate?.product?.quantity ?? 0);
  return Number.isFinite(quantity) ? quantity > 0 : false;
};

const isWashCertificateProduct = (candidate) => {
  const candidateId = toInteger(candidate?.product?.id ?? candidate?.product_id ?? candidate?.id ?? candidate);
  if (candidateId === WASH_CERTIFICATE_PRODUCT_ID) {
    return true;
  }

  // Keep older mocked data and stale catalog entries functional while the UI
  // standardizes on product 41 as the canonical wash-certificate item.
  return LEGACY_WASH_CERTIFICATE_NAME_PATTERN.test(getCandidateName(candidate));
};

const doesOrderContainWashCertificateProduct = (items = []) => {
  return Array.isArray(items) && items.some((item) => hasActiveQuantity(item) && isWashCertificateProduct(item));
};

const containsWashCertificateAddon = (addons = []) => {
  return Array.isArray(addons) && addons.some((addon) => hasActiveAddonQuantity(addon) && isWashCertificateProduct(addon));
};

const doesTransactionContainWashCertificateProduct = ({
  primaryItem = null,
  additionalItems = [],
} = {}) => {
  if (primaryItem && containsWashCertificateAddon(primaryItem.addons)) {
    return true;
  }

  for (const item of Array.isArray(additionalItems) ? additionalItems : []) {
    if (hasActiveQuantity(item) && isWashCertificateProduct(item)) {
      return true;
    }

    if (containsWashCertificateAddon(item?.addons)) {
      return true;
    }
  }
  return false;
};

const ADDON_CATEGORY_ID = 4;
const STANDALONE_ADDITIONAL_SERVICE_CATEGORY_ID = 8;
const TANK_CLEANING_TERMS = ["tank cleaning", "tankcleaning", "tankrens", "tank rens"];
const ADDITIONAL_SERVICE_TERMS = ["add-on", "add on", "addon", "tilvalg"];
const SPOT_FREE_PRODUCT_IDS = [23, 24];
const SPOT_FREE_TERMS = ["spot free", "spotfree", "skylning med ro"];

const CUSTOMER_PRODUCT_RULE_MESSAGE_KEYS = {
  restrictAdditionalServices: "pos.restrictions.addons_not_allowed",
  restrictSpotFree: "pos.restrictions.product_not_allowed",
  restrictInteriorCleaning: "pos.restrictions.product_not_allowed",
  restrictTankCleaning: "pos.restrictions.product_not_allowed",
  onlyTankCleaning: "pos.restrictions.product_not_allowed",
};

const allowedRestriction = () => ({
  restricted: false,
  rule: null,
  messageKey: null,
});

const restrictedByRule = (rule) => ({
  restricted: true,
  rule,
  messageKey: CUSTOMER_PRODUCT_RULE_MESSAGE_KEYS[rule] ?? "pos.restrictions.product_not_allowed",
});

const normalizeAttributeName = (attribute) => {
  if (typeof attribute === "string") {
    return attribute;
  }

  return String(attribute?.attribute ?? "");
};

const hasCustomerAttribute = (attributes, attributeName) => {
  if (!Array.isArray(attributes)) {
    return false;
  }

  return attributes.some((attribute) => normalizeAttributeName(attribute) === attributeName);
};

const normalizedText = (value) => String(value ?? "").trim().toLowerCase();

const textContainsAny = (value, terms) => {
  const text = normalizedText(value);
  return terms.some((term) => term !== "" && text.includes(term));
};

const isTankCleaningCategory = (category) => {
  if (Number(category) === 5) {
    return true;
  }

  return textContainsAny(category, ["tank_cleaning", ...TANK_CLEANING_TERMS]);
};

const isAddonCategory = (category, categoryName = null, options = {}) => {
  if (String(category ?? "").trim().toLowerCase() === "addons") {
    return true;
  }

  if (options.includeNumericAddonCategory === true && Number(category) === ADDON_CATEGORY_ID) {
    return true;
  }

  return textContainsAny([category, categoryName].join(" "), ADDITIONAL_SERVICE_TERMS);
};

const isStandaloneAdditionalServiceCatalogProduct = (product) => {
  if (!product) {
    return false;
  }

  const category = product.category ?? product.product_category;
  if (Number(category) === STANDALONE_ADDITIONAL_SERVICE_CATEGORY_ID) {
    return true;
  }

  return isAddonCategory(category, product.category_name ?? product.categoryName) || textContainsAny(
    [
      product.name,
      product.product_name,
      product.category_name,
      product.categoryName,
    ].join(" "),
    ADDITIONAL_SERVICE_TERMS
  );
};

const isTankCleaningProduct = (product) => {
  if (!product) {
    return false;
  }

  if (isTankCleaningCategory(product.category ?? product.product_category)) {
    return true;
  }

  return textContainsAny(
    [
      product.name,
      product.product_name,
      product.category_name,
      product.categoryName,
    ].join(" "),
    TANK_CLEANING_TERMS
  );
};

const isSpotFreeProduct = (product) => {
  if (!product) {
    return false;
  }

  const productId = Number(product.id ?? product.product_id ?? 0);
  if (SPOT_FREE_PRODUCT_IDS.includes(productId)) {
    return true;
  }

  return textContainsAny(
    [
      product.name,
      product.product_name,
      product.category_name,
      product.categoryName,
    ].join(" "),
    SPOT_FREE_TERMS
  );
};

const getProductCategoryRestrictionForCustomer = (category, attributes = [], options = {}) => {
  if (
    hasCustomerAttribute(attributes, "restrictAdditionalServices") &&
    isAddonCategory(category, options.categoryName, options)
  ) {
    return restrictedByRule("restrictAdditionalServices");
  }
  if (category === "spot_free" && hasCustomerAttribute(attributes, "restrictSpotFree")) {
    return restrictedByRule("restrictSpotFree");
  }
  if (category === "interior_cleaning" && hasCustomerAttribute(attributes, "restrictInteriorCleaning")) {
    return restrictedByRule("restrictInteriorCleaning");
  }
  if (isTankCleaningCategory(category) && hasCustomerAttribute(attributes, "restrictTankCleaning")) {
    return restrictedByRule("restrictTankCleaning");
  }
  if (hasCustomerAttribute(attributes, "onlyTankCleaning") && !isTankCleaningCategory(category)) {
    return restrictedByRule("onlyTankCleaning");
  }

  return allowedRestriction();
};

const isProductCategoryRestrictedForCustomer = (category, attributes = [], options = {}) => {
  return getProductCategoryRestrictionForCustomer(category, attributes, options).restricted;
};

const isAdditionalServiceProduct = (product, options = {}) => {
  if (options.isRelatedAddon === true || Number(options.relatedItemId ?? 0) > 0) {
    return true;
  }

  if (options.isStandaloneAdditionalService === true || options.hasExistingStandaloneOrderItem === true) {
    return true;
  }

  const category = product?.category ?? product?.product_category;
  const categoryName = product?.category_name ?? product?.categoryName ?? options.categoryName;
  if (isAddonCategory(category, categoryName, options)) {
    return true;
  }

  return textContainsAny(
    [
      product?.name,
      product?.product_name,
      categoryName,
    ].join(" "),
    ADDITIONAL_SERVICE_TERMS
  );
};

const getCustomerProductRestriction = (product, attributes = [], options = {}) => {
  if (!product) {
    return allowedRestriction();
  }

  const productName = normalizedText(product.name ?? product.product_name);

  if (
    hasCustomerAttribute(attributes, "restrictAdditionalServices") &&
    isAdditionalServiceProduct(product, options)
  ) {
    return restrictedByRule("restrictAdditionalServices");
  }
  if (hasCustomerAttribute(attributes, "restrictSpotFree") && isSpotFreeProduct(product)) {
    return restrictedByRule("restrictSpotFree");
  }
  if (
    hasCustomerAttribute(attributes, "restrictInteriorCleaning") &&
    textContainsAny(productName, ["interior", "indvendig"])
  ) {
    return restrictedByRule("restrictInteriorCleaning");
  }
  if (isTankCleaningProduct(product) && hasCustomerAttribute(attributes, "restrictTankCleaning")) {
    return restrictedByRule("restrictTankCleaning");
  }
  if (hasCustomerAttribute(attributes, "onlyTankCleaning") && !isTankCleaningProduct(product)) {
    return restrictedByRule("onlyTankCleaning");
  }

  return allowedRestriction();
};

const isProductRestrictedForCustomer = (product, attributes = [], options = {}) => {
  return getCustomerProductRestriction(product, attributes, options).restricted;
};

/**
 * Display toggleable items
 */
const hidePricesCatalog = ref(null);
const hideDiscountsCatalog = ref(null);

// Setters for the hide prices and discounts
const setHidePricesCatalog = (value) => {
  hidePricesCatalog.value = value;
  localStorage.setItem("hidePricesCatalog", "" + value);
};

const setHideDiscountsCatalog = (value) => {
  hideDiscountsCatalog.value = value;
  localStorage.setItem("hideDiscountsCatalog", "" + value);
};

// Getters
const getHidePricesCatalog = () => {
  // If the value is not set, get it from the local storage
  if (hidePricesCatalog.value === null) {
    hidePricesCatalog.value = localStorage.getItem("hidePricesCatalog") === "true";
  }
  return hidePricesCatalog.value;
};

const getHideDiscountsCatalog = () => {
  // If the value is not set, get it from the local storage
  if (hideDiscountsCatalog.value === null) {
    hideDiscountsCatalog.value = localStorage.getItem("hideDiscountsCatalog") === "true";
  }
  return hideDiscountsCatalog.value;
};

/** Define steps for the POS Department Process */
const step = ref(1);
const nextStepDelay = ref(0); // 2 seconds delay
const isCreatingOrder = ref(false);
const desktopStep1PreflightHandler = ref(null);
let createOrderRequest = null;
const posStepSaveBarriers = new Set();
let latestOrderDetailsRequestId = 0;
let latestOrderMetadataMutationSequence = 0;
let activeOrderMetadataMutationCount = 0;

const registerPosStepSaveBarrier = (handler) => {
  if (typeof handler !== "function") {
    return () => {};
  }

  posStepSaveBarriers.add(handler);
  return () => {
    posStepSaveBarriers.delete(handler);
  };
};

const unregisterPosStepSaveBarrier = (handler) => {
  posStepSaveBarriers.delete(handler);
};

const flushPosStepSaveBarriers = async () => {
  const barriers = Array.from(posStepSaveBarriers);
  if (barriers.length === 0) {
    return true;
  }

  const results = await Promise.allSettled(barriers.map((handler) => handler()));
  const failedResult = results.find((result) => result.status === "rejected");

  if (failedResult) {
    parseError(failedResult.reason, "stepError");
    return false;
  }

  return true;
};

const setDesktopStep1PreflightHandler = (handler = null) => {
  desktopStep1PreflightHandler.value = typeof handler === "function" ? handler : null;
};

const clearDesktopStep1PreflightHandler = (handler = null) => {
  if (handler === null || desktopStep1PreflightHandler.value === handler) {
    desktopStep1PreflightHandler.value = null;
  }
};

/** Define the next step delay function */
const setNextStepDelay = (delay) => {
  nextStepDelay.value = delay;
  setTimeout(() => {
    nextStepDelay.value = 0;
  }, delay * 1000);
};

/** Define the step functions */
const nextStep = async (options = { isMobile: false, orderCreation: true }) => {
  const normalizedOptions = {
    isMobile: false,
    orderCreation: true,
    ...options,
  };
  // Check if the delay has passed since the last step (To prevent double clicks)
  if (nextStepDelay.value > 0) {
    return;
  }
  if (
    normalizedOptions.isMobile === false &&
    step.value === 1 &&
    normalizedOptions.orderCreation !== false &&
    typeof desktopStep1PreflightHandler.value === "function"
  ) {
    const canProceedFromPreflight = await desktopStep1PreflightHandler.value({ reason: "next" });
    if (!canProceedFromPreflight) {
      return;
    }
  }
  if (
    normalizedOptions.isMobile === false &&
    step.value === 1 &&
    normalizedOptions.orderCreation !== false &&
    reg_1.value
  ) {
    if (!hasLoadedPendingBookings.value || isLoadingPendingBookings.value) {
      await loadPendingBookings();
    }

    if (doesVehiclePlateRequireBookingSelection(reg_1.value)) {
      return;
    }
  }
  // Set the delay to 2 seconds
  setNextStepDelay(2);
  if (!(await flushPosStepSaveBarriers())) {
    nextStepDelay.value = 0;
    return;
  }
  // Clear the errors
  clearErrors();
  // If the current step is 1, create the order
  if (step.value === 1) {
    await loadCustomerAttributes(customer_id.value);

    if (normalizedOptions.orderCreation === false) {
      step.value++;
      return;
    }
    const didCreateOrder = await createOrder$1(normalizedOptions);
    if (didCreateOrder && normalizedOptions.isMobile === false) {
      await hydrateSelectedOrderBookingForDesktop();
    }
    if (didCreateOrder && step.value === 1) {
      step.value++;
    }
    return;
  }
  if (step.value === 2) {
    // If the current step is 2, set the product category to addons
    setProductsCategory(4);
    // Set the step to 3 in the query parameters
    pushPosRouteState(`id=${order_id.value}&customer_id=${customer_id.value}&step=3`);
  }
  if (step.value === 3) {
    if (normalizedOptions.isMobile === false && doesOrderContainMaterial()) {
      step.value = 4;
      pushPosRouteState(`id=${order_id.value}&customer_id=${customer_id.value}&step=4`);
      return;
    }

    try {
      if (normalizedOptions.isMobile === false) {
        const didLinkSelectedBooking = await finalizeSelectedOrderBookingForDesktop();
        if (!didLinkSelectedBooking) {
          return;
        }
      }

      await SessionUser.objects.orders.functions.mark_as_completed(order_id.value);
      await Swal.fire({
        title: "Fuldført",
        text: "Transaktionen er fuldført, omdirigerer automatisk...",
        icon: "success",
        showConfirmButton: false,
        timer: 2000,
      });
      window.location.href = "/admin/" + department_id.value + "/modules/pos";
    } catch (error) {
      parseError(error, "stepError");
    }
    return;
  }

  if (step.value === 4) {
    try {
      if (normalizedOptions.isMobile === false) {
        const didLinkSelectedBooking = await finalizeSelectedOrderBookingForDesktop();
        if (!didLinkSelectedBooking) {
          return;
        }
      }

      await SessionUser.objects.orders.functions.mark_as_completed(order_id.value);
      await Swal.fire({
        title: "Fuldført",
        text: "Transaktionen er fuldført, omdirigerer automatisk...",
        icon: "success",
        showConfirmButton: false,
        timer: 2000,
      });
      window.location.href = "/admin/" + department_id.value + "/modules/pos";
    } catch (error) {
      parseError(error, "stepError");
    }
    return;
  }
  step.value++;
};

const previousStep = async () => {
  if (nextStepDelay.value > 0) {
    return;
  }

  if (!(await flushPosStepSaveBarriers())) {
    return;
  }

  step.value = Math.max(1, step.value - 1);

  if (order_id.value) {
    pushPosRouteState(`id=${order_id.value}&customer_id=${customer_id.value}&step=${step.value}`);
  } else {
    pushPosRouteState(`step=${step.value}`);
  }
};

const getCurrentStep = () => {
  return step.value;
};

const setStep = (newStep) => {
  step.value = newStep;
};

/** Define the current order dynamic variables */
const customer_id = ref("");
const customer_name = ref("");
const customer_data = ref([]); // The full customer data object
const department_id = ref("");
const reference$1 = ref("");
const notes = ref([]); // The customer notes
const order_notes = ref(""); // The order notes
const order_po = ref(""); // The PO number
const order_safety_seal = ref(""); // Optional safety seal metadata
const reg_1 = ref(""); // Only uppercase letters and numbers without spaces
const reg_2 = ref(""); // Only uppercase letters and numbers without spaces
const reg_3 = ref(""); // Only uppercase letters and numbers without spaces
const order_id = ref(null);
const order_items = ref([]);
const customer_attributes = ref([]);
const user_discounts = ref([]);
const has_user_discounts_loaded = ref(false);
const scan_data = ref([]);
const invoiceCollectionId = ref(null);
const completed_at = ref(null);
let latestCustomerNotesRequestId = 0;
let activeCustomerNotesCustomerNumber = null;

const toPositiveInteger$1 = (value) => {
  const parsed = Number.parseInt(String(value), 10);
  return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
};

const getRouteDepartmentId = () => {
  return getWindowPathDepartmentId();
};

const getSessionUrlDepartmentId = () => {
  try {
    return toPositiveInteger$1(SessionUser.functions?.getDepartmentIdFromUrl?.());
  } catch (error) {
    return null;
  }
};

const getWindowPathDepartmentId = () => {
  try {
    if (typeof window === "undefined") {
      return null;
    }
    const match = (window.location?.pathname || "").match(/^\/admin\/(\d+)(?:\/|$)/);
    return toPositiveInteger$1(match?.[1]);
  } catch (error) {
    return null;
  }
};

const getSelectedDepartmentId = (candidateDepartmentId = null) => {
  const candidates = [
    candidateDepartmentId,
    department_id.value,
    getRouteDepartmentId(),
    getSessionUrlDepartmentId(),
    getWindowPathDepartmentId(),
  ];

  for (const candidate of candidates) {
    const normalizedDepartmentId = toPositiveInteger$1(candidate);
    if (normalizedDepartmentId) {
      return normalizedDepartmentId;
    }
  }

  return null;
};

const reportMissingDepartmentForOrderCreation = () => {
  parseError(
    {
      response: {
        data: {
          data: {
            message: "Afdeling kunne ikke bestemmes for ordren",
          },
          message: "Afdeling kunne ikke bestemmes for ordren",
        },
      },
    },
    "stepError"
  );
};

const getCurrentOrderDepartmentId = async (targetOrderId) => {
  const normalizedOrderId = toPositiveInteger$1(targetOrderId);
  if (!normalizedOrderId) {
    return null;
  }

  if (typeof SessionUser.objects.orders.functions.get_department_id === "function") {
    return toPositiveInteger$1(await SessionUser.objects.orders.functions.get_department_id(normalizedOrderId));
  }

  if (typeof SessionUser.objects.orders.get.single === "function") {
    const order = await SessionUser.objects.orders.get.single(normalizedOrderId);
    return toPositiveInteger$1(order?.department_id);
  }

  return null;
};

const ensureCurrentOrderDepartment = async (targetDepartmentId = null) => {
  const normalizedOrderId = toPositiveInteger$1(order_id.value);
  const normalizedDepartmentId = getSelectedDepartmentId(targetDepartmentId);

  if (!normalizedOrderId || !normalizedDepartmentId) {
    return true;
  }

  try {
    const currentDepartmentId = await getCurrentOrderDepartmentId(normalizedOrderId);
    if (currentDepartmentId === normalizedDepartmentId) {
      department_id.value = normalizedDepartmentId;
      return true;
    }

    parseError(
      {
        response: {
          data: {
            data: {
              message: "Ordren tilhører ikke den valgte afdeling",
            },
            message: "Ordren tilhører ikke den valgte afdeling",
          },
        },
      },
      "stepError"
    );
    return false;
  } catch (error) {
    parseError(error, "stepError");
    return false;
  }
};

const MATERIAL_PRODUCT_IDS = new Set([53, 54]);

const normalizeOrderMetadataString = (value) => {
  return value === null || value === undefined ? "" : String(value);
};

const getNullableOrderMetadataValue = (value) => {
  const normalizedValue = normalizeOrderMetadataString(value).trim();
  return normalizedValue === "" ? null : normalizedValue;
};

const resolveCustomerNumber = (customerOrNumber) => {
  if (customerOrNumber && typeof customerOrNumber === "object") {
    return toPositiveInteger$1(
      customerOrNumber.customerNumber ?? customerOrNumber.customer_number ?? customerOrNumber.id
    );
  }
  return toPositiveInteger$1(customerOrNumber);
};

const getSelectedCustomerNumber = () => {
  return resolveCustomerNumber(customer_id.value);
};

const normalizePhoneDisplayValue = (value) => {
  if (value === null || value === undefined) {
    return "";
  }

  if (typeof value === "string" || typeof value === "number") {
    const normalizedValue = String(value).trim();
    return normalizedValue === "" ? "" : normalizedValue;
  }

  if (Array.isArray(value) || typeof value !== "object") {
    return "";
  }

  const numberCandidate =
    value.number ?? value.phoneNumber ?? value.phone_number ?? value.mobilePhone ?? value.mobile_phone ?? null;

  if (numberCandidate === null || numberCandidate === undefined) {
    return "";
  }

  return normalizePhoneDisplayValue(numberCandidate);
};

const resolveNormalizedPhoneNumber = (...candidates) => {
  for (const candidate of candidates) {
    const normalizedValue = normalizePhoneDisplayValue(candidate);
    if (normalizedValue !== "") {
      return normalizedValue;
    }
  }
  return "";
};

const normalizeCustomerRecord = (customer, fallback = {}) => {
  if (!customer || typeof customer !== "object" || Array.isArray(customer)) {
    const fallbackCustomerNumber = resolveCustomerNumber(
      fallback.customerNumber ?? fallback.customer_number ?? customer
    );

    return {
      id: fallback.id ?? fallbackCustomerNumber ?? null,
      customerNumber: fallbackCustomerNumber,
      name: fallback.name ?? fallback.customer_name ?? fallback.customerName ?? "",
      address: fallback.address ?? "",
      zip: fallback.zip ?? fallback.zip_code ?? fallback.postalCode ?? "",
      city: fallback.city ?? "",
      mobilePhone: resolveNormalizedPhoneNumber(
        fallback.mobilePhone,
        fallback.mobile_phone,
        fallback.phone?.number,
        fallback.phone,
        fallback.phoneNumber,
        fallback.phone_number
      ),
      email: fallback.email ?? "",
      corporateIdentificationNumber:
        fallback.corporateIdentificationNumber ?? fallback.corporate_identification_number ?? fallback.cvr ?? "",
      economic_customer: fallback.economic_customer ?? fallbackCustomerNumber,
      barred: Boolean(fallback.barred),
    };
  }

  const resolvedCustomerNumber = resolveCustomerNumber(
    customer.customerNumber ??
      customer.customer_number ??
      customer.economic_customer ??
      customer.economicCustomer ??
      fallback.customerNumber ??
      fallback.customer_number
  );

  return {
    ...customer,
    id: customer.id ?? resolvedCustomerNumber ?? null,
    customerNumber: resolvedCustomerNumber,
    name:
      customer.name ?? customer.customer_name ?? customer.customerName ?? fallback.name ?? fallback.customer_name ?? "",
    address: customer.address ?? fallback.address ?? "",
    zip: customer.zip ?? customer.zip_code ?? customer.postalCode ?? fallback.zip ?? fallback.zip_code ?? "",
    city: customer.city ?? fallback.city ?? "",
    mobilePhone: resolveNormalizedPhoneNumber(
      customer.mobilePhone,
      customer.mobile_phone,
      customer.phone?.number,
      customer.phone,
      customer.phoneNumber,
      customer.phone_number,
      fallback.mobilePhone,
      fallback.mobile_phone,
      fallback.phone?.number,
      fallback.phone,
      fallback.phoneNumber,
      fallback.phone_number
    ),
    email: customer.email ?? fallback.email ?? "",
    corporateIdentificationNumber:
      customer.corporateIdentificationNumber ??
      customer.corporate_identification_number ??
      customer.cvr ??
      fallback.corporateIdentificationNumber ??
      fallback.corporate_identification_number ??
      fallback.cvr ??
      "",
    economic_customer: customer.economic_customer ?? customer.economicCustomer ?? resolvedCustomerNumber,
    barred: Boolean(customer.barred ?? fallback.barred),
  };
};

const clearSelectedCustomerState = (options = {}) => {
  const normalizedOptions = {
    clearOrderNotes: false,
    ...options,
  };

  customer_id.value = "";
  customer_name.value = "";
  customer_data.value = [];
  customer_attributes.value = [];
  notes.value = [];
  user_discounts.value = [];
  has_user_discounts_loaded.value = false;
  activeCustomerNotesCustomerNumber = null;
  latestCustomerNotesRequestId += 1;

  if (normalizedOptions.clearOrderNotes) {
    order_notes.value = "";
  }
};

const getStoredPosOrderId = () => {
  const storedOrderId = toPositiveInteger$1(localStorage.getItem("pos_order_id"));
  if (!storedOrderId) {
    localStorage.removeItem("pos_order_id");
    return null;
  }
  return storedOrderId;
};

const clearStoredPosOrderId = () => {
  localStorage.removeItem("pos_order_id");
};

const hasActivePosOrderContext = () => {
  return Boolean(
    toPositiveInteger$1(order_id.value) ||
      getSelectedCustomerNumber() ||
      String(customer_name.value ?? "").trim() ||
      (Array.isArray(order_items.value) && order_items.value.length > 0) ||
      String(reference$1.value ?? "").trim() ||
      String(order_notes.value ?? "").trim() ||
      String(order_po.value ?? "").trim() ||
      String(order_safety_seal.value ?? "").trim() ||
      String(reg_1.value ?? "").trim() ||
      String(reg_2.value ?? "").trim() ||
      String(reg_3.value ?? "").trim() ||
      invoiceCollectionId.value ||
      completed_at.value ||
      getStoredPosOrderId()
  );
};

const clearActivePosOrderContext = (options = {}) => {
  const normalizedOptions = {
    clearStep: false,
    clearStoredOrderId: true,
    ...options,
  };
  const hadActiveContext = hasActivePosOrderContext();

  clearErrors();
  if (normalizedOptions.clearStep) {
    step.value = 1;
  }
  order_id.value = null;
  clearSelectedCustomerState({ clearOrderNotes: true });
  order_items.value = [];
  user_discounts.value = [];
  has_user_discounts_loaded.value = false;
  scans.value = [];
  scan_data.value = [];
  invoiceCollectionId.value = null;
  completed_at.value = null;
  reference$1.value = "";
  order_notes.value = "";
  order_po.value = "";
  order_safety_seal.value = "";
  reg_1.value = "";
  reg_2.value = "";
  reg_3.value = "";
  isCreatingOrder.value = false;
  createOrderRequest = null;
  clearSelectedOrderBookingSelection();
  if (normalizedOptions.clearStoredOrderId) {
    clearStoredPosOrderId();
  }

  return hadActiveContext;
};

const SELECTED_ORDER_BOOKING_ID_STORAGE_KEY = "pos_selected_order_booking_id";
const SELECTED_ORDER_BOOKING_PLATE_STORAGE_KEY = "pos_selected_order_booking_plate";
const SELECTED_ORDER_BOOKING_SKIPPED_PLATE_STORAGE_KEY = "pos_selected_order_booking_skipped_plate";

const selectedOrderBookingId = ref(null);
const selectedOrderBookingPlate = ref("");
const selectedOrderBookingSkippedPlate = ref("");

const normalizeVehiclePlateForBookingSelection = (value) =>
  String(value ?? "")
    .replace(/\s/g, "")
    .toUpperCase();

const getCurrentBookingSelectionDepartmentId = () => {
  return toPositiveInteger$1(department_id.value);
};

const doesOrderBookingMatchCurrentDepartment = (booking = null) => {
  const currentDepartmentId = getCurrentBookingSelectionDepartmentId();
  if (!currentDepartmentId) {
    return true;
  }

  const bookingDepartmentId = toPositiveInteger$1(booking?.department ?? booking?.department_id);
  if (!bookingDepartmentId) {
    return false;
  }

  return bookingDepartmentId === currentDepartmentId;
};

const restoreSelectedOrderBookingState = () => {
  if (typeof localStorage === "undefined") {
    return;
  }
  selectedOrderBookingId.value = toPositiveInteger$1(localStorage.getItem(SELECTED_ORDER_BOOKING_ID_STORAGE_KEY));
  selectedOrderBookingPlate.value = normalizeVehiclePlateForBookingSelection(
    localStorage.getItem(SELECTED_ORDER_BOOKING_PLATE_STORAGE_KEY)
  );
  selectedOrderBookingSkippedPlate.value = normalizeVehiclePlateForBookingSelection(
    localStorage.getItem(SELECTED_ORDER_BOOKING_SKIPPED_PLATE_STORAGE_KEY)
  );

  if (selectedOrderBookingId.value) {
    localStorage.setItem(SELECTED_ORDER_BOOKING_ID_STORAGE_KEY, String(selectedOrderBookingId.value));
  } else {
    localStorage.removeItem(SELECTED_ORDER_BOOKING_ID_STORAGE_KEY);
  }

  if (selectedOrderBookingPlate.value) {
    localStorage.setItem(SELECTED_ORDER_BOOKING_PLATE_STORAGE_KEY, selectedOrderBookingPlate.value);
  } else {
    localStorage.removeItem(SELECTED_ORDER_BOOKING_PLATE_STORAGE_KEY);
  }

  if (selectedOrderBookingSkippedPlate.value) {
    localStorage.setItem(SELECTED_ORDER_BOOKING_SKIPPED_PLATE_STORAGE_KEY, selectedOrderBookingSkippedPlate.value);
  } else {
    localStorage.removeItem(SELECTED_ORDER_BOOKING_SKIPPED_PLATE_STORAGE_KEY);
  }
};

const persistSelectedOrderBookingState = () => {
  if (typeof localStorage === "undefined") {
    return;
  }
  if (selectedOrderBookingId.value) {
    localStorage.setItem(SELECTED_ORDER_BOOKING_ID_STORAGE_KEY, String(selectedOrderBookingId.value));
  } else {
    localStorage.removeItem(SELECTED_ORDER_BOOKING_ID_STORAGE_KEY);
  }

  if (selectedOrderBookingPlate.value) {
    localStorage.setItem(SELECTED_ORDER_BOOKING_PLATE_STORAGE_KEY, selectedOrderBookingPlate.value);
  } else {
    localStorage.removeItem(SELECTED_ORDER_BOOKING_PLATE_STORAGE_KEY);
  }

  if (selectedOrderBookingSkippedPlate.value) {
    localStorage.setItem(SELECTED_ORDER_BOOKING_SKIPPED_PLATE_STORAGE_KEY, selectedOrderBookingSkippedPlate.value);
  } else {
    localStorage.removeItem(SELECTED_ORDER_BOOKING_SKIPPED_PLATE_STORAGE_KEY);
  }
};

const clearSelectedOrderBookingSelection = (options = {}) => {
  const normalizedOptions = {
    clearSkippedPlate: true,
    ...options,
  };

  selectedOrderBookingId.value = null;
  selectedOrderBookingPlate.value = "";
  if (normalizedOptions.clearSkippedPlate) {
    selectedOrderBookingSkippedPlate.value = "";
  }
  persistSelectedOrderBookingState();
};

const setSelectedOrderBookingSelection = (booking, plate = null) => {
  const normalizedBookingId = toPositiveInteger$1(booking?.id ?? booking);
  const normalizedPlate = normalizeVehiclePlateForBookingSelection(
    plate ?? booking?.reg_1 ?? booking?.reg_2 ?? booking?.plate ?? ""
  );

  selectedOrderBookingId.value = normalizedBookingId;
  selectedOrderBookingPlate.value = normalizedPlate;
  selectedOrderBookingSkippedPlate.value = "";
  persistSelectedOrderBookingState();
};

const skipSelectedOrderBookingSelection = (plate) => {
  clearSelectedOrderBookingSelection({ clearSkippedPlate: false });
  selectedOrderBookingSkippedPlate.value = normalizeVehiclePlateForBookingSelection(plate);
  persistSelectedOrderBookingState();
};

const isSelectedOrderBookingSkippedForPlate = (plate) => {
  const normalizedPlate = normalizeVehiclePlateForBookingSelection(plate);
  return normalizedPlate !== "" && normalizedPlate === selectedOrderBookingSkippedPlate.value;
};

restoreSelectedOrderBookingState();

const restoreStoredPosOrderId = async (
  options = {
    validateOrder: true,
    customerId: null,
    departmentId: null,
    allowCompleted: false,
    syncDepartment: false,
  }
) => {
  const storedOrderId = getStoredPosOrderId();
  if (!storedOrderId) {
    return null;
  }

  if (options.validateOrder === false) {
    order_id.value = storedOrderId;
    return storedOrderId;
  }

  try {
    const storedOrder = await SessionUser.objects.orders.get.single(storedOrderId);
    const resolvedOrderId = toPositiveInteger$1(storedOrder?.id);
    if (resolvedOrderId !== storedOrderId) {
      throw new Error("Stored order was not found");
    }

    const selectedCustomerId = toPositiveInteger$1(options.customerId);
    if (selectedCustomerId && toPositiveInteger$1(storedOrder?.customer_id) !== selectedCustomerId) {
      throw new Error("Stored order customer does not match current customer");
    }

    if (!options.allowCompleted && storedOrder?.completed_at) {
      throw new Error("Stored order is already completed");
    }

    const selectedDepartmentId = toPositiveInteger$1(options.departmentId);
    if (selectedDepartmentId && toPositiveInteger$1(storedOrder?.department_id) !== selectedDepartmentId) {
      if (options.syncDepartment === true) {
        order_id.value = storedOrderId;
        const isCurrentDepartment = await ensureCurrentOrderDepartment(selectedDepartmentId);
        if (!isCurrentDepartment) {
          throw new Error("Stored order department does not match current department");
        }
      } else {
        throw new Error("Stored order department does not match current department");
      }
    }

    order_id.value = storedOrderId;
    return storedOrderId;
  } catch (error) {
    if (toPositiveInteger$1(order_id.value) === storedOrderId) {
      order_id.value = null;
    }
    clearStoredPosOrderId();
    return null;
  }
};

const reset_all_values = () => {
  // Reset all values to their initial state
  clearActivePosOrderContext({ clearStep: true });
  // Clear the query parameters
  pushPosRouteState("step=1");
};

/** Whenever the reg_1, reg_2 or reg_3 changes, remove any spaces and make the string uppercase */
const normalizeRegistrationValue = (value) =>
  String(value ?? "")
    .replace(/\s/g, "")
    .toUpperCase();

const isBlankPosMetadataValue = (value) => String(value ?? "").trim().length === 0;

const getPosRoutePath = () => {
  const normalizedDepartmentId = Number.parseInt(String(department_id.value || ""), 10);

  if (Number.isInteger(normalizedDepartmentId) && normalizedDepartmentId > 0) {
    return `/admin/${normalizedDepartmentId}/modules/pos`;
  }

  return window.location.pathname && window.location.pathname !== "/" ? window.location.pathname : "/admin/modules/pos";
};

const pushPosRouteState = (queryString) => {
  const normalizedQueryString = String(queryString || "").replace(/^\?/, "");
  window.history.pushState({}, "", `${getPosRoutePath()}?${normalizedQueryString}`);
};

watch([reg_1, reg_2, reg_3], () => {
  reg_1.value = normalizeRegistrationValue(reg_1.value);
  reg_2.value = normalizeRegistrationValue(reg_2.value);
  reg_3.value = normalizeRegistrationValue(reg_3.value);
});

const applyOrderMetadataFieldToPosState = (field, value) => {
  if (field === "reference") {
    reference$1.value = normalizeOrderMetadataString(value);
    return reference$1.value;
  }

  if (field === "notes") {
    order_notes.value = normalizeOrderMetadataString(value);
    return order_notes.value;
  }

  if (field === "po") {
    order_po.value = normalizeOrderMetadataString(value);
    return order_po.value;
  }

  if (field === "safety_seal") {
    order_safety_seal.value = normalizeOrderMetadataString(value);
    return order_safety_seal.value;
  }

  if (field === "reg_1") {
    reg_1.value = normalizeRegistrationValue(value);
    return reg_1.value;
  }

  if (field === "reg_2") {
    reg_2.value = normalizeRegistrationValue(value);
    return reg_2.value;
  }

  if (field === "reg_3") {
    reg_3.value = normalizeRegistrationValue(value);
    return reg_3.value;
  }

  return normalizeOrderMetadataString(value);
};

const applyOrderDetailsToPosState = (orderData, includes = {}) => {
  if (!orderData || typeof orderData !== "object") {
    return null;
  }

  const includedCustomer = includes?.customer ?? null;
  const normalizedOrderCustomerNumber = resolveCustomerNumber(orderData?.customer_id);
  const selectedCustomerBeforeHydration = getSelectedCustomerNumber();

  department_id.value = orderData.department_id;
  applyOrderMetadataFieldToPosState("reference", orderData.reference);
  applyOrderMetadataFieldToPosState("notes", orderData.notes);
  applyOrderMetadataFieldToPosState("po", orderData.po);
  applyOrderMetadataFieldToPosState("safety_seal", orderData.safety_seal);
  applyOrderMetadataFieldToPosState("reg_1", orderData.reg_1);
  applyOrderMetadataFieldToPosState("reg_2", orderData.reg_2);
  applyOrderMetadataFieldToPosState("reg_3", orderData.reg_3);
  invoiceCollectionId.value = orderData.invoice_collection_id || null;
  completed_at.value = orderData.completed_at || null;

  if (includedCustomer && typeof includedCustomer === "object") {
    const customerSource =
      includedCustomer.economic_customer && typeof includedCustomer.economic_customer === "object"
        ? includedCustomer.economic_customer
        : includedCustomer;

    selectCustomer(
      normalizeCustomerRecord(customerSource, {
        ...includedCustomer,
        customerNumber: normalizedOrderCustomerNumber ?? resolveCustomerNumber(includedCustomer),
        name: includedCustomer.name ?? includedCustomer.customer_name ?? orderData.customer_name ?? customer_name.value,
        customer_name:
          includedCustomer.customer_name ?? includedCustomer.name ?? orderData.customer_name ?? customer_name.value,
      })
    );
  } else if (normalizedOrderCustomerNumber) {
    customer_id.value = normalizedOrderCustomerNumber;
    if (
      selectedCustomerBeforeHydration !== normalizedOrderCustomerNumber ||
      customer_name.value === "" ||
      !customer_data.value
    ) {
      void searchAndSelectCustomer(normalizedOrderCustomerNumber, { forceRefresh: true });
    }
  } else {
    clearSelectedCustomerState();
  }

  return orderData;
};

const saveOrderMetadataField = async (field, value, targetOrderId = order_id.value) => {
  const normalizedOrderId = toPositiveInteger$1(targetOrderId);
  const setter = SessionUser.objects.orders.set?.[field];

  if (!normalizedOrderId || typeof setter !== "function") {
    throw new Error(`Unable to save order field: ${field}`);
  }

  const mutationSequence = latestOrderMetadataMutationSequence + 1;
  latestOrderMetadataMutationSequence = mutationSequence;
  activeOrderMetadataMutationCount += 1;
  const isRegistrationField = field === "reg_1" || field === "reg_2" || field === "reg_3";
  const requestValue = isRegistrationField
    ? String(value ?? "").toUpperCase()
    : normalizeOrderMetadataString(value);
  const normalizedValue = isRegistrationField ? normalizeRegistrationValue(value) : requestValue;
  try {
    const response = await setter(normalizedOrderId, requestValue);
    const updatedOrder = response?.data?.data;

    if (updatedOrder && toPositiveInteger$1(updatedOrder.id) === normalizedOrderId) {
      if (mutationSequence === latestOrderMetadataMutationSequence && activeOrderMetadataMutationCount === 1) {
        applyOrderDetailsToPosState(updatedOrder, response?.data?.includes ?? {});
      }
      return applyOrderMetadataFieldToPosState(field, updatedOrder[field] ?? normalizedValue);
    }

    return applyOrderMetadataFieldToPosState(field, normalizedValue);
  } finally {
    activeOrderMetadataMutationCount = Math.max(0, activeOrderMetadataMutationCount - 1);
  }
};

/** Get the order details by order id */
const getOrderDetails = async (id = null) => {
  const token = localStorage.getItem("token");
  const targetOrderId = id ?? order_id.value;
  if (!token || !targetOrderId) {
    return null;
  }
  const requestId = ++latestOrderDetailsRequestId;
  const metadataMutationSequenceAtRequest = latestOrderMetadataMutationSequence;
  const hadActiveMetadataMutationAtRequest = activeOrderMetadataMutationCount > 0;
  return axios
    .get(API_URL + "/order?id=" + targetOrderId, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    .then((response) => {
      const order_data = response.data.data;
      if (!order_data) {
        return null;
      }

      const normalizedResponseOrderId = toPositiveInteger$1(order_data.id ?? targetOrderId);
      const normalizedCurrentOrderId = toPositiveInteger$1(order_id.value);
      const isStaleForDifferentOrder =
        requestId !== latestOrderDetailsRequestId &&
        normalizedCurrentOrderId &&
        normalizedResponseOrderId &&
        normalizedCurrentOrderId !== normalizedResponseOrderId;
      const isStaleBeforeMetadataMutation = metadataMutationSequenceAtRequest !== latestOrderMetadataMutationSequence;

      if (!isStaleForDifferentOrder && !isStaleBeforeMetadataMutation && !hadActiveMetadataMutationAtRequest) {
        applyOrderDetailsToPosState(order_data, response?.data?.includes ?? {});
      }
      // Return the order data
      return order_data;
    })
    .catch((error) => {
      parseError(error, "stepError");
      return null;
    });
};

const getOrderReg1 = async (orderId) => {
  const order = await getOrderDetails(orderId);
  if (!order) {
    return "";
  }
  return order.reg_1;
};

/** Define the current order functions */
const createOrder$1 = async (options = { isMobile: false }) => {
  if (order_id.value) {
    return ensureCurrentOrderDepartment(options.departmentId ?? getDepartment());
  }
  if (isCreatingOrder.value && createOrderRequest) {
    return createOrderRequest;
  }
  const token = localStorage.getItem("token");
  if (!token) {
    return Promise.resolve(false);
  }
  const normalizedBookingId = toPositiveInteger$1(options.bookingId ?? selectedOrderBookingId.value);
  const selectedDepartmentId = getSelectedDepartmentId(options.departmentId);
  if (!selectedDepartmentId) {
    reportMissingDepartmentForOrderCreation();
    return false;
  }

  isCreatingOrder.value = true;
  createOrderRequest = axios
    .post(
      API_URL + "/orders",
      {
        customer_id: customer_id.value,
        department_id: selectedDepartmentId,
        reference: reference$1.value,
        notes: order_notes.value,
        po: order_po.value,
        safety_seal: getNullableOrderMetadataValue(order_safety_seal.value),
        reg_1: reg_1.value,
        reg_2: reg_2.value,
        reg_3: reg_3.value,
        ...(normalizedBookingId ? { booking_id: normalizedBookingId } : {}),
        is_handheld: options.isMobile,
      },
      {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      }
    )
    .then((response) => {
      // Check if the response is successful
      if (!response.data.success) {
        parseError(response, "stepError");
        return false;
      }
      const createdOrder = response.data.data || {};
      order_id.value = parseInt(createdOrder.id);
      if (!isBlankPosMetadataValue(createdOrder.po)) {
        order_po.value = String(createdOrder.po);
      }
      if (selectedDepartmentId) {
        department_id.value = selectedDepartmentId;
      }
      // Set the order id in the local storage (To be make F5 safe)
      localStorage.setItem("pos_order_id", order_id.value);
      // Set the query parameters
      pushPosRouteState(`id=${order_id.value}&customer_id=${customer_id.value}&step=2`);
      return true;
    })
    .catch((error) => {
      parseError(error, "stepError");
      return false;
    })
    .finally(() => {
      isCreatingOrder.value = false;
      createOrderRequest = null;
    });
  return createOrderRequest;
};

const deleteOrder = (options = {}) => {
  const token = localStorage.getItem("token");
  if (!token) {
    return null;
  }
  return SessionUser.objects.orders.delete
    .single(order_id.value, options)
    .then((response) => {
      if (response?.data?.success === false) {
        parseError(response, "stepError");
        return false;
      }
      order_id.value = null;
      return response;
    })
    .catch((error) => {
      parseError(error, "stepError");
      return false;
    });
};

const getOrderId = () => {
  return order_id.value;
};

/** Define the department license plate scans dynamic variables */
const scans = ref([]);
const scans_page = ref(1);
const scans_limit = ref(10);

/** Define the department license plate scans functions */
const getScans = (forceClearCache = false) => {
  if (forceClearCache) {
    scans.value = [];
  }
  // If the scans are already loaded, return them
  if (scans.value.length > 0) {
    return scans.value;
  }
  // Get the scans from the API
  getScansDepartmentPagination(department_id.value, scans_page.value, scans_limit.value)
    .then((response) => {
      scans.value = response.data.data;
    })
    .catch((error) => {
      console.error(error);
    });
  return scans.value;
};

/** Define the department setters */
const setDepartment = (id = null) => {
  const nextDepartmentId = getSelectedDepartmentId(id);
  const previousDepartmentKey = String(department_id.value ?? "");
  department_id.value = nextDepartmentId ?? "";

  if (previousDepartmentKey !== String(nextDepartmentId ?? "")) {
    syncPendingBookingsDepartmentState();
    void ensureCurrentOrderDepartment(nextDepartmentId);
  }
};

/** Define the department getters */
const getDepartment = () => {
  return department_id.value;
};

/** Define the product category dynamic variables */
const products_category = ref(null);

/** Define the product category functions */
const setProductsCategory = (category) => {
  if (products_category.value === category) {
    return;
  }
  products_category.value = category;
};

const getProductsCategory = () => {
  return products_category.value;
};

const getUserGlobalDiscount = () => {
  // Check if the user discounts are loaded
  if (user_discounts.value === undefined) {
    getUserDiscounts();
  }

  // Find the specific discount for the category
  let discount = 0;
  try {
    discount = parseInt(user_discounts.value.find((discount) => discount.id === "999999").percentage) || null;
  } catch (e) {}
  // If there is no discount, return 0
  if (!discount) {
    return 0;
  }
  // Return the discount
  return discount;
};

/** Check if the customer is barred */
const isCustomerBarred = (customer) => {
  // Check if the customer.barred field exists, otherwise return false
  return customer.barred ? customer.barred : false;
};
/** get the customer email (if present) */
const getCustomerEmail = () => {
  // Check if the customer.email field exists, otherwise return empty string
  return customer_data.value.email ? customer_data.value.email : "";
};
/** Select a customer */
const selectCustomer = (customer, options = {}) => {
  const normalizedOptions = {
    forceRefresh: false,
    ...options,
  };

  // If the customer is null, clear the customer data
  if (!customer) {
    clearSelectedCustomerState();
    return;
  }
  // Check if the customer is barred
  if (isCustomerBarred(customer)) {
    /**
    Swal.fire({
      title: 'Kunden er spærret',
      text: 'Denne kunde er spærret og kan ikke bruges',
      icon: 'error',
      confirmButtonText: 'Ok'
    }); */
    // Select the 999 customer
    searchAndSelectCustomer(999, normalizedOptions);
    return;
  }

  const normalizedCustomer = normalizeCustomerRecord(customer);

  const nextCustomerNumber = resolveCustomerNumber(normalizedCustomer);
  if (!nextCustomerNumber) {
    clearSelectedCustomerState();
    return;
  }

  const currentCustomerNumber = getSelectedCustomerNumber();
  const isSameCustomer = currentCustomerNumber === nextCustomerNumber;

  if (!isSameCustomer) {
    clearSelectedCustomerState();
  }

  customer_id.value = nextCustomerNumber;
  customer_name.value = normalizedCustomer.name || "";
  customer_data.value = normalizedCustomer;
  console.log(normalizedCustomer);

  if (isSameCustomer && !normalizedOptions.forceRefresh) {
    return;
  }

  // Get the customer's notes
  fetchCustomerNotes(nextCustomerNumber);
  // Get the customer's attributes
  loadCustomerAttributes(nextCustomerNumber);
};

/** Is customer selected */
const isCustomerSelected = () => {
  return customer_name.value !== "";
};

const doesOrderContainMaterial = () => {
  return order_items.value.some((item) => MATERIAL_PRODUCT_IDS.has(Number(item?.product?.id ?? item?.product_id)));
};

const doesOrderContainWashCertificate = () => {
  return doesOrderContainWashCertificateProduct(order_items.value);
};

/** Fetch the customer's notes */
const fetchCustomerNotes = (customerNumber = customer_id.value) => {
  const normalizedCustomerNumber = resolveCustomerNumber(customerNumber);
  if (!normalizedCustomerNumber) {
    activeCustomerNotesCustomerNumber = null;
    latestCustomerNotesRequestId += 1;
    notes.value = [];
    return Promise.resolve(notes.value);
  }

  const requestId = latestCustomerNotesRequestId + 1;
  latestCustomerNotesRequestId = requestId;
  activeCustomerNotesCustomerNumber = normalizedCustomerNumber;

  return getNotes(normalizedCustomerNumber)
    .then((response) => {
      const isLatestRequest = requestId === latestCustomerNotesRequestId;
      const isStillSelectedCustomer = getSelectedCustomerNumber() === normalizedCustomerNumber;
      const isActiveCustomer = activeCustomerNotesCustomerNumber === normalizedCustomerNumber;

      if (!isLatestRequest || !isStillSelectedCustomer || !isActiveCustomer) {
        return notes.value;
      }

      notes.value = Array.isArray(response?.data?.data) ? response.data.data : [];
      return notes.value;
    })
    .catch((error) => {
      console.error(error);
      return notes.value;
    });
};

/** Create a customer note */
const addCustomerNote = (note) => {
  const selectedCustomerNumber = getSelectedCustomerNumber();
  createNote(selectedCustomerNumber, note)
    .then((response) => {
      fetchCustomerNotes(selectedCustomerNumber);
    })
    .catch((error) => {
      console.error(error);
    });
};

/** Delete a customer note */
const removeCustomerNote = (id) => {
  const selectedCustomerNumber = getSelectedCustomerNumber();
  deleteNote(id)
    .then((response) => {
      fetchCustomerNotes(selectedCustomerNumber);
    })
    .catch((error) => {
      console.error(error);
    });
};

/** Show confirmation delete note dialog */
const showDeleteNoteDialog = (noteId) => {
  Swal.fire({
    title: "Are you sure?",
    text: `You are about to delete the note: ${noteId}`,
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Yes, delete it!",
    cancelButtonText: "No, keep it",
  }).then((result) => {
    if (result.isConfirmed) {
      removeCustomerNote(noteId);
    }
  });
};

/** Select a scan */
const selectScan = (scan) => {
  // Check which registration number is empty
  //if (!Object.keys(reg_1.value).length > 0 || !reg_1.value) {
  // Set the registration number 1
  //reg_1.value = scan.plate;
  //return;
  //}
  // Set the registration number 1
  reg_1.value = scan.plate;
};

const cached_customer_names = [];
const activeCustomerSelectionRequests = new Map();

/** Get the customer's name */
const getCustomerName = async (customerNumber) => {
  if (!customerNumber) {
    return "";
  }
  // Check if the customer name is already cached
  if (cached_customer_names[customerNumber]) {
    return cached_customer_names[customerNumber];
  }
  // Get the customer data
  await authenticatedRequest(`/users/customer?customer_number=${customerNumber}`, "GET")
    .then((response) => {
      console.log(response);
      // Cache the customer name
      cached_customer_names[customerNumber] = response.data.data.customer_name;
      return cached_customer_names[customerNumber];
    })
    .catch((error) => {
      // If the customer is not found, return an empty string
      cached_customer_names[customerNumber] = "";
      console.error(error);
    });
  return "";
};

/** Search, then select customer by customer number */
const searchAndSelectCustomer = async (customerNumber, options = {}) => {
  const normalizedOptions = {
    forceRefresh: false,
    ...options,
  };
  const normalizedCustomerNumber = resolveCustomerNumber(customerNumber);
  if (!normalizedCustomerNumber) {
    return null;
  }

  const selectedCustomerNumber = getSelectedCustomerNumber();
  const hasSelectedCustomerData =
    customer_data.value &&
    typeof customer_data.value === "object" &&
    !Array.isArray(customer_data.value) &&
    Object.keys(customer_data.value).length > 0;

  if (
    !normalizedOptions.forceRefresh &&
    selectedCustomerNumber === normalizedCustomerNumber &&
    hasSelectedCustomerData
  ) {
    return customer_data.value;
  }

  if (!normalizedOptions.forceRefresh && activeCustomerSelectionRequests.has(normalizedCustomerNumber)) {
    return await activeCustomerSelectionRequests.get(normalizedCustomerNumber);
  }

  // Get the customer data
  const request = authenticatedRequest(`/users/customer?customer_number=${normalizedCustomerNumber}`, "GET")
    .then((response) => {
      console.log(response);
      const responseData = response?.data?.data ?? {};
      const rawEconomicCustomer = responseData.economic_customer ?? null;
      const normalizedCustomer = normalizeCustomerRecord(rawEconomicCustomer, {
        ...responseData,
        customerNumber: resolveCustomerNumber(rawEconomicCustomer) ?? normalizedCustomerNumber,
      });
      selectCustomer(normalizedCustomer, normalizedOptions);
      return normalizedCustomer;
    })
    .catch((error) => {
      console.error(error);
      return null;
    })
    .finally(() => {
      if (activeCustomerSelectionRequests.get(normalizedCustomerNumber) === request) {
        activeCustomerSelectionRequests.delete(normalizedCustomerNumber);
      }
    });

  if (!normalizedOptions.forceRefresh) {
    activeCustomerSelectionRequests.set(normalizedCustomerNumber, request);
  }

  return await request;
};

/** Get order items */
const loadOrderItems = async () => {
  const normalizedOrderId = Number(order_id.value);
  if (!Number.isInteger(normalizedOrderId) || normalizedOrderId <= 0) {
    order_items.value = [];
    return order_items.value;
  }
  const response = await getOrderItems(normalizedOrderId);
  if (!response || !response.data || !Array.isArray(response.data.data)) {
    order_items.value = [];
    return order_items.value;
  }
  order_items.value = response.data.data;
  return order_items.value;
};

const isStandaloneOrderItem = (item) => item?.related_item_id === null || item?.related_item_id === undefined;

const getOrderItemProductId = (item) => {
  return toPositiveInteger$1(item?.product?.id ?? item?.product_id);
};

const getOrderItemQuantity = (item) => {
  const parsedQuantity = Number.parseInt(String(item?.quantity ?? 1), 10);
  return Number.isInteger(parsedQuantity) && parsedQuantity > 0 ? parsedQuantity : null;
};

const getOrderItemNotes = (item) => {
  const notesValue = String(item?.notes ?? item?.product?.notes ?? "").trim();
  return notesValue === "" ? null : notesValue;
};

const copyLastWashReferenceToEmptyCurrentOrder = async (sourceReference) => {
  const normalizedSourceReference = String(sourceReference ?? "").trim();
  if (!normalizedSourceReference || !isBlankPosMetadataValue(reference$1.value)) {
    return;
  }

  reference$1.value = normalizedSourceReference;

  const normalizedOrderId = toPositiveInteger$1(order_id.value);
  if (normalizedOrderId) {
    await saveOrderMetadataField("reference", normalizedSourceReference, normalizedOrderId);
  }
};

const createCopiedOrderItem = (targetOrderId, sourceItem, relatedItemId = null) => {
  const productId = getOrderItemProductId(sourceItem);
  const quantity = getOrderItemQuantity(sourceItem);
  if (!productId || !quantity) {
    return Promise.resolve(null);
  }

  return createOrderItem(
    targetOrderId,
    productId,
    quantity,
    relatedItemId,
    getOrderItemNotes(sourceItem)
  );
};

const copyLastWashItemsToCurrentOrder = async (sourceItems = [], options = {}) => {
  const normalizedSourceItems = Array.isArray(sourceItems) ? sourceItems.filter(Boolean) : [];
  const standaloneItems = normalizedSourceItems.filter(isStandaloneOrderItem);
  const primarySourceItem =
    standaloneItems.find((item) => getOrderItemProductId(item) && getOrderItemQuantity(item)) ||
    normalizedSourceItems.find((item) => getOrderItemProductId(item) && getOrderItemQuantity(item));

  if (!primarySourceItem) {
    return false;
  }

  await copyLastWashReferenceToEmptyCurrentOrder(options.sourceReference ?? options.sourceOrder?.reference);

  const didEnsureOrder = await createOrder$1({
    ...options,
    isMobile: false,
  });
  if (!didEnsureOrder) {
    return false;
  }

  const normalizedOrderId = toPositiveInteger$1(order_id.value);
  if (!normalizedOrderId) {
    return false;
  }

  const currentItems = await loadOrderItems();
  await Promise.all((currentItems || []).map((item) => removeOrderItem(item.id)).filter(Boolean));
  order_items.value = [];

  const createdPrimaryResponse = await createCopiedOrderItem(normalizedOrderId, primarySourceItem, null);
  const createdPrimaryItemId = toPositiveInteger$1(createdPrimaryResponse?.data?.data?.id);
  if (!createdPrimaryItemId) {
    await loadOrderItems();
    return false;
  }

  const primarySourceItemId = toPositiveInteger$1(primarySourceItem?.id);
  const addonItems = primarySourceItemId
    ? normalizedSourceItems.filter((item) => toPositiveInteger$1(item?.related_item_id) === primarySourceItemId)
    : [];
  const addonItemIds = new Set(addonItems.map((item) => toPositiveInteger$1(item?.id)).filter(Boolean));
  const additionalItems = standaloneItems.filter((item) => {
    const sourceItemId = toPositiveInteger$1(item?.id);
    if (sourceItemId && sourceItemId === primarySourceItemId) {
      return false;
    }

    if (sourceItemId && addonItemIds.has(sourceItemId)) {
      return false;
    }

    return item !== primarySourceItem && getOrderItemProductId(item) && getOrderItemQuantity(item);
  });

  await Promise.all(
    addonItems.map((item) => createCopiedOrderItem(normalizedOrderId, item, createdPrimaryItemId)).filter(Boolean)
  );
  await Promise.all(additionalItems.map((item) => createCopiedOrderItem(normalizedOrderId, item, null)).filter(Boolean));

  await loadOrderItems();
  return true;
};

/** Get customer attributes */
const loadCustomerAttributes = async (customerNumber = customer_id.value) => {
  const normalizedCustomerNumber = resolveCustomerNumber(customerNumber);
  if (!normalizedCustomerNumber) {
    customer_attributes.value = [];
    return customer_attributes.value;
  }

  const response = await getAttributes(normalizedCustomerNumber);
  try {
    if (!response.data.success) {
      return customer_attributes.value;
    }
  } catch (e) {
    return customer_attributes.value;
  }

  if (getSelectedCustomerNumber() !== normalizedCustomerNumber) {
    return customer_attributes.value;
  }
  customer_attributes.value = response.data.data;
  return customer_attributes.value;
};

/** Check if an attribute is set in the customer attributes */
const hasAttribute = (attrib) => {
  // Check if the customer has been loaded
  if (!customer_attributes.value) {
    return false;
  }
  return customer_attributes.value.some((attribute) => attribute.attribute === attrib);
};

const customerRequiresReferenceNumber = () => {
  return hasAttribute("requiresReferenceNumber");
};

const customerUsesPONumbers = () => {
  return hasAttribute("usePONumbers");
};

/** Check if the product category is allowed */
const getProductCategoryRestriction = (category, options = {}) => {
  return getProductCategoryRestrictionForCustomer(category, customer_attributes.value, options);
};

const productCategoryAllowed = (category, options = {}) => {
  return !isProductCategoryRestrictedForCustomer(category, customer_attributes.value, options);
};

/** Check if the customer should be billed per order, or per billing period */
const invoiceAllOrdersIndividually = () => {
  // Check if the customer has the attribute invoiceAllOrdersIndividually
  return hasAttribute("invoiceAllOrdersIndividually");
};

/** Check if the customer should be billed using Stripe */
const invoiceUsingStripe = () => {
  // Check if the customer has the attribute invoiceWithStripe
  return hasAttribute("invoiceWithStripe");
};

/** Check if the customer is allowed to buy spot free products */
const canBuySpotFree = () => {
  // Check if the customer has the attribute restrictSpotFree
  return !hasAttribute("restrictSpotFree");
};

/** Check if the customer is allowed to buy interior cleaning products */
const canBuyInteriorCleaning = () => {
  // Check if the customer has the attribute restrictInteriorCleaning
  return !hasAttribute("restrictInteriorCleaning");
};

/** Check if the customer is allowed to buy tank cleaning products */
const canBuyTankCleaning = () => {
  // Check if the customer has the attribute restrictTankCleaning
  return !hasAttribute("restrictTankCleaning");
};

/** Check if the customer is allowed to buy additional services */
const canBuyAdditionalServices = () => {
  // Check if the customer has the attribute restrictAdditionalServices
  return !hasAttribute("restrictAdditionalServices");
};

/** Check if the customer has the onlyTankCleaning attribute */
const hasOnlyTankCleaning = () => {
  return hasAttribute("onlyTankCleaning");
};

/** Check if a product is restricted based on customer attributes */
const getProductRestriction = (product, options = {}) => {
  return getCustomerProductRestriction(product, customer_attributes.value, options);
};

const isProductRestricted = (product, options = {}) => {
  return isProductRestrictedForCustomer(product, customer_attributes.value, options);
};

const getAddonProductForRestriction = (addon) => {
  const addonProduct = addon?.product || addon || {};
  return {
    ...addonProduct,
    name: addon?.name || addonProduct.name,
    category: addonProduct.category ?? addon?.category,
    category_name: addonProduct.category_name ?? addon?.category_name,
  };
};

/** Check if an addon is restricted based on customer attributes */
const getAddonRestriction = (addon, options = {}) => {
  return getCustomerProductRestriction(getAddonProductForRestriction(addon), customer_attributes.value, {
    includeNumericAddonCategory: true,
    isRelatedAddon: true,
    ...options,
  });
};

const isAddonRestricted = (addon, options = {}) => {
  return getAddonRestriction(addon, options).restricted;
};

function loadOrderDetails(onAfterSuccess = null, options = {}) {
  return getOrderDetails().then(async (response) => {
    console.log(response);
    const selectedDepartmentId = getSelectedDepartmentId(options.departmentId ?? null);
    if (
      response &&
      options.syncDepartmentWithSelection === true &&
      selectedDepartmentId &&
      toPositiveInteger$1(response.department_id) !== selectedDepartmentId
    ) {
      await ensureCurrentOrderDepartment(selectedDepartmentId);
    }
    if (response && onAfterSuccess) {
      onAfterSuccess(response);
    }
    return response;
  });
}

/** Set the order id */
const setOrderId = (id, options = {}) => {
  const selectedDepartmentId = getSelectedDepartmentId(options.departmentId ?? null);
  order_id.value = id;
  // Load the order details
  loadOrderDetails(null, {
    departmentId: selectedDepartmentId,
    syncDepartmentWithSelection: options.syncDepartmentWithSelection !== false,
  });
  if (options.loadItems !== false) {
    // Load the order items
    loadOrderItems();
  }
};

/** Delete everything button */
const deleteEverything = async () => {
  // If the order is created, delete it
  if (order_id.value) {
    const deleted = await SessionUser.objects.orders.functions.deleteWithConfirmation(order_id.value).catch((error) => {
      parseError(error, "stepError");
      return false;
    });
    if (!deleted) {
      return;
    }
  }
  // Clear the cache
  clearCache();
  location.reload();
};

/** Delete everything button dialog */
const showDeleteEverythingDialog = () => {
  Swal.fire({
    title: "Er du sikker?",
    text: "Du er ved at slette alt i denne ordre. Dette kan ikke fortrydes.",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Ja, slet alt",
    cancelButtonText: "Nej, fortryd",
    allowEscapeKey: false,
    allowOutsideClick: false,
    showLoaderOnConfirm: true,
  }).then((result) => {
    if (result.isConfirmed) {
      deleteEverything().then(() => {
        Swal.fire("Slettet", "Ordren er slettet", "success");
      });
    }
  });
};

/** Clear cache */
const clearCache = () => {
  // Reset the query parameters
  pushPosRouteState("step=1");
  // Clear the customer data
  clearCustomerSelection();
  // Clear the order data
  order_id.value = null;
  order_items.value = [];
  // Clear the registration numbers
  reg_1.value = "";
  reg_2.value = "";
  reg_3.value = "";
  order_po.value = "";
  order_safety_seal.value = "";
  clearSelectedOrderBookingSelection();
  // Clear the scans
  scans.value = [];
};

const clearCustomerSelection = () => {
  clearSelectedCustomerState({ clearOrderNotes: true });
};

/** Show delete order dialog */
const showDeleteOrderDialog = () => {
  SessionUser.objects.orders.functions.showDeleteConfirmationModal(order_id.value, () => {
    clearCache();
    location.reload();
  });
};

/** Get users discounts */
const getUserDiscounts = async () => {
  const token = localStorage.getItem("token");
  if (!token) {
    return null;
  }
  return axios
    .get(API_URL + "/superuser/user/discounts", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      params: {
        customer_number: customer_id.value,
      },
    })
    .then((response) => {
      user_discounts.value = response.data.data;
      //console.log(user_discounts.value);
      return user_discounts.value;
    })
    .catch((error) => {
      console.error(error);
    });
};

const ensureUserDiscountsLoaded = () => {
  if (!has_user_discounts_loaded.value) {
    has_user_discounts_loaded.value = true;
    getUserDiscounts().then(() => {});
  }
};

const isDirectCustomerProductDiscount = (discount, productId) => {
  return discount?.product_or_category_id == productId && Number(discount?.is_category) === 0;
};

const parseFixedPriceValue = (value) => {
  if (value === null || value === undefined || value === '') {
    return null;
  }

  const parsed = Number.parseInt(String(value), 10);
  return Number.isFinite(parsed) ? parsed : null;
};

/** Get user product discount */
const getUserProductDiscount = (product, allowCategory = null, onlyCategory = null) => {
  // Check if the user discounts are loaded
  ensureUserDiscountsLoaded();

  // Get the product's id
  const productId = product.id;

  // Get the product's category
  const category = getProductsCategory(productId);

  // Find the specific discount for the product
  let discount = 0;
  let allowCategoryDiscount = null;
  let categoryDiscount = 0;
  let globalDiscount = 0;
  let productDiscount = 0;
  let allowProductDiscount = null;
  let appliedDiscount = 0;

  // Check if we should allow the category discount
  if (allowCategory || allowCategory === null) {
    // If the allowCategory is null, check if the category discount is allowed by the product
    if (allowCategory === null) {
      allowCategoryDiscount = parseInt(product.apply_category_discount) === 1;
    } else if (allowCategory) {
      allowCategoryDiscount = true;
    }
    //console.log('Allow category discount', allowCategoryDiscount);
    //console.log(product);
  }

  // Check if we should allow the product discount
  if (allowCategory === null) {
    allowProductDiscount = true;
  } else {
    allowProductDiscount = allowCategory;
  }

  // Check if we should only allow the category discount
  if (onlyCategory) {
    allowProductDiscount = false;
    //console.log('Only category discount');
  }

  // Get the global discount
  try {
    globalDiscount = parseInt(user_discounts.value.find((discount) => discount.id == "999999").percentage) || null;
  } catch (e) {}
  //console.log('Global discount', globalDiscount);

  try {
    productDiscount =
      parseInt(
        user_discounts.value.find(
          (discount) => discount.product_or_category_id == productId && discount.is_category == "0"
        ).percentage
      ) || null;
  } catch (e) {}
  //console.log('Product discount', productDiscount);

  try {
    categoryDiscount =
      parseInt(
        user_discounts.value.find(
          (discount) => discount.product_or_category_id == category && discount.is_category == "1"
        ).percentage
      ) || null;
  } catch (e) {}
  //console.log('Category discount', categoryDiscount);

  // If we should allow the product discount, apply it
  if (allowProductDiscount && !onlyCategory && productDiscount) {
    appliedDiscount = productDiscount;
  }

  // If the category has a discount, apply it (If the category discount is allowed, and has a higher percentage than the product discount)
  if (categoryDiscount && allowCategoryDiscount && categoryDiscount > appliedDiscount) {
    appliedDiscount = categoryDiscount;
  }

  // If the global discount is higher than the applied discount, apply it
  if (globalDiscount && globalDiscount > appliedDiscount && allowCategoryDiscount) {
    appliedDiscount = globalDiscount;
  }

  // If there's a global discount, and category discounts are allowed, apply the global discount (If it's higher than the applied discount)
  if (globalDiscount && globalDiscount > appliedDiscount && allowCategoryDiscount) {
    appliedDiscount = globalDiscount;
  }

  // If there is no discount, return 0
  if (!appliedDiscount) {
    return 0;
  }

  // Return the applied discount
  //console.log('Applied discount', appliedDiscount);
  return appliedDiscount;
};

const getUserProductFixedPrice = (product) => {
  ensureUserDiscountsLoaded();

  const productId = product?.id;
  if (productId === null || productId === undefined) {
    return null;
  }

  const fixedPriceDiscount = (Array.isArray(user_discounts.value) ? user_discounts.value : []).find((discount) => (
    isDirectCustomerProductDiscount(discount, productId) && parseFixedPriceValue(discount.fixed_price) !== null
  ));

  return fixedPriceDiscount ? parseFixedPriceValue(fixedPriceDiscount.fixed_price) : null;
};

const getUserProductPrice = (product) => {
  const fixedPrice = getUserProductFixedPrice(product);
  if (fixedPrice !== null) {
    return fixedPrice;
  }

  const price = Number(product?.price ?? 0);
  const discount = Number(getUserProductDiscount(product) || 0);
  if (!Number.isFinite(price)) {
    return 0;
  }

  return Number((price - (price * (discount / 100))).toFixed(0));
};

const isPendingOrderItemProduct = (product) => {
  return product && typeof product === "object" && String(product.name ?? product.product_name ?? "").trim() !== "";
};

const clearPendingOrderItems = () => {
  order_items.value = order_items.value.filter((item) => item?._pending !== true);
};

const showPendingCreateOrderItem = (product, quantity, price, relatedItemId = null, notes = "") => {
  if (!isPendingOrderItemProduct(product)) {
    console.warn("Skipping pending order item without product details", product);
    return null;
  }

  const pendingItem = {
    id: `pending-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
    _pending: true,
    product: product,
    product_id: product.id,
    related_item_id: relatedItemId,
    quantity: quantity,
    price: price,
    notes: notes || "",
    reference: "",
  };
  order_items.value.push(pendingItem);
  return pendingItem;
};

const showFakeCreateOrderItem = (product, quantity, price, relatedItemId = null, notes = "") => {
  return showPendingCreateOrderItem(product, quantity, price, relatedItemId, notes);
};

/** Vehicle search functionality */
const vehicles_matching = ref([]);
const isSearching$1 = ref(false);
const latest_search_id = ref(0);
const pendingBookings = ref([]);
const hasLoadedPendingBookings = ref(false);
const isLoadingPendingBookings = ref(false);
let pendingBookingsRequest = null;
let pendingBookingsRequestDepartmentKey = null;
const pendingPlateBookingRequests = new Map();
const loadedPendingBookingPlates = new Set();
let pendingBookingsDepartmentKey = null;

function getPendingBookingsDepartmentKey() {
  return String(department_id.value ?? "");
}

function resetPendingBookingsState(departmentKey = getPendingBookingsDepartmentKey()) {
  pendingBookingsDepartmentKey = departmentKey;
  pendingBookings.value = [];
  hasLoadedPendingBookings.value = false;
  isLoadingPendingBookings.value = false;
  pendingBookingsRequest = null;
  pendingBookingsRequestDepartmentKey = null;
  pendingPlateBookingRequests.clear();
  loadedPendingBookingPlates.clear();
}

function syncPendingBookingsDepartmentState() {
  const currentDepartmentKey = getPendingBookingsDepartmentKey();
  if (pendingBookingsDepartmentKey !== currentDepartmentKey) {
    resetPendingBookingsState(currentDepartmentKey);
  }

  return currentDepartmentKey;
}

const is_latest_search = (search_id) => {
  // Check if the search ID is the latest
  return search_id === latest_search_id.value;
};

// Get the department booking list
const loadPendingBookings = () => {
  const currentDepartmentKey = syncPendingBookingsDepartmentState();

  if (pendingBookingsRequest) {
    return pendingBookingsRequest;
  }

  const requestDepartmentId = department_id.value;
  const requestDepartmentKey = currentDepartmentKey;
  isLoadingPendingBookings.value = true;
  pendingBookingsRequestDepartmentKey = requestDepartmentKey;
  pendingBookingsRequest = SessionUser.request(SessionUser.objects.order_bookings.meta.endpoint, "GET", {
    filters: "department:" + requestDepartmentId + ",order_id:is null",
    page: 1,
    limit: 100,
  })
    .then((response) => {
      if (pendingBookingsDepartmentKey !== requestDepartmentKey) {
        return pendingBookings.value;
      }

      pendingBookings.value = Array.isArray(response?.data?.data) ? response.data.data : [];
      hasLoadedPendingBookings.value = true;
      return pendingBookings.value;
    })
    .catch((error) => {
      console.error("Error:", error);

      if (pendingBookingsDepartmentKey === requestDepartmentKey) {
        hasLoadedPendingBookings.value = true;
      }

      return pendingBookings.value;
    })
    .finally(() => {
      if (pendingBookingsRequestDepartmentKey === requestDepartmentKey) {
        isLoadingPendingBookings.value = false;
        pendingBookingsRequest = null;
        pendingBookingsRequestDepartmentKey = null;
      }
    });

  return pendingBookingsRequest;
};

const getOrderBookingSortDateValue = (booking) => {
  return booking?.datetime ?? booking?.created_at ?? booking?.date ?? null;
};

const hasOrderBookingSortDateValue = (booking) => {
  return Boolean(getOrderBookingSortDateValue(booking));
};

const getOrderBookingSortTimestamp = (booking) => {
  const dateValue = getOrderBookingSortDateValue(booking);
  const parsedValue = dateValue ? Date.parse(dateValue) : Number.NaN;
  if (!Number.isNaN(parsedValue)) {
    return parsedValue;
  }
  const fallbackId = Number.parseInt(String(booking?.id ?? 0), 10);
  return Number.isFinite(fallbackId) ? fallbackId : Number.MAX_SAFE_INTEGER;
};

const sortPendingOrderBookings = (bookings = []) => {
  return [...bookings].sort((left, right) => {
    const leftHasDate = hasOrderBookingSortDateValue(left);
    const rightHasDate = hasOrderBookingSortDateValue(right);
    if (leftHasDate !== rightHasDate) {
      return rightHasDate ? 1 : -1;
    }

    const timeDifference = getOrderBookingSortTimestamp(left) - getOrderBookingSortTimestamp(right);
    if (timeDifference !== 0) {
      return timeDifference;
    }
    return Number.parseInt(String(left?.id ?? 0), 10) - Number.parseInt(String(right?.id ?? 0), 10);
  });
};

const getOrderBookingReferenceValue = (booking) => {
  return String(booking?.reference ?? booking?.reference_number ?? "").trim();
};

const getOrderBookingNotesValue = (booking) => {
  return String(booking?.notes ?? booking?.note ?? "").trim();
};

const getOrderBookingReg1Value = (booking) => {
  return normalizeRegistrationValue(booking?.reg_1 ?? booking?.regNr ?? "");
};

const getOrderBookingReg2Value = (booking) => {
  return normalizeRegistrationValue(booking?.reg_2 ?? booking?.regNrTrailer ?? "");
};

const getOrderBookingCustomerNumber = (booking) => {
  return resolveCustomerNumber(booking?.customer_number ?? booking?.customer_id ?? booking?.customerNumber);
};

const dedupeOrderBookings = (bookings = []) => {
  const bookingsByKey = new Map();

  bookings.filter(Boolean).forEach((booking) => {
    const normalizedBookingId = toPositiveInteger$1(booking?.id);
    const bookingKey =
      normalizedBookingId ??
      [
        normalizeVehiclePlateForBookingSelection(booking?.reg_1),
        normalizeVehiclePlateForBookingSelection(booking?.reg_2),
        booking?.datetime,
        booking?.reference,
        booking?.reference_number,
      ]
        .filter(Boolean)
        .join("|");

    if (!bookingKey || bookingsByKey.has(bookingKey)) {
      return;
    }

    bookingsByKey.set(bookingKey, booking);
  });

  return Array.from(bookingsByKey.values());
};

const mergePendingBookings = (bookings = []) => {
  const mergedBookings = dedupeOrderBookings([...(pendingBookings.value || []), ...(bookings || [])]);
  pendingBookings.value = sortPendingOrderBookings(mergedBookings);
  return pendingBookings.value;
};

const resolveVehiclePlateBookingMatches = (vehiclePlate, bookingMatches = null) => {
  if (Array.isArray(bookingMatches)) {
    return sortPendingOrderBookings(
      dedupeOrderBookings(bookingMatches.filter((booking) => doesOrderBookingMatchCurrentDepartment(booking)))
    );
  }

  return getVehiclePlateBookings(vehiclePlate);
};

const getVehiclePlateBookings = (vehiclePlate) => {
  const normalizedVehiclePlate = normalizeVehiclePlateForBookingSelection(vehiclePlate);
  if (!normalizedVehiclePlate) {
    return [];
  }

  const seenBookingIds = new Set();
  const matchingBookings = pendingBookings.value.filter((booking) => {
    const isMatch =
      normalizeVehiclePlateForBookingSelection(booking?.reg_1) === normalizedVehiclePlate ||
      normalizeVehiclePlateForBookingSelection(booking?.reg_2) === normalizedVehiclePlate;

    if (!isMatch || !doesOrderBookingMatchCurrentDepartment(booking)) {
      return false;
    }

    const normalizedBookingId = toPositiveInteger$1(booking?.id);
    if (!normalizedBookingId) {
      return true;
    }

    if (seenBookingIds.has(normalizedBookingId)) {
      return false;
    }

    seenBookingIds.add(normalizedBookingId);
    return true;
  });

  return sortPendingOrderBookings(matchingBookings);
};

const ensureVehiclePlateBookingsLoaded = async (vehiclePlate, _options = {}) => {
  const normalizedVehiclePlate = normalizeVehiclePlateForBookingSelection(vehiclePlate);
  const currentDepartmentKey = syncPendingBookingsDepartmentState();
  if (!normalizedVehiclePlate || !department_id.value) {
    return [];
  }

  if (loadedPendingBookingPlates.has(normalizedVehiclePlate)) {
    return getVehiclePlateBookings(normalizedVehiclePlate);
  }

  if (pendingPlateBookingRequests.has(normalizedVehiclePlate)) {
    return pendingPlateBookingRequests.get(normalizedVehiclePlate);
  }

  const requestDepartmentId = department_id.value;
  const requestDepartmentKey = currentDepartmentKey;
  const fetchBookingsForField = async (field) => {
    const filters = [`department:${requestDepartmentId}`, `${field}:${normalizedVehiclePlate}`, "order_id:is null"].join(
      ","
    );
    const response = await SessionUser.request(SessionUser.objects.order_bookings.meta.endpoint, "GET", {
      filters,
      page: 1,
      limit: 250,
    });
    return Array.isArray(response?.data?.data) ? response.data.data : [];
  };

  const requestPromise = Promise.all([
    fetchBookingsForField("reg_1"),
    fetchBookingsForField("reg_2"),
  ])
    .then(([reg1Bookings, reg2Bookings]) => {
      if (pendingBookingsDepartmentKey !== requestDepartmentKey) {
        return getVehiclePlateBookings(normalizedVehiclePlate);
      }

      const fetchedBookings = sortPendingOrderBookings(dedupeOrderBookings([...reg1Bookings, ...reg2Bookings]));
      mergePendingBookings(fetchedBookings);
      loadedPendingBookingPlates.add(normalizedVehiclePlate);
      return getVehiclePlateBookings(normalizedVehiclePlate);
    })
    .catch((error) => {
      console.error("Unable to load pending bookings for plate:", normalizedVehiclePlate, error);

      if (pendingBookingsDepartmentKey === requestDepartmentKey) {
        loadedPendingBookingPlates.add(normalizedVehiclePlate);
      }

      return getVehiclePlateBookings(normalizedVehiclePlate);
    })
    .finally(() => {
      if (pendingPlateBookingRequests.get(normalizedVehiclePlate) === requestPromise) {
        pendingPlateBookingRequests.delete(normalizedVehiclePlate);
      }
    });

  pendingPlateBookingRequests.set(normalizedVehiclePlate, requestPromise);
  return requestPromise;
};

const doesVehiclePlateHaveBooking = (vehiclePlate) => {
  return getVehiclePlateBookings(vehiclePlate).length > 0;
};

const getPreferredVehiclePlateBooking = (vehiclePlate) => {
  return getVehiclePlateBookings(vehiclePlate)[0] || null;
};

const getVehiclePlateBooking = (vehiclePlate) => {
  return getPreferredVehiclePlateBooking(vehiclePlate);
};

const getSelectedVehiclePlateBooking = (vehiclePlate, bookingMatches = null) => {
  const normalizedVehiclePlate = normalizeVehiclePlateForBookingSelection(vehiclePlate);
  const normalizedBookingId = toPositiveInteger$1(selectedOrderBookingId.value);
  if (!normalizedVehiclePlate || !normalizedBookingId) {
    return null;
  }

  if (normalizeVehiclePlateForBookingSelection(selectedOrderBookingPlate.value) !== normalizedVehiclePlate) {
    return null;
  }

  const matchingBookings = resolveVehiclePlateBookingMatches(normalizedVehiclePlate, bookingMatches);
  return (
    matchingBookings.find((booking) => toPositiveInteger$1(booking?.id) === normalizedBookingId) || null
  );
};

const doesVehiclePlateRequireBookingSelection = (vehiclePlate, bookingMatches = null) => {
  const normalizedVehiclePlate = normalizeVehiclePlateForBookingSelection(vehiclePlate);
  if (!normalizedVehiclePlate) {
    return false;
  }

  const matchingBookings = resolveVehiclePlateBookingMatches(normalizedVehiclePlate, bookingMatches);
  if (matchingBookings.length <= 1) {
    return false;
  }

  if (isSelectedOrderBookingSkippedForPlate(normalizedVehiclePlate)) {
    return false;
  }

  return !getSelectedVehiclePlateBooking(normalizedVehiclePlate, matchingBookings);
};

const getSelectedPendingOrderBooking = () => {
  const normalizedBookingId = toPositiveInteger$1(selectedOrderBookingId.value);
  if (!normalizedBookingId) {
    return null;
  }

  return (
    pendingBookings.value.find((booking) => toPositiveInteger$1(booking?.id) === normalizedBookingId) || null
  );
};

const fetchOrderBookingProductWithPricing = async (productId) => {
  const normalizedProductId = toPositiveInteger$1(productId);
  if (!normalizedProductId) {
    return null;
  }

  return await SessionUser.objects.products.get.single(normalizedProductId, {
    department_id: department_id.value,
    customer_id: getSelectedCustomerNumber(),
    category_id: null,
    final_price: true,
  });
};

const getFirstAvailableWashProduct = async () => {
  try {
    const products = await SessionUser.objects.products.get.all({
      department_id: department_id.value,
      is_wash: true,
      limit: 1,
    });
    if (!Array.isArray(products) || products.length === 0) {
      return null;
    }
    return await fetchOrderBookingProductWithPricing(products[0].id);
  } catch (error) {
    console.error("Unable to fetch fallback wash product:", error);
    return null;
  }
};

const hydrateSelectedOrderBookingForDesktop = async () => {
  const normalizedOrderId = toPositiveInteger$1(order_id.value);
  const normalizedBookingId = toPositiveInteger$1(selectedOrderBookingId.value);

  if (!normalizedOrderId || !normalizedBookingId) {
    return true;
  }

  try {
    let booking = getSelectedPendingOrderBooking();
    if (!booking || !Array.isArray(booking?.items)) {
      booking = await SessionUser.objects.order_bookings.get.single(normalizedBookingId, {
        department_id: department_id.value,
      });
    }

    if (!booking) {
      return false;
    }

    const bookingCustomerNumber = getOrderBookingCustomerNumber(booking);
    if (bookingCustomerNumber && bookingCustomerNumber !== getSelectedCustomerNumber()) {
      await searchAndSelectCustomer(bookingCustomerNumber);
    }

    const bookingReference = getOrderBookingReferenceValue(booking);
    if (bookingReference !== "" && bookingReference !== reference$1.value) {
      reference$1.value = await saveOrderMetadataField("reference", bookingReference, normalizedOrderId);
    }

    const bookingReg1 = getOrderBookingReg1Value(booking);
    if (bookingReg1 !== "" && bookingReg1 !== reg_1.value) {
      reg_1.value = await saveOrderMetadataField("reg_1", bookingReg1, normalizedOrderId);
    }

    const bookingReg2 = getOrderBookingReg2Value(booking);
    if (bookingReg2 !== reg_2.value) {
      reg_2.value = await saveOrderMetadataField("reg_2", bookingReg2, normalizedOrderId);
    }

    const bookingNotes = getOrderBookingNotesValue(booking);
    if (bookingNotes !== "" && bookingNotes !== order_notes.value) {
      order_notes.value = await saveOrderMetadataField("notes", bookingNotes, normalizedOrderId);
    }

    const bookingPo = String(booking?.po ?? "").trim();
    if (bookingPo !== "" && isBlankPosMetadataValue(order_po.value)) {
      order_po.value = await saveOrderMetadataField("po", bookingPo, normalizedOrderId);
    }

    const currentOrderItems = await loadOrderItems();
    if (Array.isArray(currentOrderItems) && currentOrderItems.length > 0) {
      return true;
    }

    const bookingItems = Array.isArray(booking?.items) ? booking.items : [];
    if (bookingItems.length === 0) {
      return true;
    }

    const primaryRawItem = bookingItems[0];
    const primaryRawProductId = toPositiveInteger$1(primaryRawItem?.id);
    if (!primaryRawProductId) {
      return true;
    }

    let primaryProduct = await fetchOrderBookingProductWithPricing(primaryRawProductId);
    if (!primaryProduct) {
      return true;
    }

    if (!primaryProduct.is_wash) {
      const fallbackWashProduct = await getFirstAvailableWashProduct();
      if (fallbackWashProduct) {
        primaryProduct = fallbackWashProduct;
      }
    }

    const forcedPrimaryPrice = primaryProduct.price ?? null;
    const primaryItemResponse = await createOrderItem(
      normalizedOrderId,
      primaryProduct.id,
      1,
      null,
      null,
      forcedPrimaryPrice
    );
    const relatedPrimaryItemId = toPositiveInteger$1(primaryItemResponse?.data?.data?.id);

    const secondaryBookingItems = bookingItems.slice(1);
    for (const bookingItem of secondaryBookingItems) {
      const secondaryProductId = toPositiveInteger$1(bookingItem?.id);
      if (!secondaryProductId) {
        continue;
      }

      const secondaryProduct = await fetchOrderBookingProductWithPricing(secondaryProductId);

      await createOrderItem(
        normalizedOrderId,
        secondaryProductId,
        Math.max(1, Number.parseInt(String(bookingItem?.quantity ?? 1), 10) || 1),
        relatedPrimaryItemId,
        String(bookingItem?.notes ?? "").trim() || null,
        secondaryProduct?.price ?? null
      );
    }

    await loadOrderItems();
    return true;
  } catch (error) {
    console.error("Unable to hydrate selected desktop order booking:", error);
    parseError(error, "stepError");
    return false;
  }
};

const finalizeSelectedOrderBookingForDesktop = async () => {
  const normalizedOrderId = toPositiveInteger$1(order_id.value);
  const normalizedBookingId = toPositiveInteger$1(selectedOrderBookingId.value);

  if (!normalizedOrderId || !normalizedBookingId) {
    return true;
  }

  try {
    await SessionUser.objects.orders.set.booking_id(normalizedOrderId, normalizedBookingId);
    await SessionUser.objects.order_bookings.set.order_id(normalizedBookingId, normalizedOrderId);
    pendingBookings.value = pendingBookings.value.filter(
      (booking) => toPositiveInteger$1(booking?.id) !== normalizedBookingId
    );
    return true;
  } catch (error) {
    console.error("Unable to complete selected desktop order booking:", error);
    parseError(error, "stepError");
    return false;
  }
};

const get_unregistered_vehicle_object = (reg) => {
  // Generate an id for the unregistered vehicle, this is only used for the dropdown
  let id_prefix = 999999999999;
  let id = id_prefix + Math.floor(Math.random() * 1000000);
  return {
    id: id,
    user_id: null,
    customer_id: null,
    customer_name: "",
    type: null,
    barred: false,
    reg: reg,
    wash_subscription: false,
    addons: {
      enabled: 0,
      available: 0,
      list: [],
    },
    is_known: true,
  };
};

const getUnregisteredVehicleObjects = async (inputValue, search_id) => {
  // Check if the search ID is the latest
  if (!is_latest_search(search_id)) {
    console.log("Search ID is not the latest. Ignoring this search.");
    return [];
  }
  return await SessionUser.request("/department/vehicles/unknown-customer", "GET", {
    search: inputValue,
    page: 1,
    limit: 10,
  })
    .then((response) => {
      console.log("Unregistered vehicles:", response.data.data);
      if (!is_latest_search(search_id)) {
        return [];
      }
      let result = response?.data?.data;
      let unregistered_vehicles = [];
      if (result && result.length > 0) {
        // If there are results, parse them into unregistered_vehicles
        for (let i = 0; i < result.length; i++) {
          // Check if the unregistered vehicle already exists in the vehicles_matching array
          let existingVehicle = vehicles_matching.value.find((vehicle) => vehicle.reg === result[i].reg_1);
          if (existingVehicle) {
            // If it exists, skip adding it again
            continue;
          }
          unregistered_vehicles.push(get_unregistered_vehicle_object(result[i].reg_1));
        }
        console.warn(unregistered_vehicles, search_id, "Parsed unregistered vehicles for search ID");
        return unregistered_vehicles;
      } else {
        return [];
        // Do nothing
      }
    })
    .catch((error) => {
      console.error("Error:", error, search_id);
      return [];
    })
    .finally(() => {
      console.log("Finish search", search_id);
      if (is_latest_search(search_id)) {
        // Set the isSearching flag to false
        isSearching$1.value = false;
      }
    });
};

// Function to register a new search and return the search ID
// This is used to ensure that only the latest search is processed
const register_new_search = () => {
  let search_id = Date.now();
  // Set the latest search ID to the current search ID
  latest_search_id.value = search_id;
  return search_id;
};

const reg_1_status = ref("unknown");
const reg_2_status = ref("unknown");
const reg_3_status = ref("unknown");

// Function to search for vehicles
const searchVehicle = async (inputValue, search_id) => {
  // Check if the search ID is the latest
  if (!is_latest_search(search_id)) {
    console.log("Search ID is not the latest. Ignoring this search.");
    return;
  }
  // Set the isSearching flag to true
  isSearching$1.value = true;
  // Perform the search
  SessionUser.request(SessionUser.objects.vehicles.meta.endpoint + "/search", "GET", {
    search: inputValue,
    ...(department_id.value ? { department: department_id.value } : {}),
    page: 1,
    limit: 10,
  }).then((response) => {
    // Check if the registration number is already in the vehicles_matching array
    if (!is_latest_search(search_id)) {
      return;
    }
    let result = response?.data?.data;
    if (result && result.length > 0) {
      // If there are results, parse them into vehicles_matching
      if (!is_latest_search(search_id)) {
        return;
      }
      vehicles_matching.value = result;
    }
  });
};

const attachments = ref([]);

const fetchAttachments = async (orderId) => {
  if (!orderId) {
    return [];
  }
  return await SessionUser.objects.orders.functions
    .fetchAttachments(order_id.value)
    .then((response) => {
      attachments.value = response;
      return attachments.value;
    })
    .catch((error) => {
      console.error("Error fetching attachments:", error);
      return [];
    });
};

const deleteAttachment = async (attachmentId) => {
  if (!attachmentId) {
    return false;
  }
  return await SessionUser.objects.orders.functions
    .removeAttachment(order_id.value, attachmentId)
    .then((response) => {
      // Remove the attachment from the attachments array
      attachments.value = attachments.value.filter((attachment) => attachment.id !== attachmentId);
      return true;
    })
    .catch((error) => {
      console.error("Error deleting attachment:", error);
      return false;
    });
};

const uploadAttachment = async (file = { filename: "", base64String: "" }) => {
  if (!file || !file.filename || !file.base64String) {
    return false;
  }
  return await SessionUser.objects.orders.functions
    .uploadAttachment(order_id.value, file.filename, file.base64String)
    .then((response) => {
      // Add the attachment to the attachments
      attachments.value.push(response);
      return true;
    })
    .catch((error) => {
      console.error("Error uploading attachment:", error);
      return false;
    });
};

const downloadAttachment = (attachmentId, orderId = null) => {
  if (!attachmentId) {
    return false;
  }
  return SessionUser.objects.orders.functions
    .downloadAttachment(orderId ? orderId : order_id.value, attachmentId)
    .then((response) => {
      // Create a link element
      const link = document.createElement("a");
      link.href = response;
      link.download = response.filename;
      link.style.display = "none";
      link.target = "_blank";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      return true;
    })
    .catch((error) => {
      console.error("Error downloading attachment:", error);
      return false;
    });
};

const getAttachmentPreviewLink = (attachmentId) => {
  if (!attachmentId) {
    return null;
  }
  return SessionUser.objects.orders.functions
    .downloadAttachment(order_id.value, attachmentId)
    .then((response) => {
      if (!response || typeof response !== "string") {
        return null;
      }

      try {
        const parsedUrl = new URL(response);
        parsedUrl.searchParams.set("preview", "true");
        return parsedUrl.toString();
      } catch {
        const separator = response.includes("?") ? "&" : "?";
        return `${response}${separator}preview=true`;
      }
    })
    .catch((error) => {
      console.error("Error getting attachment preview link:", error);
      return null;
    });
};

const _sfc_main$1X = {};
const POSDepartmentProcess = /*#__PURE__*/_export_sfc(_sfc_main$1X, [['__file',"POSDepartmentProcess.vue"]]);

const _sfc_main$1W = {
  __name: 'RequiresPermission',
  props: {
  permission: {
    type: String,
    required: true,
  },
  trackMissingPermission: {
    type: Boolean,
    default: false,
  },
  trackingSource: {
    type: String,
    default: "",
  },
  allowSuperuser: {
    type: Boolean,
    default: false,
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;
const slots = useSlots();

// Show an error if the permission prop is not provided
if (!props.permission) {
  console.error('The permission prop is required for the requiresPermission component');
}

const hasAccess = computed(() => {
  if (props.allowSuperuser && typeof SessionUser.canAccessSuperUser === "function" && SessionUser.canAccessSuperUser()) {
    return true;
  }
  return SessionUser.hasPermission(props.permission);
});

watch(
  hasAccess,
  (value) => {
    if (value || !props.trackMissingPermission) {
      return;
    }
    reportComponentMissingPermission(props.permission, {
      source: props.trackingSource || null,
    });
  },
  { immediate: true }
);

const __returned__ = { props, slots, hasAccess, SessionUser, computed, useSlots, watch, get reportComponentMissingPermission() { return reportComponentMissingPermission } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$10 = { key: 0 };
const _hoisted_2$Q = { key: 1 };

function _sfc_render$1b(_ctx, _cache, $props, $setup, $data, $options) {
  return ($setup.hasAccess)
    ? (openBlock(), createElementBlock("div", _hoisted_1$10, [
        renderSlot(_ctx.$slots, "default")
      ]))
    : ($setup.slots.fail)
      ? (openBlock(), createElementBlock("div", _hoisted_2$Q, [
          renderSlot(_ctx.$slots, "fail")
        ]))
      : createCommentVNode("v-if", true)
}
const RequiresPermission = /*#__PURE__*/_export_sfc(_sfc_main$1W, [['render',_sfc_render$1b],['__file',"RequiresPermission.vue"]]);

// The discounts

const _sfc_main$1V = {
  __name: 'CustomerDiscountsDepartmentDisplay',
  setup(__props, { expose: __expose }) {
  __expose();

const discounts = ref([]);
// The sorted discounts
const sorted_discounts = ref([]);
// Check if a customer is selected
const isCustomerSelected = ref(false);


const onCustomerChange = () => {
  if (parseInt(customer_id.value) > 0) {
    getUserDiscounts(customer_id.value).then((discounts_res) => {
      console.log(discounts_res);
      // Set the discounts
      discounts.value = discounts_res;
    });
    isCustomerSelected.value = true;
    return;
  }
  isCustomerSelected.value = false;
};

const parseFixedPriceValue = (value) => {
  if (value === null || value === undefined || value === '') {
    return null;
  }

  const parsed = Number.parseInt(String(value), 10);
  return Number.isFinite(parsed) ? parsed : null;
};

const formatNumber = (value) => Number.isInteger(value) ? String(value) : value.toFixed(2);

const parseValue = (discount) => {
  const fixedPrice = parseFixedPriceValue(discount.fixed_price);
  if (fixedPrice !== null) {
    return `${formatNumber(fixedPrice)} Kr.`;
  }

  let tmp_value = parseFloat(discount.percentage).toFixed(2);
  // Add the percentage sign
  return `${tmp_value}%`;
};

const parseDiscountDisplayName = (discount) => {
  // Check if the discount is a global discount
  if (discount.product_or_category_id === 'global') {
    return 'E-conomic rabatsats';
  }
  // Check if the discount is a category discount
  if (discount.is_category === '1') {
    // Get the category name
    return SessionUser.objects.categories.functions.getCategoryName(discount.product_or_category_id);
  }
  // Otherwise, it's a product discount
  return SessionUser.objects.products.functions.getProductName(discount.product_or_category_id);
};

const sortDiscounts = () => {
  const tmp_sorted = [];
  // There is technically only one global discount, but to remain consistent with the other discounts, we'll filter it out.
  const global_discounts = discounts.value.filter((discount) => discount.product_or_category_id === 'global');
  // Category discounts
  const category_discounts = discounts.value.filter((discount) => discount.is_category === '1' && discount.product_or_category_id !== 'global');
  // Product discounts
  const product_discounts = discounts.value.filter((discount) => discount.is_category === '0');

  // Add the global discount first
  tmp_sorted.push(...global_discounts);
  tmp_sorted.push(...category_discounts);
  tmp_sorted.push(...product_discounts);

  // Update the discounts
  sorted_discounts.value = tmp_sorted;
};

watch(discounts, sortDiscounts, { immediate: true });
watch(customer_id, onCustomerChange, { immediate: true });

const __returned__ = { discounts, sorted_discounts, isCustomerSelected, onCustomerChange, parseFixedPriceValue, formatNumber, parseValue, parseDiscountDisplayName, sortDiscounts, ref, watch, getUserDiscounts, user_discounts, customer_id, SessionUser };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$$ = {
  key: 0,
  style: {"width":"100%"}
};
const _hoisted_2$P = { class: "column is-8" };
const _hoisted_3$K = { class: "is-flex-wrap-nowrap" };
const _hoisted_4$J = { class: "column is-4 has-text-right is-float-right" };

function _sfc_render$1a(_ctx, _cache, $props, $setup, $data, $options) {
  return ($setup.isCustomerSelected)
    ? (openBlock(), createElementBlock("div", _hoisted_1$$, [
        (openBlock(true), createElementBlock(Fragment, null, renderList($setup.sorted_discounts, (discount) => {
          return (openBlock(), createElementBlock("div", {
            class: "columns is-vcentered",
            key: discount.id
          }, [
            createBaseVNode("div", _hoisted_2$P, [
              createBaseVNode("span", _hoisted_3$K, toDisplayString($setup.parseDiscountDisplayName(discount)), 1 /* TEXT */)
            ]),
            createBaseVNode("div", _hoisted_4$J, [
              createCommentVNode("<span class=\"icon is-small mr-1\">\n          <i class=\"fas fa-percent\" aria-hidden=\"true\"></i>\n        </span> "),
              createBaseVNode("span", null, toDisplayString($setup.parseValue(discount)), 1 /* TEXT */)
            ])
          ]))
        }), 128 /* KEYED_FRAGMENT */))
      ]))
    : createCommentVNode("v-if", true)
}
const CustomerDiscountsDepartmentDisplay = /*#__PURE__*/_export_sfc(_sfc_main$1V, [['render',_sfc_render$1a],['__file',"CustomerDiscountsDepartmentDisplay.vue"]]);

const _sfc_main$1U = {
  __name: 'ExpandableContentBox',
  props: {
  expanded: {
    type: Boolean,
    default: false,
  },
},
  emits: ['update:expanded'],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const props = __props;
const emit = __emit;
const expandIcon = ref(null);
const toggleIsSelected = () => {
  emit('update:expanded', !props.expanded);
};

const __returned__ = { props, emit, expandIcon, toggleIsSelected, ref };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$_ = { class: "expandable-content-box" };
const _hoisted_2$O = { key: 0 };
const _hoisted_3$J = { class: "column is-12-desktop" };
const _hoisted_4$I = {
  class: "icon is-small",
  style: {"color":"#c7c7c7"}
};

function _sfc_render$19(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$_, [
    ($setup.props.expanded)
      ? (openBlock(), createElementBlock("div", _hoisted_2$O, [
          renderSlot(_ctx.$slots, "expandedContent")
        ]))
      : createCommentVNode("v-if", true),
    createCommentVNode(" Expander "),
    createBaseVNode("div", _hoisted_3$J, [
      createBaseVNode("p", {
        class: "has-text-centered",
        onClick: $setup.toggleIsSelected,
        onMouseover: _cache[0] || (_cache[0] = $event => ($setup.expandIcon.classList.add('has-text-link'))),
        onMouseleave: _cache[1] || (_cache[1] = $event => ($setup.expandIcon.classList.remove('has-text-link')))
      }, [
        createBaseVNode("span", _hoisted_4$I, [
          createBaseVNode("i", {
            class: normalizeClass(["fas fa-angle-down fa-lg", { 'fa-rotate-180': $setup.props.expanded }]),
            "aria-hidden": "true",
            ref: "expandIcon"
          }, null, 2 /* CLASS */)
        ])
      ], 32 /* NEED_HYDRATION */)
    ])
  ]))
}
const ExpandableContentBox = /*#__PURE__*/_export_sfc(_sfc_main$1U, [['render',_sfc_render$19],['__file',"ExpandableContentBox.vue"]]);

const CUSTOMER_RULE_DEFINITIONS = Object.freeze([
  {
    attribute: "restrictAdditionalServices",
    group: "category",
    sortOrder: 10,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.restrictAdditionalServices.label",
    descriptionKey: "customer_rules.attributes.restrictAdditionalServices.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
    productImpact: true,
  },
  {
    attribute: "restrictTankCleaning",
    group: "category",
    sortOrder: 20,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.restrictTankCleaning.label",
    descriptionKey: "customer_rules.attributes.restrictTankCleaning.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
    productImpact: true,
  },
  {
    attribute: "restrictSpotFree",
    group: "category",
    sortOrder: 30,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.restrictSpotFree.label",
    descriptionKey: "customer_rules.attributes.restrictSpotFree.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
    productImpact: true,
  },
  {
    attribute: "restrictInteriorCleaning",
    group: "category",
    sortOrder: 40,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.restrictInteriorCleaning.label",
    descriptionKey: "customer_rules.attributes.restrictInteriorCleaning.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
    productImpact: true,
  },
  {
    attribute: "onlyTankCleaning",
    group: "category",
    sortOrder: 50,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.onlyTankCleaning.label",
    descriptionKey: "customer_rules.attributes.onlyTankCleaning.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
    productImpact: true,
  },
  {
    attribute: "requiresReferenceNumber",
    group: "workflow",
    sortOrder: 60,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.requiresReferenceNumber.label",
    descriptionKey: "customer_rules.attributes.requiresReferenceNumber.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
  },
  {
    attribute: "requiresRegistrationNumbersInvoice",
    group: "workflow",
    sortOrder: 70,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.requiresRegistrationNumbersInvoice.label",
    descriptionKey: "customer_rules.attributes.requiresRegistrationNumbersInvoice.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
  },
  {
    attribute: "invoiceAllOrdersIndividually",
    group: "workflow",
    sortOrder: 80,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.invoiceAllOrdersIndividually.label",
    descriptionKey: "customer_rules.attributes.invoiceAllOrdersIndividually.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
  },
  {
    attribute: "invoiceWithStripe",
    group: "workflow",
    sortOrder: 90,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.invoiceWithStripe.label",
    descriptionKey: "customer_rules.attributes.invoiceWithStripe.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
  },
  {
    attribute: "showPricesOnBookingPage",
    group: "workflow",
    sortOrder: 100,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.showPricesOnBookingPage.label",
    descriptionKey: "customer_rules.attributes.showPricesOnBookingPage.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
  },
  {
    attribute: "usePONumbers",
    group: "workflow",
    sortOrder: 110,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.usePONumbers.label",
    descriptionKey: "customer_rules.attributes.usePONumbers.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
  },
  {
    attribute: "exemptFromAdministrationFee",
    group: "workflow",
    sortOrder: 120,
    icon: "fas fa-cogs",
    labelKey: "customer_rules.attributes.exemptFromAdministrationFee.label",
    descriptionKey: "customer_rules.attributes.exemptFromAdministrationFee.description",
    addPermission: "add_customer_attribute",
    deletePermission: "delete_customer_attribute",
  },
]);

const getCustomerRuleDefinitions = () => CUSTOMER_RULE_DEFINITIONS;

const getCustomerRuleDefinition = (attribute) =>
  CUSTOMER_RULE_DEFINITIONS.find((rule) => rule.attribute === attribute) ?? null;

const getCustomerRuleAttributeKey = (attributeEntry) => {
  if (typeof attributeEntry === "string") {
    const normalizedKey = attributeEntry.trim();
    return normalizedKey || "";
  }

  if (attributeEntry && typeof attributeEntry === "object") {
    const normalizedKey = String(attributeEntry.attribute ?? attributeEntry.key ?? "").trim();
    return normalizedKey || "";
  }

  return "";
};

const getCustomerRuleAttributeKeys = (attributeEntries = []) => (
  Array.isArray(attributeEntries)
    ? attributeEntries
      .map((entry) => getCustomerRuleAttributeKey(entry))
      .filter(Boolean)
    : []
);

const PRODUCT_GROUPS = Object.freeze([
  {
    key: "primaryProducts",
    labelKey: "customer_rules.tooltip.groups.primary_products",
  },
  {
    key: "relatedAddons",
    labelKey: "customer_rules.tooltip.groups.related_addons",
  },
  {
    key: "standaloneAdditionalServices",
    labelKey: "customer_rules.tooltip.groups.standalone_additional_services",
  },
]);

const normalizeProductId = (value) => {
  const parsed = Number.parseInt(String(value ?? ""), 10);
  return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
};

const normalizeProductName = (product) => String(product?.name ?? product?.product_name ?? "").trim();

const sortProductsByDisplayOrder = (products) =>
  [...products].sort((left, right) => {
    const leftPriority = Number(left?.order_priority ?? 0);
    const rightPriority = Number(right?.order_priority ?? 0);
    if (leftPriority !== rightPriority) {
      return leftPriority - rightPriority;
    }

    return normalizeProductName(left).localeCompare(normalizeProductName(right));
  });

const normalizeRuleProductList = (products = []) => {
  if (!Array.isArray(products)) {
    return [];
  }

  const seen = new Set();
  return sortProductsByDisplayOrder(products)
    .filter((product) => {
      const productId = normalizeProductId(product?.id ?? product?.product_id);
      if (productId === null || seen.has(productId)) {
        return false;
      }

      seen.add(productId);
      return normalizeProductName(product) !== "";
    });
};

const addonToProduct = (addon, parentProduct) => {
  const addonProduct = addon?.product || {};
  const addonId = normalizeProductId(addon?.option_id ?? addonProduct.id ?? addon?.id);

  return {
    ...addonProduct,
    id: addonId ?? addonProduct.id ?? addon?.id,
    name: addon?.name || addonProduct.name,
    category: addonProduct.category ?? addon?.category,
    category_name: addonProduct.category_name ?? addon?.category_name,
    order_priority: addonProduct.order_priority ?? addon?.order_priority ?? parentProduct?.order_priority,
    parentProductName: normalizeProductName(parentProduct),
  };
};

const flattenRelatedAddons = (products) =>
  products.flatMap((product) => (
    Array.isArray(product?.addons)
      ? product.addons.map((addon) => addonToProduct(addon, product))
      : []
  ));

const buildAttributeSet = (attribute) => [{ attribute }];

const productIsRestrictedByAttribute = (product, attribute, options = {}) => (
  getCustomerProductRestriction(product, buildAttributeSet(attribute), options).rule === attribute
);

const emptyGroups = () => ({
  primaryProducts: [],
  relatedAddons: [],
  standaloneAdditionalServices: [],
});

const groupedRestrictedProducts = (attribute, products) => {
  const normalizedProducts = normalizeRuleProductList(products);
  const relatedAddons = normalizeRuleProductList(flattenRelatedAddons(normalizedProducts));
  const standaloneCandidates = normalizeRuleProductList(
    normalizedProducts.filter((product) => isStandaloneAdditionalServiceCatalogProduct(product))
  );

  return {
    primaryProducts: normalizedProducts.filter((product) => productIsRestrictedByAttribute(product, attribute)),
    relatedAddons: relatedAddons.filter((product) => productIsRestrictedByAttribute(product, attribute, {
      includeNumericAddonCategory: true,
      isRelatedAddon: true,
    })),
    standaloneAdditionalServices: standaloneCandidates.filter((product) =>
      productIsRestrictedByAttribute(product, attribute, {
        includeNumericAddonCategory: true,
        isStandaloneAdditionalService: true,
      })
    ),
  };
};

const groupedAllowedOnlyTankCleaningProducts = (products) => ({
  primaryProducts: normalizeRuleProductList(products).filter((product) => isTankCleaningProduct(product)),
  relatedAddons: normalizeRuleProductList(flattenRelatedAddons(products)).filter((product) => isTankCleaningProduct(product)),
  standaloneAdditionalServices: [],
});

const getCustomerRuleProductImpact = (attribute, products = []) => {
  const definition = getCustomerRuleDefinition(attribute);
  if (!definition?.productImpact) {
    return {
      hasProductImpact: false,
      blocked: emptyGroups(),
      available: emptyGroups(),
    };
  }

  const normalizedProducts = normalizeRuleProductList(products);
  const blocked = groupedRestrictedProducts(attribute, normalizedProducts);
  const available = attribute === "onlyTankCleaning"
    ? groupedAllowedOnlyTankCleaningProducts(normalizedProducts)
    : emptyGroups();

  return {
    hasProductImpact: true,
    groups: PRODUCT_GROUPS,
    blocked,
    available,
  };
};

const groupHasProducts = (groupedProducts = {}) => (
  PRODUCT_GROUPS.some((group) => (groupedProducts[group.key] || []).length > 0)
);

const getCustomerRuleTooltipModel = (attribute, options = {}) => {
  const definition = getCustomerRuleDefinition(attribute);
  if (!definition) {
    return null;
  }

  const productImpact = getCustomerRuleProductImpact(attribute, options.products || []);

  return {
    attribute,
    active: options.active === true,
    definition,
    descriptionKey: definition.descriptionKey,
    hasProductImpact: productImpact.hasProductImpact,
    groups: productImpact.groups || PRODUCT_GROUPS,
    blocked: productImpact.blocked,
    available: productImpact.available,
  };
};

const productCatalogCache = new Map();
const productCatalogRequests = new Map();

const normalizePositiveInteger$2 = (value) => {
  const parsed = Number.parseInt(String(value ?? ""), 10);
  return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
};

const normalizeProductsResponse = (response) => {
  if (Array.isArray(response?.data?.data)) {
    return response.data.data;
  }

  if (Array.isArray(response?.data)) {
    return response.data;
  }

  if (Array.isArray(response)) {
    return response;
  }

  return [];
};

const getCustomerRuleProductCatalogCacheKey = ({ departmentId = null, customerNumber = null } = {}) => {
  const normalizedDepartmentId = normalizePositiveInteger$2(departmentId);
  const normalizedCustomerNumber = normalizePositiveInteger$2(customerNumber);

  return [
    normalizedDepartmentId ? `department:${normalizedDepartmentId}` : "department:global",
    normalizedCustomerNumber ? `customer:${normalizedCustomerNumber}` : "customer:global",
  ].join("|");
};

const loadCustomerRuleProductCatalog = async ({ departmentId = null, customerNumber = null } = {}) => {
  const normalizedDepartmentId = normalizePositiveInteger$2(departmentId);
  const normalizedCustomerNumber = normalizePositiveInteger$2(customerNumber);
  const cacheKey = getCustomerRuleProductCatalogCacheKey({
    departmentId: normalizedDepartmentId,
    customerNumber: normalizedCustomerNumber,
  });

  if (productCatalogCache.has(cacheKey)) {
    return productCatalogCache.get(cacheKey);
  }

  if (productCatalogRequests.has(cacheKey)) {
    return productCatalogRequests.get(cacheKey);
  }

  const request = SessionUser.objects.products.get.all({
    ...(normalizedDepartmentId ? { department_id: normalizedDepartmentId } : {}),
    ...(normalizedCustomerNumber ? { customer_id: normalizedCustomerNumber } : {}),
    final_price: false,
  })
    .then((response) => {
      const products = normalizeProductsResponse(response);
      productCatalogCache.set(cacheKey, products);
      return products;
    })
    .finally(() => {
      productCatalogRequests.delete(cacheKey);
    });

  productCatalogRequests.set(cacheKey, request);
  return request;
};

const clearCustomerRuleProductCatalogCache = () => {
  productCatalogCache.clear();
  productCatalogRequests.clear();
};

const _sfc_main$1T = {
  __name: 'CustomerRuleTooltip',
  props: {
  active: {
    type: Boolean,
    default: false,
  },
  attribute: {
    type: String,
    required: true,
  },
  customerNumber: {
    type: [Number, String],
    default: null,
  },
  departmentId: {
    type: [Number, String],
    default: null,
  },
  position: {
    type: String,
    default: "is-bottom",
  },
  products: {
    type: Array,
    default: null,
  },
  testId: {
    type: String,
    default: "",
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;

const { t } = useI18n({ useScope: "global" });

const catalogProducts = ref([]);
const isLoading = ref(false);
const loadFailed = ref(false);
const isTooltipOpen = ref(false);
const triggerHovered = ref(false);
const contentHovered = ref(false);
const focusWithinTooltip = ref(false);
const tooltipRef = ref(null);
let loadRequestId = 0;
let closeTimer = null;

const hasProvidedProducts = computed(() => Array.isArray(props.products));
const effectiveProducts = computed(() => (hasProvidedProducts.value ? props.products : catalogProducts.value));
const tooltipModel = computed(() => getCustomerRuleTooltipModel(props.attribute, {
  active: props.active,
  products: effectiveProducts.value,
}));
const hasTooltip = computed(() => tooltipModel.value !== null);
const shouldLoadProducts = computed(() => (
  hasTooltip.value &&
  tooltipModel.value.hasProductImpact &&
  !hasProvidedProducts.value &&
  !isLoading.value &&
  catalogProducts.value.length === 0 &&
  !loadFailed.value
));

const blockedTitleKey = computed(() => (
  props.active
    ? "customer_rules.tooltip.blocked_now"
    : "customer_rules.tooltip.blocked_if_enabled"
));
const availableTitleKey = computed(() => (
  props.active
    ? "customer_rules.tooltip.available_while_enabled"
    : "customer_rules.tooltip.available_if_enabled"
));

const listTestId = (sectionKey, groupKey) => (
  props.testId
    ? `${props.testId}-${sectionKey}-${groupKey}`
    : `customer-rule-tooltip-${props.attribute}-${sectionKey}-${groupKey}`
);

const ensureProductsLoaded = async () => {
  if (!shouldLoadProducts.value) {
    return;
  }

  const requestId = ++loadRequestId;
  isLoading.value = true;
  loadFailed.value = false;

  try {
    const products = await loadCustomerRuleProductCatalog({
      departmentId: props.departmentId,
      customerNumber: props.customerNumber,
    });

    if (requestId === loadRequestId) {
      catalogProducts.value = products;
    }
  } catch (error) {
    console.warn("Unable to load products for customer rule tooltip", error);
    if (requestId === loadRequestId) {
      loadFailed.value = true;
    }
  } finally {
    if (requestId === loadRequestId) {
      isLoading.value = false;
    }
  }
};

const clearCloseTimer = () => {
  if (closeTimer) {
    clearTimeout(closeTimer);
    closeTimer = null;
  }
};

const updateTooltipPosition = async () => {
  await nextTick();
  tooltipRef.value?.updateAppendToBody?.();
};

const openTooltip = () => {
  clearCloseTimer();
  isTooltipOpen.value = true;
  ensureProductsLoaded();
  updateTooltipPosition();
};

const closeTooltip = () => {
  clearCloseTimer();
  triggerHovered.value = false;
  contentHovered.value = false;
  focusWithinTooltip.value = false;
  isTooltipOpen.value = false;
};

const scheduleTooltipClose = () => {
  clearCloseTimer();
  closeTimer = setTimeout(() => {
    closeTimer = null;
    if (!triggerHovered.value && !contentHovered.value && !focusWithinTooltip.value) {
      isTooltipOpen.value = false;
    }
  }, 180);
};

const onTriggerMouseEnter = () => {
  triggerHovered.value = true;
  openTooltip();
};

const onTriggerMouseLeave = () => {
  triggerHovered.value = false;
  scheduleTooltipClose();
};

const onContentMouseEnter = () => {
  contentHovered.value = true;
  openTooltip();
};

const onContentMouseLeave = () => {
  contentHovered.value = false;
  scheduleTooltipClose();
};

const onTooltipFocusIn = () => {
  focusWithinTooltip.value = true;
  openTooltip();
};

const onTooltipFocusOut = () => {
  focusWithinTooltip.value = false;
  scheduleTooltipClose();
};

watch(
  () => [props.attribute, props.customerNumber, props.departmentId],
  () => {
    closeTooltip();
    if (!hasProvidedProducts.value) {
      catalogProducts.value = [];
      loadFailed.value = false;
    }
  }
);

onBeforeUnmount(() => {
  clearCloseTimer();
});

const __returned__ = { props, t, catalogProducts, isLoading, loadFailed, isTooltipOpen, triggerHovered, contentHovered, focusWithinTooltip, tooltipRef, get loadRequestId() { return loadRequestId }, set loadRequestId(v) { loadRequestId = v; }, get closeTimer() { return closeTimer }, set closeTimer(v) { closeTimer = v; }, hasProvidedProducts, effectiveProducts, tooltipModel, hasTooltip, shouldLoadProducts, blockedTitleKey, availableTitleKey, listTestId, ensureProductsLoaded, clearCloseTimer, updateTooltipPosition, openTooltip, closeTooltip, scheduleTooltipClose, onTriggerMouseEnter, onTriggerMouseLeave, onContentMouseEnter, onContentMouseLeave, onTooltipFocusIn, onTooltipFocusOut, computed, nextTick, onBeforeUnmount, ref, watch, get BTooltip() { return Tooltip$1 }, get useI18n() { return useI18n }, get getCustomerRuleTooltipModel() { return getCustomerRuleTooltipModel }, get groupHasProducts() { return groupHasProducts }, get loadCustomerRuleProductCatalog() { return loadCustomerRuleProductCatalog } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$Z = ["data-testid", "onKeydown"];
const _hoisted_2$N = { class: "customer-rule-tooltip__section" };
const _hoisted_3$I = { class: "customer-rule-tooltip__heading" };
const _hoisted_4$H = {
  key: 0,
  class: "customer-rule-tooltip__state"
};
const _hoisted_5$G = {
  key: 1,
  class: "customer-rule-tooltip__state customer-rule-tooltip__state--error"
};
const _hoisted_6$D = { class: "customer-rule-tooltip__section" };
const _hoisted_7$B = { class: "customer-rule-tooltip__heading" };
const _hoisted_8$A = { class: "customer-rule-tooltip__group-title" };
const _hoisted_9$y = ["data-testid"];
const _hoisted_10$x = { key: 1 };
const _hoisted_11$s = {
  key: 0,
  class: "customer-rule-tooltip__section"
};
const _hoisted_12$q = { class: "customer-rule-tooltip__heading" };
const _hoisted_13$o = { class: "customer-rule-tooltip__group-title" };
const _hoisted_14$m = ["data-testid"];
const _hoisted_15$l = ["data-testid", "onKeydown"];

function _sfc_render$18(_ctx, _cache, $props, $setup, $data, $options) {
  return ($setup.hasTooltip)
    ? (openBlock(), createBlock($setup["BTooltip"], {
        key: 0,
        ref: "tooltipRef",
        class: "customer-rule-tooltip",
        active: $setup.isTooltipOpen,
        triggers: [],
        position: $props.position,
        "content-class": "customer-rule-tooltip__panel",
        type: "is-dark",
        multilined: "",
        "append-to-body": "",
        always: "",
        "auto-close": false
      }, {
        content: withCtx(() => [
          createBaseVNode("div", {
            class: "customer-rule-tooltip__content",
            tabindex: "-1",
            "data-testid": $props.testId ? `${$props.testId}-content` : `customer-rule-tooltip-${$props.attribute}`,
            onMouseenter: $setup.onContentMouseEnter,
            onMouseleave: $setup.onContentMouseLeave,
            onFocusin: $setup.onTooltipFocusIn,
            onFocusout: $setup.onTooltipFocusOut,
            onKeydown: withKeys(withModifiers($setup.closeTooltip, ["stop","prevent"]), ["escape"])
          }, [
            createBaseVNode("div", _hoisted_2$N, [
              createBaseVNode("strong", _hoisted_3$I, toDisplayString($setup.t("customer_rules.tooltip.changes")), 1 /* TEXT */),
              createBaseVNode("p", null, toDisplayString($setup.t($setup.tooltipModel.descriptionKey)), 1 /* TEXT */)
            ]),
            ($setup.tooltipModel.hasProductImpact)
              ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                  ($setup.isLoading)
                    ? (openBlock(), createElementBlock("div", _hoisted_4$H, toDisplayString($setup.t("customer_rules.tooltip.loading_products")), 1 /* TEXT */))
                    : ($setup.loadFailed)
                      ? (openBlock(), createElementBlock("div", _hoisted_5$G, toDisplayString($setup.t("customer_rules.tooltip.load_failed")), 1 /* TEXT */))
                      : (openBlock(), createElementBlock(Fragment, { key: 2 }, [
                          createBaseVNode("div", _hoisted_6$D, [
                            createBaseVNode("strong", _hoisted_7$B, toDisplayString($setup.t($setup.blockedTitleKey)), 1 /* TEXT */),
                            ($setup.groupHasProducts($setup.tooltipModel.blocked))
                              ? (openBlock(true), createElementBlock(Fragment, { key: 0 }, renderList($setup.tooltipModel.groups, (group) => {
                                  return (openBlock(), createElementBlock("div", {
                                    key: `blocked-${group.key}`,
                                    class: "customer-rule-tooltip__group"
                                  }, [
                                    (($setup.tooltipModel.blocked[group.key] || []).length > 0)
                                      ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                                          createBaseVNode("span", _hoisted_8$A, toDisplayString($setup.t(group.labelKey)), 1 /* TEXT */),
                                          createBaseVNode("ul", {
                                            class: "customer-rule-tooltip__blocked-list",
                                            "data-testid": $setup.listTestId('blocked', group.key)
                                          }, [
                                            (openBlock(true), createElementBlock(Fragment, null, renderList($setup.tooltipModel.blocked[group.key], (product) => {
                                              return (openBlock(), createElementBlock("li", {
                                                key: `${group.key}-${product.id}`,
                                                class: "customer-rule-tooltip__blocked-product"
                                              }, [
                                                _cache[0] || (_cache[0] = createBaseVNode("span", {
                                                  class: "customer-rule-tooltip__blocked-prefix",
                                                  "aria-hidden": "true"
                                                }, "-", -1 /* CACHED */)),
                                                createBaseVNode("span", null, toDisplayString(product.name || product.product_name), 1 /* TEXT */)
                                              ]))
                                            }), 128 /* KEYED_FRAGMENT */))
                                          ], 8 /* PROPS */, _hoisted_9$y)
                                        ], 64 /* STABLE_FRAGMENT */))
                                      : createCommentVNode("v-if", true)
                                  ]))
                                }), 128 /* KEYED_FRAGMENT */))
                              : (openBlock(), createElementBlock("p", _hoisted_10$x, toDisplayString($setup.t("customer_rules.tooltip.no_affected_products")), 1 /* TEXT */))
                          ]),
                          ($setup.groupHasProducts($setup.tooltipModel.available))
                            ? (openBlock(), createElementBlock("div", _hoisted_11$s, [
                                createBaseVNode("strong", _hoisted_12$q, toDisplayString($setup.t($setup.availableTitleKey)), 1 /* TEXT */),
                                (openBlock(true), createElementBlock(Fragment, null, renderList($setup.tooltipModel.groups, (group) => {
                                  return (openBlock(), createElementBlock("div", {
                                    key: `available-${group.key}`,
                                    class: "customer-rule-tooltip__group"
                                  }, [
                                    (($setup.tooltipModel.available[group.key] || []).length > 0)
                                      ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                                          createBaseVNode("span", _hoisted_13$o, toDisplayString($setup.t(group.labelKey)), 1 /* TEXT */),
                                          createBaseVNode("ul", {
                                            "data-testid": $setup.listTestId('available', group.key)
                                          }, [
                                            (openBlock(true), createElementBlock(Fragment, null, renderList($setup.tooltipModel.available[group.key], (product) => {
                                              return (openBlock(), createElementBlock("li", {
                                                key: `${group.key}-${product.id}`
                                              }, toDisplayString(product.name || product.product_name), 1 /* TEXT */))
                                            }), 128 /* KEYED_FRAGMENT */))
                                          ], 8 /* PROPS */, _hoisted_14$m)
                                        ], 64 /* STABLE_FRAGMENT */))
                                      : createCommentVNode("v-if", true)
                                  ]))
                                }), 128 /* KEYED_FRAGMENT */))
                              ]))
                            : createCommentVNode("v-if", true)
                        ], 64 /* STABLE_FRAGMENT */))
                ], 64 /* STABLE_FRAGMENT */))
              : createCommentVNode("v-if", true)
          ], 40 /* PROPS, NEED_HYDRATION */, _hoisted_1$Z)
        ]),
        default: withCtx(() => [
          createBaseVNode("span", {
            class: "customer-rule-tooltip__trigger",
            tabindex: "0",
            "data-testid": $props.testId || undefined,
            onMouseenter: $setup.onTriggerMouseEnter,
            onMouseleave: $setup.onTriggerMouseLeave,
            onFocusin: $setup.onTooltipFocusIn,
            onFocusout: $setup.onTooltipFocusOut,
            onKeydown: withKeys(withModifiers($setup.closeTooltip, ["stop","prevent"]), ["escape"])
          }, [
            renderSlot(_ctx.$slots, "default", {}, undefined, true)
          ], 40 /* PROPS, NEED_HYDRATION */, _hoisted_15$l)
        ]),
        _: 3 /* FORWARDED */
      }, 8 /* PROPS */, ["active", "position"]))
    : renderSlot(_ctx.$slots, "default", { key: 1 }, undefined, true)
}
const CustomerRuleTooltip = /*#__PURE__*/_export_sfc(_sfc_main$1T, [['render',_sfc_render$18],['__scopeId',"data-v-41485545"],['__file',"CustomerRuleTooltip.vue"]]);

const _sfc_main$1S = {
  __name: 'PosSelectedCustomer',
  props: {
  variant: {
    type: String,
    default: "default",
    validator: (value) => ["default", "order-detail", "sidebar"].includes(value),
  },
},
  emits: ["update:activeTab"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const { t } = useI18n();
const emit = __emit;

const panel_tabs = ref([
  {
    key: "details",
    name: "Detaljer",
    active: true,
    permission: "get_user",
  },
  {
    key: "rules",
    name: "Regler",
    active: false,
    permission: "list_customer_attributes",
  },
  {
    key: "shortcuts",
    name: "Genveje",
    active: false,
  },
  {
    key: "discounts",
    name: "Rabatter",
    active: false,
    permission: "get_custom_prices_other",
  },
]);

const details = ref([
  {
    name: "Kunde nummer",
    prop: "customerNumber",
    icon: "fas fa-user",
  },
  {
    name: "Navn",
    prop: "name",
    icon: "fas fa-user",
  },
  {
    name: "Adresse",
    prop: "address",
    icon: "fas fa-map-marker-alt",
  },
  {
    name: "Postnummer",
    prop: "zip",
    icon: "fas fa-map-marker-alt",
  },
  {
    name: "Kunde by",
    prop: "city",
    icon: "fas fa-map-marker-alt",
  },
  {
    name: "Telefon",
    prop: "mobilePhone",
    icon: "fas fa-phone",
  },
  {
    name: "Email",
    prop: "email",
    icon: "fas fa-envelope",
  },
  {
    name: "CVR",
    prop: "corporateIdentificationNumber",
    icon: "fas fa-id-card",
  },
]);

const attributes = computed(() =>
  getCustomerRuleDefinitions().map((attribute) => ({
    ...attribute,
    name: t(attribute.labelKey),
    prop: attribute.attribute,
    description: t(attribute.descriptionKey),
  }))
);

const shortcuts = ref([
  {
    name: "Administrer kunde",
    icon: "fas fa-user-edit",
    // Open link in new tab
    action: () => {
      SessionUser.adminUser.customers.fromCustomerNumber
        .getUserId(customer_id.value)
        .then((response) => window.open("/superuser/users/" + response.data.data.user_id, "_blank"));
    },
    visible: SessionUser.canAccessSuperUser(),
  },
  {
    name: "Vaskeabonnement & Specialaftaler",
    icon: "fas fa-user-edit",
    // Open link in new tab
    action: () => {
      SessionUser.adminUser.customers.fromCustomerNumber
        .getUserId(customer_id.value)
        .then((response) => window.open("/superuser/users/" + response.data.data.user_id + "/other", "_blank"));
    },
    visible: SessionUser.canAccessSuperUser(),
  },
]);

const props = __props;

const rootClasses = computed(() => ({
  "pos-selected-customer": true,
  [`pos-selected-customer--${props.variant}`]: true,
}));
const isSidebarVariant = computed(() => props.variant === "sidebar");
const isRulesTabActive = computed(() => panel_tabs.value[1]?.active === true);
const activeTabKey = computed(() => panel_tabs.value.find((tab) => tab.active)?.key ?? "details");

const setActiveTab = (selectedIndex) => {
  panel_tabs.value.forEach((tab, index) => {
    tab.active = index === selectedIndex;
  });
};

const refreshCustomerAttributesForRules = async (selectedCustomerNumber = customer_id.value) => {
  if (!selectedCustomerNumber) {
    return customer_attributes.value;
  }

  return loadCustomerAttributes(selectedCustomerNumber);
};

/** Check if an attribute is set in the customer attributes */
const hasAttribute = (prop) => {
  return customer_attributes.value.some((attribute) => attribute.attribute === prop);
};

watch(
  activeTabKey,
  (tabKey) => {
    emit("update:activeTab", tabKey);
  },
  { immediate: true }
);

watch(
  isRulesTabActive,
  (isActive) => {
    if (!isActive) {
      return;
    }
    void refreshCustomerAttributesForRules();
  },
  { immediate: true }
);

watch(
  () => customer_id.value,
  (nextCustomerId, previousCustomerId) => {
    if (!nextCustomerId || nextCustomerId === previousCustomerId) {
      return;
    }
    void refreshCustomerAttributesForRules(nextCustomerId);
  },
  { immediate: true }
);

const isCustomerDetailsExpanded = ref(false);

const customer_data_has_empty_details = () => {
  return details.value.some(
    (detail) => customer_data.value[detail.prop] === null || customer_data.value[detail.prop] === ""
  );
};

const __returned__ = { t, emit, panel_tabs, details, attributes, shortcuts, props, rootClasses, isSidebarVariant, isRulesTabActive, activeTabKey, setActiveTab, refreshCustomerAttributesForRules, hasAttribute, isCustomerDetailsExpanded, customer_data_has_empty_details, customer_name, customer_id, customer_data, customer_attributes, department_id, loadCustomerAttributes, hideDiscountsCatalog, hidePricesCatalog, setHidePricesCatalog, setHideDiscountsCatalog, getHideDiscountsCatalog, getHidePricesCatalog, getUserDiscounts, user_discounts, createAttribute, deleteAttribute, computed, ref, watch, SessionUser, get useI18n() { return useI18n }, RequiresPermission, CustomerDiscountsDepartmentDisplay, ExpandableContentBox, get getCustomerRuleDefinitions() { return getCustomerRuleDefinitions }, CustomerRuleTooltip };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$Y = { class: "pos-selected-customer__panel" };
const _hoisted_2$M = { class: "panel-block pos-selected-customer__header" };
const _hoisted_3$H = { class: "pos-selected-customer__title-wrap" };
const _hoisted_4$G = { class: "title is-6 pos-selected-customer__title" };
const _hoisted_5$F = ["data-testid"];
const _hoisted_6$C = ["data-testid", "onClick"];
const _hoisted_7$A = { key: 1 };
const _hoisted_8$z = {
  key: 0,
  class: "panel-block pos-selected-customer__row"
};
const _hoisted_9$x = { class: "panel-icon pos-selected-customer__icon" };
const _hoisted_10$w = { class: "pos-selected-customer__label" };
const _hoisted_11$r = { class: "pos-selected-customer__value" };
const _hoisted_12$p = ["data-rule-attribute"];
const _hoisted_13$n = { class: "panel-icon pos-selected-customer__icon" };
const _hoisted_14$l = { class: "pos-selected-customer__label" };
const _hoisted_15$k = { class: "pos-selected-customer__value" };
const _hoisted_16$j = ["onClick"];
const _hoisted_17$g = { class: "field" };
const _hoisted_18$g = ["id", "name", "disabled"];
const _hoisted_19$e = ["for"];
const _hoisted_20$d = ["onClick"];
const _hoisted_21$d = { class: "field" };
const _hoisted_22$d = ["id", "name", "disabled"];
const _hoisted_23$d = ["for"];
const _hoisted_24$d = {
  key: 0,
  class: "pos-selected-customer__rules-footer",
  "data-testid": "pos-customer-rules-footer"
};
const _hoisted_25$c = { class: "panel-block pos-selected-customer__row" };
const _hoisted_26$c = { class: "panel-icon pos-selected-customer__icon" };
const _hoisted_27$b = ["onClick"];
const _hoisted_28$b = {
  key: 0,
  class: "panel-block pos-selected-customer__discounts"
};

function _sfc_render$17(_ctx, _cache, $props, $setup, $data, $options) {
  return ($setup.customer_name)
    ? (openBlock(), createElementBlock("div", {
        key: 0,
        class: normalizeClass($setup.rootClasses)
      }, [
        createBaseVNode("article", _hoisted_1$Y, [
          createBaseVNode("div", _hoisted_2$M, [
            createBaseVNode("div", _hoisted_3$H, [
              createBaseVNode("span", _hoisted_4$G, toDisplayString($setup.customer_name), 1 /* TEXT */)
            ]),
            createBaseVNode("div", {
              class: normalizeClass(["tabs is-small is-centered pos-selected-customer__tabs", { 'pos-sidebar-panel-tabs': $setup.isSidebarVariant }]),
              "data-testid": $setup.isSidebarVariant ? 'pos-customer-sidebar-tabs' : undefined
            }, [
              createBaseVNode("ul", null, [
                (openBlock(true), createElementBlock(Fragment, null, renderList($setup.panel_tabs, (tab, index) => {
                  return (openBlock(), createElementBlock("li", {
                    key: tab.key,
                    class: normalizeClass({ 'is-active': tab.active }),
                    "data-testid": `pos-customer-tab-${tab.key}`,
                    onClick: $event => ($setup.setActiveTab(index))
                  }, [
                    (tab.permission)
                      ? (openBlock(), createBlock($setup["RequiresPermission"], {
                          key: 0,
                          permission: tab.permission
                        }, {
                          default: withCtx(() => [
                            createBaseVNode("a", null, toDisplayString(tab.name), 1 /* TEXT */)
                          ]),
                          _: 2 /* DYNAMIC */
                        }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["permission"]))
                      : (openBlock(), createElementBlock("a", _hoisted_7$A, toDisplayString(tab.name), 1 /* TEXT */))
                  ], 10 /* CLASS, PROPS */, _hoisted_6$C))
                }), 128 /* KEYED_FRAGMENT */))
              ])
            ], 10 /* CLASS, PROPS */, _hoisted_5$F)
          ]),
          ($setup.panel_tabs[0].active)
            ? (openBlock(true), createElementBlock(Fragment, { key: 0 }, renderList($setup.details, (detail) => {
                return (openBlock(), createElementBlock(Fragment, {
                  key: detail.name
                }, [
                  createCommentVNode(" Details that's not empty (unless isCustomerDetailsExpanded is true) "),
                  ($setup.customer_data[detail.prop] || $setup.isCustomerDetailsExpanded)
                    ? (openBlock(), createElementBlock("a", _hoisted_8$z, [
                        createBaseVNode("span", _hoisted_9$x, [
                          createBaseVNode("i", {
                            class: normalizeClass(detail.icon),
                            "aria-hidden": "true"
                          }, null, 2 /* CLASS */)
                        ]),
                        createBaseVNode("span", _hoisted_10$w, toDisplayString(detail.name), 1 /* TEXT */),
                        createBaseVNode("span", _hoisted_11$r, toDisplayString($setup.customer_data[detail.prop]), 1 /* TEXT */)
                      ]))
                    : createCommentVNode("v-if", true)
                ], 64 /* STABLE_FRAGMENT */))
              }), 128 /* KEYED_FRAGMENT */))
            : createCommentVNode("v-if", true),
          createCommentVNode(" Details that's empty, (If there are any) "),
          ($setup.panel_tabs[0].active && $setup.customer_data_has_empty_details())
            ? (openBlock(), createBlock($setup["ExpandableContentBox"], {
                key: 1,
                "onUpdate:expanded": _cache[0] || (_cache[0] = $event => ($setup.isCustomerDetailsExpanded = !$setup.isCustomerDetailsExpanded)),
                expanded: $setup.isCustomerDetailsExpanded
              }, null, 8 /* PROPS */, ["expanded"]))
            : createCommentVNode("v-if", true),
          createCommentVNode(" Attributes "),
          createVNode($setup["RequiresPermission"], { permission: "list_customer_attributes" }, {
            default: withCtx(() => [
              ($setup.panel_tabs[1].active)
                ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                    (openBlock(true), createElementBlock(Fragment, null, renderList($setup.attributes, (attribute) => {
                      return (openBlock(), createElementBlock("div", {
                        key: attribute.attribute,
                        class: "panel-block pos-selected-customer__row",
                        "data-testid": "pos-customer-rule-row",
                        "data-rule-attribute": attribute.attribute
                      }, [
                        createBaseVNode("span", _hoisted_13$n, [
                          createBaseVNode("i", {
                            class: normalizeClass(attribute.icon),
                            "aria-hidden": "true"
                          }, null, 2 /* CLASS */)
                        ]),
                        createVNode($setup["CustomerRuleTooltip"], {
                          attribute: attribute.attribute,
                          active: $setup.hasAttribute(attribute.prop),
                          "customer-number": $setup.customer_id,
                          "department-id": $setup.department_id,
                          "test-id": `pos-customer-rule-tooltip-${attribute.attribute}`
                        }, {
                          default: withCtx(() => [
                            createBaseVNode("span", _hoisted_14$l, toDisplayString(attribute.name), 1 /* TEXT */)
                          ]),
                          _: 2 /* DYNAMIC */
                        }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["attribute", "active", "customer-number", "department-id", "test-id"]),
                        createBaseVNode("span", _hoisted_15$k, [
                          ($setup.hasAttribute(attribute.prop))
                            ? (openBlock(), createElementBlock("span", {
                                key: 0,
                                onClick: $event => ($setup.deleteAttribute($setup.customer_id, attribute.prop).then(() => $setup.loadCustomerAttributes()))
                              }, [
                                createBaseVNode("span", _hoisted_17$g, [
                                  createBaseVNode("input", {
                                    id: attribute.prop,
                                    type: "checkbox",
                                    name: attribute.prop,
                                    class: "switch",
                                    checked: "checked",
                                    disabled: !$setup.SessionUser.hasPermission('delete_customer_attribute')
                                  }, null, 8 /* PROPS */, _hoisted_18$g),
                                  createBaseVNode("label", {
                                    for: attribute.prop
                                  }, null, 8 /* PROPS */, _hoisted_19$e)
                                ])
                              ], 8 /* PROPS */, _hoisted_16$j))
                            : (openBlock(), createElementBlock("span", {
                                key: 1,
                                onClick: $event => ($setup.createAttribute($setup.customer_id, attribute.prop).then(() => $setup.loadCustomerAttributes()))
                              }, [
                                createBaseVNode("span", _hoisted_21$d, [
                                  createBaseVNode("input", {
                                    id: attribute.prop,
                                    type: "checkbox",
                                    name: attribute.prop,
                                    class: "switch",
                                    disabled: !$setup.SessionUser.hasPermission('add_customer_attribute')
                                  }, null, 8 /* PROPS */, _hoisted_22$d),
                                  createBaseVNode("label", {
                                    for: attribute.prop
                                  }, null, 8 /* PROPS */, _hoisted_23$d)
                                ])
                              ], 8 /* PROPS */, _hoisted_20$d))
                        ])
                      ], 8 /* PROPS */, _hoisted_12$p))
                    }), 128 /* KEYED_FRAGMENT */)),
                    (_ctx.$slots['rules-footer'])
                      ? (openBlock(), createElementBlock("div", _hoisted_24$d, [
                          renderSlot(_ctx.$slots, "rules-footer", {}, undefined, true)
                        ]))
                      : createCommentVNode("v-if", true)
                  ], 64 /* STABLE_FRAGMENT */))
                : createCommentVNode("v-if", true)
            ]),
            _: 3 /* FORWARDED */
          }),
          createCommentVNode(" Shortcuts "),
          ($setup.panel_tabs[2].active)
            ? (openBlock(true), createElementBlock(Fragment, { key: 2 }, renderList($setup.shortcuts, (shortcut) => {
                return (openBlock(), createBlock($setup["RequiresPermission"], {
                  key: shortcut.name,
                  permission: "access_super_user"
                }, {
                  default: withCtx(() => [
                    createBaseVNode("a", _hoisted_25$c, [
                      createBaseVNode("span", _hoisted_26$c, [
                        createBaseVNode("i", {
                          class: normalizeClass(shortcut.icon),
                          "aria-hidden": "true"
                        }, null, 2 /* CLASS */)
                      ]),
                      createBaseVNode("span", {
                        class: "pos-selected-customer__shortcut",
                        onClick: shortcut.action
                      }, toDisplayString(shortcut.name), 9 /* TEXT, PROPS */, _hoisted_27$b)
                    ])
                  ]),
                  _: 2 /* DYNAMIC */
                }, 1024 /* DYNAMIC_SLOTS */))
              }), 128 /* KEYED_FRAGMENT */))
            : createCommentVNode("v-if", true),
          createCommentVNode(" Discounts "),
          createVNode($setup["RequiresPermission"], { permission: "get_custom_prices_other" }, {
            default: withCtx(() => [
              ($setup.panel_tabs[3].active)
                ? (openBlock(), createElementBlock("div", _hoisted_28$b, [
                    createVNode($setup["CustomerDiscountsDepartmentDisplay"])
                  ]))
                : createCommentVNode("v-if", true)
            ]),
            _: 1 /* STABLE */
          })
        ]),
        _cache[1] || (_cache[1] = createBaseVNode("div", null, null, -1 /* CACHED */))
      ], 2 /* CLASS */))
    : createCommentVNode("v-if", true)
}
const PosSelectedCustomer = /*#__PURE__*/_export_sfc(_sfc_main$1S, [['render',_sfc_render$17],['__scopeId',"data-v-1f3324d4"],['__file',"PosSelectedCustomer.vue"]]);

const resolvePingUrl = (endpoint = REQUEST_QUEUE_CONFIG.ping.endpoint) => {
  const value = String(endpoint || "/ping");
  return resolveReleaseApiUrl(value);
};

const pingApiServer = async ({
  endpoint = REQUEST_QUEUE_CONFIG.ping.endpoint,
  timeoutMs = REQUEST_QUEUE_CONFIG.ping.timeoutMs,
  fetchImpl = globalThis.fetch,
} = {}) => {
  const url = resolvePingUrl(endpoint);

  if (typeof fetchImpl !== "function") {
    return {
      ok: false,
      status: null,
      url,
      error: new Error("Fetch API is unavailable"),
    };
  }

  const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
  const timeout =
    controller && Number.isFinite(timeoutMs) && timeoutMs > 0
      ? setTimeout(() => controller.abort(), timeoutMs)
      : null;

  try {
    const response = await fetchImpl(url, {
      method: "GET",
      cache: "no-store",
      mode: "cors",
      signal: controller?.signal,
    });

    return {
      ok: Boolean(response?.ok),
      status: response?.status ?? null,
      url,
      error: null,
    };
  } catch (error) {
    return {
      ok: false,
      status: null,
      url,
      error,
    };
  } finally {
    if (timeout) {
      clearTimeout(timeout);
    }
  }
};

const _sfc_main$1R = {
  __name: 'RestrictedPageWrapper',
  props: {
  hasPermission: {
    type: Boolean,
    default: false,
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;
const router = useRouter();

const showDebugInfo = ref(false);
const isSessionInitiated = computed(() => SessionUser.isInitiated());
let sessionTimeout = null;

const clearSessionTimeout = () => {
  if (sessionTimeout) {
    clearTimeout(sessionTimeout);
    sessionTimeout = null;
  }
};

const redirectToConnectivityIssue = () => {
  if (typeof window === "undefined" || window.location.pathname === "/connectivity-issue") {
    return;
  }

  window.location.href = "/connectivity-issue";
};

const handleSlowSessionBootstrap = async () => {
  if (!SessionUser.isInitiated()) {
    const pingResult = await pingApiServer();
    if (!pingResult.ok) {
      redirectToConnectivityIssue();
      return;
    }

    const result = await Swal.fire({
      title: "Error",
      text: "The user session could not be initiated.",
      icon: "error",
      confirmButtonText: "Clear session, and try again",
      showCancelButton: true,
      cancelButtonText: "Retry",
    });

    if (result.isConfirmed) {
      SessionUser.auth.forceClearSession();
      SessionUser.functions.redirectTo.pages.login();
      return;
    }

    await SessionUser.initiateOnAppStart({ force: true });
  }
};

watch(isSessionInitiated, (initiated) => {
  if (initiated) {
    clearSessionTimeout();
  }
});

onMounted(() => {
  sessionTimeout = setTimeout(() => {
    void handleSlowSessionBootstrap();
  }, 15000);
});

onBeforeUnmount(clearSessionTimeout);

const __returned__ = { props, router, showDebugInfo, isSessionInitiated, get sessionTimeout() { return sessionTimeout }, set sessionTimeout(v) { sessionTimeout = v; }, clearSessionTimeout, redirectToConnectivityIssue, handleSlowSessionBootstrap, get useRouter() { return useRouter }, SessionUser, get Swal() { return Swal }, computed, onBeforeUnmount, onMounted, ref, watch, get pingApiServer() { return pingApiServer } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$X = { key: 0 };
const _hoisted_2$L = { key: 2 };
const _hoisted_3$G = { key: 0 };
const _hoisted_4$F = { key: 1 };
const _hoisted_5$E = { key: 2 };
const _hoisted_6$B = { key: 3 };
const _hoisted_7$z = { class: "message mb-6" };
const _hoisted_8$y = { class: "message-header" };
const _hoisted_9$w = { class: "message-body" };
const _hoisted_10$v = { class: "buttons" };

function _sfc_render$16(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", null, [
    (!$setup.isSessionInitiated)
      ? (openBlock(), createElementBlock("div", _hoisted_1$X, [...(_cache[4] || (_cache[4] = [
          createBaseVNode("div", { class: "pageloader is-active is-dark" }, [
            createBaseVNode("span", { class: "title" }, "Bekræfter bruger...")
          ], -1 /* CACHED */)
        ]))]))
      : ($setup.props.hasPermission)
        ? renderSlot(_ctx.$slots, "default", { key: 1 })
        : (openBlock(), createElementBlock("div", _hoisted_2$L, [
            _cache[13] || (_cache[13] = createStaticVNode("<div class=\"my-6\"><h2 class=\"title is-2\">403 Forbidden</h2><h4 class=\"subtitle is-4\">You do not have permission to view this page.</h4></div><div class=\"message is-danger\"><div class=\"message-body\"><h2>403 Forbidden</h2><p>You do not have permission to view this page.</p></div></div>", 2)),
            createCommentVNode(" Simple checks "),
            ($setup.router.currentRoute.value.path === '/user')
              ? (openBlock(), createElementBlock("p", _hoisted_3$G, [
                  _cache[5] || (_cache[5] = createTextVNode(" You are on the /user page. ", -1 /* CACHED */)),
                  _cache[6] || (_cache[6] = createBaseVNode("br", null, null, -1 /* CACHED */)),
                  createTextVNode("You do " + toDisplayString($setup.SessionUser.hasPermission("user") ? "" : "not") + " have permission ( user ) to view this page. ", 1 /* TEXT */)
                ]))
              : createCommentVNode("v-if", true),
            ($setup.router.currentRoute.value.path === '/admin')
              ? (openBlock(), createElementBlock("p", _hoisted_4$F, [
                  _cache[7] || (_cache[7] = createTextVNode(" You are on the /admin page. ", -1 /* CACHED */)),
                  _cache[8] || (_cache[8] = createBaseVNode("br", null, null, -1 /* CACHED */)),
                  createTextVNode("You do " + toDisplayString($setup.SessionUser.hasPermission("admin") ? "" : "not") + " have permission ( admin ) to view this page. ", 1 /* TEXT */)
                ]))
              : createCommentVNode("v-if", true),
            ($setup.router.currentRoute.value.path === '/superuser')
              ? (openBlock(), createElementBlock("p", _hoisted_5$E, [
                  _cache[9] || (_cache[9] = createTextVNode(" You are on the /superuser ", -1 /* CACHED */)),
                  _cache[10] || (_cache[10] = createBaseVNode("br", null, null, -1 /* CACHED */)),
                  createTextVNode("page. You do " + toDisplayString($setup.SessionUser.hasPermission("superuser") ? "" : "not") + " have permission ( superuser ) to view this page. ", 1 /* TEXT */)
                ]))
              : createCommentVNode("v-if", true),
            ($setup.showDebugInfo)
              ? (openBlock(), createElementBlock("div", _hoisted_6$B, [
                  createBaseVNode("div", _hoisted_7$z, [
                    createBaseVNode("div", _hoisted_8$y, [
                      _cache[11] || (_cache[11] = createBaseVNode("p", null, "Debug information", -1 /* CACHED */)),
                      createBaseVNode("button", {
                        class: "delete",
                        "aria-label": "delete",
                        onClick: _cache[0] || (_cache[0] = $event => ($setup.showDebugInfo = false))
                      })
                    ]),
                    createBaseVNode("div", _hoisted_9$w, [
                      _cache[12] || (_cache[12] = createBaseVNode("p", { class: "label" }, "Session user:", -1 /* CACHED */)),
                      createBaseVNode("pre", null, toDisplayString($setup.SessionUser), 1 /* TEXT */)
                    ])
                  ])
                ]))
              : createCommentVNode("v-if", true),
            createBaseVNode("div", _hoisted_10$v, [
              createCommentVNode(" Button to go back to the previous page "),
              createBaseVNode("button", {
                class: "button is-dark",
                onClick: _cache[1] || (_cache[1] = $event => ($setup.router.go(-1)))
              }, "Go back"),
              createCommentVNode(" Button to see the debug information "),
              (!$setup.showDebugInfo)
                ? (openBlock(), createElementBlock("button", {
                    key: 0,
                    class: "button is-dark",
                    onClick: _cache[2] || (_cache[2] = $event => ($setup.showDebugInfo = !$setup.showDebugInfo))
                  }, " Show debug information "))
                : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
                    createCommentVNode(" Button to hide the debug information "),
                    createBaseVNode("button", {
                      class: "button is-dark",
                      onClick: _cache[3] || (_cache[3] = $event => ($setup.showDebugInfo = !$setup.showDebugInfo))
                    }, "Hide debug information")
                  ], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */))
            ])
          ]))
  ]))
}
const RestrictedPageWrapper = /*#__PURE__*/_export_sfc(_sfc_main$1R, [['render',_sfc_render$16],['__file',"RestrictedPageWrapper.vue"]]);

const _sfc_main$1Q = {
  __name: 'SuperuserInvoiceRowActions',
  props: {
  includeBuffer: {
    type: Boolean,
    default: false,
  },
},
  setup(__props, { expose: __expose }) {
  __expose();



const __returned__ = {  };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$W = { class: "buttons superuser-invoice-row-actions" };
const _hoisted_2$K = {
  key: 0,
  type: "button",
  class: "button is-small superuser-invoice-row-actions__buffer",
  "aria-hidden": "true",
  tabindex: "-1",
  disabled: "",
  "data-testid": "superuser-invoice-action-buffer"
};

function _sfc_render$15(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$W, [
    ($props.includeBuffer)
      ? (openBlock(), createElementBlock("button", _hoisted_2$K, [...(_cache[0] || (_cache[0] = [
          createBaseVNode("span", { class: "icon" }, [
            createBaseVNode("i", { class: "fas fa-paperclip" })
          ], -1 /* CACHED */)
        ]))]))
      : createCommentVNode("v-if", true),
    renderSlot(_ctx.$slots, "default", {}, undefined, true)
  ]))
}
const SuperuserInvoiceRowActions = /*#__PURE__*/_export_sfc(_sfc_main$1Q, [['render',_sfc_render$15],['__scopeId',"data-v-7f60b1f1"],['__file',"SuperuserInvoiceRowActions.vue"]]);

const _sfc_main$1P = {
  __name: 'CollectedOrderInvoicesDefaultTable',
  props: {
  objects: {
    type: Array,
    default: () => [],
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const { t } = useI18n();


const props = __props;

const redirect = (path) => {
  window.open(path, '_blank');
};

const parseProcessor = (value) => {
  if (value === null) return t('global.no_data');
  if (value === 1) return 'E-conomic';
  return t('global.other');
};

const parseDate = (value) => {
  if (value === null) return '-';
  return value;
};

const parseClosedAt = (value) => {
  if (value === null) return t('global.open');
  return t('global.closed') + ' ' + value;
};

const __returned__ = { t, props, redirect, parseProcessor, parseDate, parseClosedAt, get useI18n() { return useI18n }, SessionUser, ActionSettingsWheelButton, ActionSettingsWheelItem, SuperuserInvoiceRowActions };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$V = { class: "table is-fullwidth is-hoverable is-striped" };
const _hoisted_2$J = { class: "has-text-right" };
const _hoisted_3$F = { class: "is-narrow" };
const _hoisted_4$E = { key: 0 };
const _hoisted_5$D = { colspan: "11" };

function _sfc_render$14(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("table", _hoisted_1$V, [
    createBaseVNode("thead", null, [
      createBaseVNode("tr", null, [
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.id.label), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.customer_number.label), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.name.label), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.notes.label), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.processor.label), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.external_id.label), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.po_number.label), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.closed_at.label), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.created_at.label), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.updated_at.label), 1 /* TEXT */),
        createBaseVNode("th", _hoisted_2$J, toDisplayString(_ctx.$t('tables.actions')), 1 /* TEXT */)
      ])
    ]),
    createBaseVNode("tbody", null, [
      (openBlock(true), createElementBlock(Fragment, null, renderList($setup.props.objects, (object) => {
        return (openBlock(), createElementBlock("tr", {
          key: object.id
        }, [
          createBaseVNode("td", null, toDisplayString(object.id), 1 /* TEXT */),
          createBaseVNode("td", null, toDisplayString(object.customer_number), 1 /* TEXT */),
          createBaseVNode("td", null, toDisplayString(object.name ?? '-'), 1 /* TEXT */),
          createBaseVNode("td", null, toDisplayString(object.notes ?? '-'), 1 /* TEXT */),
          createBaseVNode("td", null, toDisplayString($setup.parseProcessor(object.processor)), 1 /* TEXT */),
          createBaseVNode("td", null, toDisplayString(object.external_id ?? '-'), 1 /* TEXT */),
          createBaseVNode("td", null, toDisplayString(object.po_number ?? '-'), 1 /* TEXT */),
          createBaseVNode("td", null, toDisplayString($setup.parseClosedAt(object.closed_at)), 1 /* TEXT */),
          createBaseVNode("td", null, toDisplayString($setup.parseDate(object.created_at)), 1 /* TEXT */),
          createBaseVNode("td", null, toDisplayString($setup.parseDate(object.updated_at)), 1 /* TEXT */),
          createBaseVNode("td", _hoisted_3$F, [
            createVNode($setup["SuperuserInvoiceRowActions"], { "include-buffer": true }, {
              default: withCtx(() => [
                createVNode($setup["ActionSettingsWheelButton"], null, {
                  actions: withCtx(() => [
                    createVNode($setup["ActionSettingsWheelItem"], {
                      icon: "fas fa-eye",
                      onClick: $event => ($setup.redirect('/superuser/invoices/' + object.id)),
                      label: $setup.t('common.show')
                    }, null, 8 /* PROPS */, ["onClick", "label"])
                  ]),
                  _: 2 /* DYNAMIC */
                }, 1024 /* DYNAMIC_SLOTS */)
              ]),
              _: 2 /* DYNAMIC */
            }, 1024 /* DYNAMIC_SLOTS */)
          ])
        ]))
      }), 128 /* KEYED_FRAGMENT */)),
      ($props.objects.length === 0)
        ? (openBlock(), createElementBlock("tr", _hoisted_4$E, [
            createBaseVNode("td", _hoisted_5$D, toDisplayString(_ctx.$t('global.no_data')), 1 /* TEXT */)
          ]))
        : createCommentVNode("v-if", true)
    ])
  ]))
}
const CollectedOrderInvoicesDefaultTable = /*#__PURE__*/_export_sfc(_sfc_main$1P, [['render',_sfc_render$14],['__file',"CollectedOrderInvoicesDefaultTable.vue"]]);

const _sfc_main$1O = {
  __name: 'LoadButtonWhileAwait',
  props: {
  loadFunction: {
    type: Function,
    required: true,
  },
  icon: {
    type: String,
    default: null,
  },
  isLoading: {
    type: Boolean,
    default: undefined,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  actionKey: {
    type: String,
    default: null,
  },
  copyKey: {
    type: String,
    default: null,
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;

// Local loading state for when isLoading prop is not provided
const localIsLoading = ref(false);

// Use computed to react to prop changes, fallback to local state if prop not provided
const isLoading = computed(() => {
  if (props.isLoading !== undefined) {
    return props.isLoading;
  }
  return localIsLoading.value;
});

const loadWhileAwait = async (loadFunction) => {
  if (props.isLoading === undefined) {
    localIsLoading.value = true;
  }
  await loadFunction();
  if (props.isLoading === undefined) {
    localIsLoading.value = false;
  }
};

const handleClick = () => loadWhileAwait(props.loadFunction);

const __returned__ = { props, localIsLoading, isLoading, loadWhileAwait, handleClick, get BButton() { return BButton }, get BIcon() { return BIcon }, get BLoading() { return BLoading }, computed, ref };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

function _sfc_render$13(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createBlock($setup["BButton"], {
    loading: $setup.isLoading,
    "icon-left": $props.icon,
    "icon-pack": 'fas',
    onClick: $setup.handleClick,
    disabled: $setup.isLoading || ($setup.props.disabled ?? false),
    "data-action-key": $setup.props.actionKey || null,
    "data-copy-key": $setup.props.copyKey || null
  }, {
    default: withCtx(() => [
      renderSlot(_ctx.$slots, "default")
    ]),
    _: 3 /* FORWARDED */
  }, 8 /* PROPS */, ["loading", "icon-left", "disabled", "data-action-key", "data-copy-key"]))
}
const LoadButtonWhileAwait = /*#__PURE__*/_export_sfc(_sfc_main$1O, [['render',_sfc_render$13],['__file',"LoadButtonWhileAwait.vue"]]);

// Define the reactive properties
// Data for the table
const dataColumns = ref([]);
const dataRows = ref([]);

// Setters and getters for dataColumns
const setDataColumns = (columns) => {
  // Default functions
  let defaultFunctions = {
    getLabel: function () {
      if (this.properties.label) {
        return this.properties.label;
      }
      return this.id;
    },
    getType: function () {
      return this.type;
    },
    getProperties: function () {
      return this.properties;
    },
  };
  // Push the default functions to each column
  columns.forEach((column) => {
    // Add the default functions to the column
    for (const key in defaultFunctions) {
      if (Object.prototype.hasOwnProperty.call(defaultFunctions, key)) {
        column[key] = defaultFunctions[key].bind(column);
      }
    }
  });
  // Set the dataColumns
  dataColumns.value = columns;
};
const getDataColumns = () => {
  return dataColumns.value;
};

// Setters and getters for dataRows
const setDataRows = (rows) => {
  // Default functions
  let defaultFunctions = {
    parseValue: function (value) {
      // This function is here, to make it possible to override the data parsing elsewhere.
      return value;
    },
    getValue: function (key) {
      return this.parseValue(this[key]);
    },
  };
  // Push the default functions to each row
  rows.forEach((row) => {
    // Add the default functions to the row
    for (const key in defaultFunctions) {
      if (Object.prototype.hasOwnProperty.call(defaultFunctions, key)) {
        row[key] = defaultFunctions[key].bind(row);
      }
    }
  });
  // Set the dataRows
  dataRows.value = rows;
};
const getDataRows = () => {
  return dataRows.value;
};

// Metadata for the table
const title = ref("Mass Data Inserter");
const subtitle = ref("Indsæt data i systemet");

// Setters and getters for metadata
const setTitle = (newTitle) => {
  title.value = newTitle;
};
const getTitle = () => {
  return title.value;
};
const setSubtitle = (newSubtitle) => {
  subtitle.value = newSubtitle;
};
const getSubtitle = () => {
  return subtitle.value;
};

// Data structure parser
const parsedDataFormatFunction = ref((data) => {
  // This function is here, to make it possible to override the data parsing elsewhere.
  return data;
});
const setParsedDataFormatFunction = (newFunction) => {
  parsedDataFormatFunction.value = newFunction;
};
const getParsedDataFormatFunction = () => {
  return parsedDataFormatFunction.value;
};

// Save function
const saveFunction = ref(() => {
  // This function is here, to make it possible to override the data saving elsewhere.
  console.log("Save function not set");
});
const setSaveFunction = (newFunction) => {
  saveFunction.value = newFunction;
};
const getSaveFunction = () => {
  return saveFunction.value;
};

// Progress
const request_limit = ref(5);
const pending = ref([]);
const processing = ref([]);
const completed = ref([]);
const failed = ref([]);
const responses = ref([]);
const progress = computed(() => {
  return {
    pending: pending.value,
    processing: processing.value,
    completed: completed.value,
    failed: failed.value,
    total: pending.value.length + processing.value.length + completed.value.length + failed.value.length,
  };
});
const setRequestLimit = (limit) => {
  request_limit.value = limit;
};
const getRequestLimit = () => {
  return request_limit.value;
};
const setPending = (newPending) => {
  pending.value = newPending;
};
const getPending = () => {
  return pending.value;
};
const setProcessing = (newProcessing) => {
  processing.value = newProcessing;
};
const getProcessing = () => {
  return processing.value;
};
const setCompleted = (newCompleted) => {
  completed.value = newCompleted;
};
const getCompleted = () => {
  return completed.value;
};
const setFailed = (newFailed) => {
  failed.value = newFailed;
};
const getFailed = () => {
  return failed.value;
};
const setResponses = (newResponses) => {
  responses.value = newResponses;
};
const getResponses = () => {
  return responses.value;
};
const getResponse = (object) => {
  // Get the response for the object
  return getResponses().find((response) => response.object === object);
};


// Clear the progress
const clearProgress = () => {
  pending.value = [];
  processing.value = [];
  completed.value = [];
  failed.value = [];
  responses.value = [];
};





const _sfc_main$1N = {};
const MassDataInserter = /*#__PURE__*/_export_sfc(_sfc_main$1N, [['__file',"MassDataInserter.vue"]]);

const createColumnType = (name, type, validationFunction = null) => {
  return {
    name: name,
    type: type,
    validationFunction: validationFunction,
  };
};

const columnTypes = {
  string: createColumnType('string', 'string'),
  number: createColumnType('number', 'number'),
  boolean: createColumnType('boolean', 'boolean'),
  date: createColumnType('date', 'date'),
  datetime: createColumnType('datetime', 'datetime'),
  time: createColumnType('time', 'time'),
  decimal: createColumnType('decimal', 'decimal'),

  // Add more column types as needed
  registration_number: createColumnType('registration_number', 'string', (value) => {
    // Require no spaces, between 1 and 12 letters and numbers
    return /^[A-Za-z0-9]{1,12}$/.test(value);
  }),
  product: createColumnType('product', 'number', (value) => {
    // Require a number between 0 and 999999
    return /^[0-9]{1,6}$/.test(value);
  }),
};

const _sfc_main$1M = {};
const dataColumnsType = /*#__PURE__*/_export_sfc(_sfc_main$1M, [['__file',"dataColumnsType.vue"]]);

const defaultColumnProperties = {
  type: columnTypes.string,
  required: false,
  defaultValue: null,
  label: undefined,
};

const availableColumnProperties = {
  type: {
    type: String,
    default: defaultColumnProperties.type,
  },
  required: {
    type: Boolean,
    default: defaultColumnProperties.required,
  },
  defaultValue: {
    type: [String, Number, Boolean, Object],
    default: defaultColumnProperties.defaultValue,
  },
};

const applyColumnProperties = (properties) => {
  return { ...defaultColumnProperties, ...properties };
};

const _sfc_main$1L = {};
const dataColumn = /*#__PURE__*/_export_sfc(_sfc_main$1L, [['__file',"dataColumn.vue"]]);

// Function to generate a new column
const generateNewColumn = (
    id,
    type,
    properties = {}
) => {
  return {
    id: id,
    type: type,
    properties: applyColumnProperties(properties),
  };
};

const _sfc_main$1K = {};
const manageDataColumns = /*#__PURE__*/_export_sfc(_sfc_main$1K, [['__file',"manageDataColumns.vue"]]);

const exampleRows = [
  {
    id: 1,
    customer_number: 12345,
    name: "Test Invoice 1",
  },
  {
    id: 2,
    customer_number: 67890,
    name: "Test Invoice 2",
  },
];

const init = () => {
  /**
   * Set the data columns for the collected order invoices compare data structure
   * @type {function}
   */
  setDataColumns([
    generateNewColumn("id", columnTypes.number, applyColumnProperties({required: true, label: SessionUser.objects.collectedOrderInvoices.columns.id.label})),
    generateNewColumn("customer_number", columnTypes.number, applyColumnProperties({required: true, label: SessionUser.objects.collectedOrderInvoices.columns.customer_number.label})),
    generateNewColumn("customer_name", columnTypes.string, applyColumnProperties({required: false, label: SessionUser.objects.collectedOrderInvoices.columns.name.label})),
    generateNewColumn("total_net_amount", columnTypes.decimal, applyColumnProperties({required: false, label: SessionUser.objects.collectedOrderInvoices.columns.total_net_amount.label})),
  ]);

  /**
   * Set the data format parser function
   * @type {function}
   */
  setParsedDataFormatFunction((objects) => {
    console.log('parsing format collected order invoices for comparison', objects);
    // Define the objects
    let parsedObjects = [];
    // Loop through the objects and parse them to the correct format
    objects.forEach((object) => {
      let parsedObject = {
        id: object.id,
        customer_number: object.customer_number,
        customer_name: object.customer_name,
        total_net_amount: object.total_net_amount,
      };
      // Add the parsed object to the parsed objects array
      parsedObjects.push(parsedObject);
    });
    // Store the parsed objects in the data rows
    setDataRows(parsedObjects);
    return parsedObjects;
  });

  /**
   * Set the save function for the collected order invoices compare data structure
   * @type {function}
   */
  setSaveFunction((objects) => {
    // Add all the objects to the pending objects
    setPending(objects);
    // Start the processing
    processPendingInvoices();
  });
};

const processPendingInvoices = () => {
  // While there's unprocessed objects, process them
  while (getPending().length > 0 && getProcessing().length < getRequestLimit()) {
      // Get the first object from the pending objects
      let object = getPending()[0];
      // Remove the object from the pending objects
      setPending(getPending().slice(1));
      // Add the object to the processing objects
      setProcessing([...getProcessing(), object]);
      // Process the object
      processInvoice(object);
  }
};

const processInvoice = (object) => {
  // Send a request to the server to compare the invoice with E-conomic
  SessionUser.objects.collectedOrderInvoices.functions.economic.compareToEconomic(
      object.id
  ).then((response) => {
    // If the request was successful, check if the object is valid
    if (response.status === 200) {
      // Store the difference from the API response into the object
      const responseData = response.data?.data || response.data;
      if (responseData && responseData.difference !== undefined) {
        object.difference = responseData.difference;
      }
      // Add the response to the responses
      setResponses([...getResponses(), {
        object: object,
        success: true,
        response: response,
        data: responseData,
      }]);
      // If the object is valid, add it to the completed objects
      setCompleted([...getCompleted(), object]);
      // Remove the object from the processing objects
      setProcessing(getProcessing().filter((o) => o !== object));
    }
  }).catch((error) => {
    // If the request failed, add the object to the failed objects
    console.log('Failed to compare invoice', error);
    // Try to extract difference from error response (difference can also be returned in error responses)
    const errorResponseData = error.response?.data?.data || error.response?.data;
    if (errorResponseData && errorResponseData.difference !== undefined) {
      object.difference = errorResponseData.difference;
    }
    // Add the response to the responses
    setResponses([...getResponses(), {
      object: object,
      success: false,
      error: error,
      data: errorResponseData,
    }]);
    setFailed([...getFailed(), object]);
    // Remove the object from the processing objects
    setProcessing(getProcessing().filter((o) => o !== object));
  }).finally(() => {
    // Process the next object
    processPendingInvoices();
  });
};



const _sfc_main$1J = {};
const CollectedOrderInvoicesCompareDataStructure = /*#__PURE__*/_export_sfc(_sfc_main$1J, [['__file',"CollectedOrderInvoicesCompareDataStructure.vue"]]);

const _sfc_main$1I = {
  __name: 'MassDataInsertTable',
  setup(__props, { expose: __expose }) {
  __expose();

const rowDetailsVisible = ref([]);
const toggleDetails = (row) => {
  const index = rowDetailsVisible.value.indexOf(row);
  if (index > -1) {
    rowDetailsVisible.value.splice(index, 1);
  } else {
    rowDetailsVisible.value.push(row);
  }
};
const isRowDetailsVisible = (row) => {
  return rowDetailsVisible.value.includes(row);
};

// Get the difference for a row from the response
const getRowDifference = (row) => {
  const response = getResponse(row);
  if (response && response.data && response.data.difference !== undefined && response.data.difference !== null && response.data.difference !== 0) {
    return response.data.difference;
  }
  return null;
};

// Calculate total difference from all responses
const getTotalDifference = () => {
  const responses = getResponses();
  let total = 0;
  responses.forEach((r) => {
    if (r.data && r.data.difference !== undefined && r.data.difference !== null) {
      total += Number(r.data.difference) || 0;
    }
  });
  return total;
};

const __returned__ = { rowDetailsVisible, toggleDetails, isRowDetailsVisible, getRowDifference, getTotalDifference, getDataColumns, getDataRows, progress, getResponse, getResponses, SessionUser, ref, computed };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$U = { class: "table is-striped is-hoverable is-fullwidth" };
const _hoisted_2$I = ["onClick"];
const _hoisted_3$E = {
  key: 0,
  class: "tag is-light is-clickable"
};
const _hoisted_4$D = {
  key: 1,
  class: "tag is-info is-clickable"
};
const _hoisted_5$C = {
  key: 2,
  class: "tag is-success is-clickable"
};
const _hoisted_6$A = {
  key: 3,
  class: "tag is-danger is-clickable"
};
const _hoisted_7$y = { class: "has-text-left" };
const _hoisted_8$x = {
  key: 0,
  class: "tag is-warning"
};
const _hoisted_9$v = { colspan: "100%" };
const _hoisted_10$u = { class: "notification is-light has-text-left" };
const _hoisted_11$q = { key: 0 };
const _hoisted_12$o = { key: 1 };
const _hoisted_13$m = { key: 2 };
const _hoisted_14$k = {
  colspan: "100%",
  class: "has-text-left"
};
const _hoisted_15$j = {
  key: 0,
  class: "ml-3 tag is-warning"
};

function _sfc_render$12(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("table", _hoisted_1$U, [
    createBaseVNode("thead", null, [
      createBaseVNode("tr", null, [
        createCommentVNode(" Add the column headers "),
        (openBlock(true), createElementBlock(Fragment, null, renderList($setup.getDataColumns(), (column) => {
          return (openBlock(), createElementBlock("th", {
            key: column.id
          }, toDisplayString(column.getLabel()), 1 /* TEXT */))
        }), 128 /* KEYED_FRAGMENT */)),
        createCommentVNode(" Status processing "),
        ($setup.progress.total > 0)
          ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
              createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.global.language.status), 1 /* TEXT */),
              _cache[0] || (_cache[0] = createBaseVNode("th", null, "Difference", -1 /* CACHED */))
            ], 64 /* STABLE_FRAGMENT */))
          : createCommentVNode("v-if", true)
      ])
    ]),
    createBaseVNode("tbody", null, [
      (openBlock(true), createElementBlock(Fragment, null, renderList($setup.getDataRows(), (row) => {
        return (openBlock(), createElementBlock(Fragment, {
          key: row.id
        }, [
          createBaseVNode("tr", null, [
            (openBlock(true), createElementBlock(Fragment, null, renderList($setup.getDataColumns(), (column) => {
              return (openBlock(), createElementBlock("td", {
                key: column.id,
                class: "has-text-left"
              }, toDisplayString(row.getValue(column.id)), 1 /* TEXT */))
            }), 128 /* KEYED_FRAGMENT */)),
            createCommentVNode(" Status processing "),
            ($setup.progress.total > 0)
              ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                  createBaseVNode("td", {
                    class: "has-text-left",
                    onClick: $event => ($setup.toggleDetails(row))
                  }, [
                    ($setup.progress.pending.includes(row))
                      ? (openBlock(), createElementBlock("span", _hoisted_3$E, toDisplayString($setup.SessionUser.objects.global.language.waiting), 1 /* TEXT */))
                      : createCommentVNode("v-if", true),
                    ($setup.progress.processing.includes(row))
                      ? (openBlock(), createElementBlock("span", _hoisted_4$D, toDisplayString($setup.SessionUser.objects.global.language.in_progress), 1 /* TEXT */))
                      : createCommentVNode("v-if", true),
                    ($setup.progress.completed.includes(row))
                      ? (openBlock(), createElementBlock("span", _hoisted_5$C, toDisplayString($setup.SessionUser.objects.global.language.succeeded), 1 /* TEXT */))
                      : createCommentVNode("v-if", true),
                    ($setup.progress.failed.includes(row))
                      ? (openBlock(), createElementBlock("span", _hoisted_6$A, toDisplayString($setup.SessionUser.objects.global.language.failed), 1 /* TEXT */))
                      : createCommentVNode("v-if", true)
                  ], 8 /* PROPS */, _hoisted_2$I),
                  createCommentVNode(" Show difference if not 0 "),
                  createBaseVNode("td", _hoisted_7$y, [
                    ($setup.getRowDifference(row) !== null)
                      ? (openBlock(), createElementBlock("span", _hoisted_8$x, toDisplayString($setup.getRowDifference(row)), 1 /* TEXT */))
                      : createCommentVNode("v-if", true)
                  ])
                ], 64 /* STABLE_FRAGMENT */))
              : createCommentVNode("v-if", true)
          ]),
          createCommentVNode(" Details row "),
          ($setup.isRowDetailsVisible(row))
            ? (openBlock(), createElementBlock("tr", {
                key: row.id + '-details'
              }, [
                createBaseVNode("td", _hoisted_9$v, [
                  createBaseVNode("div", _hoisted_10$u, [
                    createBaseVNode("strong", null, toDisplayString($setup.SessionUser.objects.global.language.error), 1 /* TEXT */),
                    ($setup.progress.failed.includes(row))
                      ? (openBlock(), createElementBlock("pre", _hoisted_11$q, toDisplayString($setup.getResponse(row).error.response.data.data.message ? $setup.getResponse(row).error.response.data.data.message : $setup.getResponse(row).error.response.data.data), 1 /* TEXT */))
                      : ($setup.progress.completed.includes(row))
                        ? (openBlock(), createElementBlock("pre", _hoisted_12$o, toDisplayString($setup.getResponse(row).data.data ? $setup.getResponse(row).data.data : $setup.getResponse(row).data), 1 /* TEXT */))
                        : (openBlock(), createElementBlock("pre", _hoisted_13$m, toDisplayString($setup.SessionUser.objects.global.language.pending), 1 /* TEXT */))
                  ])
                ])
              ]))
            : createCommentVNode("v-if", true)
        ], 64 /* STABLE_FRAGMENT */))
      }), 128 /* KEYED_FRAGMENT */))
    ]),
    createBaseVNode("tfoot", null, [
      createBaseVNode("tr", null, [
        createCommentVNode(" Add the total row count "),
        createBaseVNode("td", _hoisted_14$k, [
          createTextVNode(toDisplayString($setup.getDataRows().length) + " " + toDisplayString($setup.SessionUser.objects.global.language.rows.toLowerCase()) + " ", 1 /* TEXT */),
          ($setup.getTotalDifference() !== 0)
            ? (openBlock(), createElementBlock("span", _hoisted_15$j, " Total difference: " + toDisplayString($setup.getTotalDifference()), 1 /* TEXT */))
            : createCommentVNode("v-if", true)
        ])
      ])
    ])
  ]))
}
const MassDataInsertTable = /*#__PURE__*/_export_sfc(_sfc_main$1I, [['render',_sfc_render$12],['__file',"MassDataInsertTable.vue"]]);

// File content
const fileContent = ref('');
// File content
const selectFile = ref('');
// Parsed file content
const parsedFileContent = ref(null);
// Define the onParsedFunction
const onParsedFunctionCache = ref(null);

const showError = (message) => {
  Swal.fire({
    icon: 'error',
    title: 'Error',
    text: message,
    confirmButtonText: SessionUser.objects.global.language.close,
  });
};

const isSpreadsheetFile = (file) => {
  return /\.(xlsx|xls)$/i.test(file?.name ?? '');
};

const initiateFileSelection = (onParsedFunction = null) => {
  // Reset the file content
  fileContent.value = '';
  // Reset the parsed file content
  parsedFileContent.value = null;
  // Reset the select file
  selectFile.value = '';
  // Set the onParsedFunction
  if (onParsedFunction) {
    onParsedFunctionCache.value = onParsedFunction;
  } else {
    onParsedFunctionCache.value = null;
  }
  // Create a file input element
  const fileInput = document.createElement('input');
  fileInput.type = 'file';
  fileInput.accept = '.xlsx, .xls, .csv, .txt, .tsv';

  // Listen for the change event
  fileInput.addEventListener('change', (event) => {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        if (isSpreadsheetFile(file)) {
          if (validateSpreadsheetContent(e.target.result)) {
            parseSpreadsheetContent(e.target.result);
          }
          return;
        }

        fileContent.value = e.target.result;
        if (validateDelimitedFileContent(fileContent.value)) {
          parseDelimitedFileContent(fileContent.value);
        }
      };

      if (isSpreadsheetFile(file)) {
        reader.readAsArrayBuffer(file);
      } else {
        reader.readAsText(file);
      }
    }
  });

  // Trigger the file input click
  fileInput.click();
};

const getFileContent = () => {
  return fileContent.value;
};

const validateDelimitedFileContent = (content) => {
  // Check if the content is empty
  if (!content) {
    showError('File content is empty');
    return false;
  }

  // Check if the content has at least one row
  const rows = content
      .split('\n')
      .map((row) => normalizeLine(row))
      .filter((row) => row.trim() !== '');
  if (rows.length === 0) {
    showError('File has no rows');
    return false;
  }

  return true;
};

const validateSpreadsheetContent = (content) => {
  if (!(content instanceof ArrayBuffer) || content.byteLength === 0) {
    showError('File content is empty');
    return false;
  }

  return true;
};

const normalizeLine = (row) => {
  return String(row ?? '')
      .replace(/\uFEFF/g, '')
      .replace(/\r/g, '')
      .trimEnd();
};

const detectDelimiter = (rows) => {
  const sampleRows = rows
      .map((row) => normalizeLine(row))
      .filter((row) => row.trim() !== '')
      .slice(0, 5);

  const candidates = ['\t', ';', ','];
  let selectedDelimiter = ';';
  let highestScore = -1;

  candidates.forEach((candidate) => {
    const score = sampleRows.reduce((sum, row) => {
      return sum + ((row.match(new RegExp(candidate === '\t' ? '\\t' : `\\${candidate}`, 'g')) || []).length);
    }, 0);

    if (score > highestScore) {
      highestScore = score;
      selectedDelimiter = candidate;
    }
  });

  return selectedDelimiter;
};

const parseDelimitedRow = (row, delimiter) => {
  const values = [];
  let currentValue = '';
  let insideQuotes = false;

  for (let index = 0; index < row.length; index += 1) {
    const character = row[index];
    const nextCharacter = row[index + 1];

    if (character === '"') {
      if (insideQuotes && nextCharacter === '"') {
        currentValue += '"';
        index += 1;
        continue;
      }

      insideQuotes = !insideQuotes;
      continue;
    }

    if (!insideQuotes && character === delimiter) {
      values.push(currentValue.trim());
      currentValue = '';
      continue;
    }

    currentValue += character;
  }

  values.push(currentValue.trim());
  return values;
};

const parseDelimitedFileContent = (content) => {
  const rows = content
      .split('\n')
      .map((row) => normalizeLine(row))
      .filter((row) => row.trim() !== '');

  const delimiter = detectDelimiter(rows);
  const parsedData = rows
      .map((row) => parseDelimitedRow(row, delimiter))
      .filter((row) => row.some((column) => column !== ''));

  parsedFileContent.value = parsedData;
  onParsed(onParsedFunctionCache.value);
};

const parseSpreadsheetContent = (content) => {
  const workbook = readSync(content, {
    type: 'array',
    raw: true,
  });

  const firstSheetName = workbook.SheetNames[0];
  if (!firstSheetName) {
    showError('File has no sheets');
    return;
  }

  const worksheet = workbook.Sheets[firstSheetName];
  const parsedData = utils.sheet_to_json(worksheet, {
    header: 1,
    blankrows: false,
    defval: '',
    raw: true,
  })
      .map((row) => (Array.isArray(row) ? row.map((column) => String(column ?? '').trim()) : []))
      .filter((row) => row.some((column) => column !== ''));

  parsedFileContent.value = parsedData;
  onParsed(onParsedFunctionCache.value);
};

const onParsed = (onParsedFunction) => {
  // Check if the onParsedFunction is set
  if (onParsedFunction) {
    // Call the onParsedFunction with the parsed data
    onParsedFunction(parsedFileContent.value);
  } else {
    // If no onParsedFunction is set, just set the dataRows
    showError('No onParsedFunction set');
  }
};

const _sfc_main$1H = {};
const selectParseFile = /*#__PURE__*/_export_sfc(_sfc_main$1H, [['__file',"selectParseFile.vue"]]);

// Emits

const _sfc_main$1G = {
  __name: 'MassDataInsertControls',
  emits: ["onClickAdd", "onClickClear"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const emit = __emit;
const onClickAdd = () => {
  initiateFileSelection(getParsedDataFormatFunction());
  emit("onClickAdd");
};
const onClickClear = () => {
  // Clear the dataRows
  setDataRows([]);
  // Clear the progress
  clearProgress();
  emit("onClickClear");
};

const __returned__ = { emit, onClickAdd, onClickClear, getDataColumns, getDataRows, getParsedDataFormatFunction, setDataRows, clearProgress, ref, computed, initiateFileSelection, getFileContent, SessionUser };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$T = { class: "buttons is-pulled-right" };

function _sfc_render$11(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$T, [
    createCommentVNode(" Add rows "),
    createBaseVNode("button", {
      class: "button is-light",
      "data-testid": "mass-data-insert-add-button",
      onClick: $setup.onClickAdd
    }, [
      _cache[0] || (_cache[0] = createBaseVNode("span", { class: "icon is-small" }, [
        createBaseVNode("i", { class: "fas fa-plus" })
      ], -1 /* CACHED */)),
      createBaseVNode("span", null, toDisplayString($setup.SessionUser.objects.global.language.add), 1 /* TEXT */)
    ]),
    createCommentVNode(" Clear rows "),
    createBaseVNode("button", {
      class: "button is-danger is-light",
      "data-testid": "mass-data-insert-clear-button",
      onClick: $setup.onClickClear
    }, [
      _cache[1] || (_cache[1] = createBaseVNode("span", { class: "icon is-small" }, [
        createBaseVNode("i", { class: "fas fa-trash" })
      ], -1 /* CACHED */)),
      createBaseVNode("span", null, toDisplayString($setup.SessionUser.objects.global.language.clear), 1 /* TEXT */)
    ])
  ]))
}
const MassDataInsertControls = /*#__PURE__*/_export_sfc(_sfc_main$1G, [['render',_sfc_render$11],['__file',"MassDataInsertControls.vue"]]);

// Emits

const _sfc_main$1F = {
  __name: 'MassDataInsertButtonSave',
  emits: ["onClickSave"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const emit = __emit;
const onClickSave = () => {
    // Save the dataRows
    const saveFunction = getSaveFunction();
    if (saveFunction) {
        saveFunction(getDataRows());
    } else {
        console.error("No save function defined");
    }
    // Emit the event
    emit("onClickSave");
};


const __returned__ = { emit, onClickSave, getDataColumns, getDataRows, getSaveFunction, setDataRows, ref, computed, SessionUser };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$S = ["disabled"];

function _sfc_render$10(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock(Fragment, null, [
    createCommentVNode(" Confirm, save and close "),
    createBaseVNode("button", {
      class: "button is-light is-fullwidth",
      "data-testid": "mass-data-insert-save-button",
      disabled: $setup.getDataRows().length === 0,
      onClick: $setup.onClickSave
    }, [
      _cache[0] || (_cache[0] = createBaseVNode("span", { class: "icon is-small" }, [
        createBaseVNode("i", { class: "fas fa-plus" })
      ], -1 /* CACHED */)),
      createBaseVNode("span", null, toDisplayString($setup.SessionUser.objects.global.language.add) + toDisplayString($setup.getDataRows().length > 0 ? ( ' ' + $setup.getDataRows().length + ' ' + $setup.SessionUser.objects.global.language.rows ) : ''), 1 /* TEXT */)
    ], 8 /* PROPS */, _hoisted_1$S)
  ], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */))
}
const MassDataInsertButtonSave = /*#__PURE__*/_export_sfc(_sfc_main$1F, [['render',_sfc_render$10],['__file',"MassDataInsertButtonSave.vue"]]);

const _sfc_main$1E = {
  __name: 'MassDataInsertProgress',
  setup(__props, { expose: __expose }) {
  __expose();


const __returned__ = { progress, ref, computed, SessionUser };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$R = { class: "level" };
const _hoisted_2$H = { class: "level-item has-text-centered" };
const _hoisted_3$D = { class: "heading" };
const _hoisted_4$C = { class: "title" };
const _hoisted_5$B = { class: "level-item has-text-centered" };
const _hoisted_6$z = { class: "heading" };
const _hoisted_7$x = { class: "title" };
const _hoisted_8$w = { class: "level-item has-text-centered" };
const _hoisted_9$u = { class: "heading" };
const _hoisted_10$t = { class: "title" };
const _hoisted_11$p = { class: "level-item has-text-centered" };
const _hoisted_12$n = { class: "heading" };
const _hoisted_13$l = { class: "title" };
const _hoisted_14$j = { class: "level-item has-text-centered" };
const _hoisted_15$i = { class: "heading" };
const _hoisted_16$i = { class: "title" };

function _sfc_render$$(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", null, [
    createCommentVNode(" Level "),
    createBaseVNode("nav", _hoisted_1$R, [
      createBaseVNode("div", _hoisted_2$H, [
        createBaseVNode("div", null, [
          createBaseVNode("p", _hoisted_3$D, toDisplayString($setup.SessionUser.objects.global.language.waiting), 1 /* TEXT */),
          createBaseVNode("p", _hoisted_4$C, toDisplayString($setup.progress.pending.length), 1 /* TEXT */)
        ])
      ]),
      createBaseVNode("div", _hoisted_5$B, [
        createBaseVNode("div", null, [
          createBaseVNode("p", _hoisted_6$z, toDisplayString($setup.SessionUser.objects.global.language.in_progress), 1 /* TEXT */),
          createBaseVNode("p", _hoisted_7$x, toDisplayString($setup.progress.processing.length), 1 /* TEXT */)
        ])
      ]),
      createBaseVNode("div", _hoisted_8$w, [
        createBaseVNode("div", null, [
          createBaseVNode("p", _hoisted_9$u, toDisplayString($setup.SessionUser.objects.global.language.succeeded), 1 /* TEXT */),
          createBaseVNode("p", _hoisted_10$t, toDisplayString($setup.progress.completed.length), 1 /* TEXT */)
        ])
      ]),
      createBaseVNode("div", _hoisted_11$p, [
        createBaseVNode("div", null, [
          createBaseVNode("p", _hoisted_12$n, toDisplayString($setup.SessionUser.objects.global.language.failed), 1 /* TEXT */),
          createBaseVNode("p", _hoisted_13$l, toDisplayString($setup.progress.failed.length), 1 /* TEXT */)
        ])
      ]),
      createBaseVNode("div", _hoisted_14$j, [
        createBaseVNode("div", null, [
          createBaseVNode("p", _hoisted_15$i, toDisplayString($setup.SessionUser.objects.global.language.total), 1 /* TEXT */),
          createBaseVNode("p", _hoisted_16$i, toDisplayString($setup.progress.total), 1 /* TEXT */)
        ])
      ])
    ])
  ]))
}
const MassDataInsertProgress = /*#__PURE__*/_export_sfc(_sfc_main$1E, [['render',_sfc_render$$],['__file',"MassDataInsertProgress.vue"]]);

// Re-run function - clears progress and re-triggers save with existing data

const _sfc_main$1D = {
  __name: 'MassDataInserterModal',
  props: {
  onClose: {
    type: Function,
    default: () => {}
  }
},
  emits: ["closeModal", "saveChanges"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const t = i18n.global.t;
const onClickRerun = () => {
  clearProgress();
  const saveFunction = getSaveFunction();
  if (saveFunction) {
    saveFunction(getDataRows());
  }
};

// Check if re-run should be enabled (has data rows and has completed/failed items)
const canRerun = () => {
  const p = progress.value;
  return getDataRows().length > 0 && (p.completed.length > 0 || p.failed.length > 0) && p.processing.length === 0 && p.pending.length === 0;
};

// Remove passing (completed) items from the data rows
const onClickRemovePassingItems = () => {
  const completedItems = getCompleted();
  if (completedItems.length === 0) return;
  
  // Filter out completed items from data rows
  const currentRows = getDataRows();
  const completedIds = new Set(completedItems.map(item => item.id));
  const filteredRows = currentRows.filter(row => !completedIds.has(row.id));
  setDataRows(filteredRows);
  
  // Also filter out completed responses
  const currentResponses = getResponses();
  const filteredResponses = currentResponses.filter(r => !completedIds.has(r.object?.id));
  setResponses(filteredResponses);
  
  // Clear completed items
  setCompleted([]);
};

// Check if remove passing items should be enabled
const canRemovePassingItems = () => {
  const p = progress.value;
  return p.completed.length > 0 && p.processing.length === 0 && p.pending.length === 0;
};

// Export data rows to a JSON file
const onClickExport = () => {
  const dataRows = getDataRows();
  if (dataRows.length === 0) return;
  
  // Create export object with metadata
  const exportData = {
    exportedAt: new Date().toISOString(),
    title: getTitle(),
    items: dataRows.map(row => {
      // Remove function properties from the row
      const cleanRow = {};
      for (const key in row) {
        if (typeof row[key] !== 'function') {
          cleanRow[key] = row[key];
        }
      }
      return cleanRow;
    })
  };
  
  // Create blob and download
  const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `mass-data-export-${new Date().toISOString().split('T')[0]}.json`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

// Check if export should be enabled
const canExport = () => {
  return getDataRows().length > 0;
};

// File input ref for import
const fileInput = ref(null);

// Trigger file input click
const onClickImport = () => {
  fileInput.value?.click();
};

// Handle file import
const onFileImport = (event) => {
  const file = event.target.files?.[0];
  if (!file) return;
  
  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const importData = JSON.parse(e.target.result);
      if (importData.items && Array.isArray(importData.items)) {
        // Clear current progress
        clearProgress();
        // Use the parsed data format function to properly set up the rows
        const parseFunction = getParsedDataFormatFunction();
        parseFunction(importData.items);
      } else {
        alert(t('modals.invalid_file_format'));
      }
    } catch (error) {
      console.error('Error parsing import file:', error);
      alert(t('modals.could_not_read_file'));
    }
  };
  reader.readAsText(file);
  
  // Reset file input so the same file can be imported again
  event.target.value = '';
};

const props = __props;

const emit = __emit;

const closeModal = () => {
  emit("closeModal");
  if (props.onClose) {
    props.onClose();
  }
};

// Listen for esc key to close the modal
const handleKeydown = (event) => {
  if (event.key === "Escape") {
    closeModal();
  }
};
const modal = ref(null);
window.addEventListener("keydown", handleKeydown);

const __returned__ = { t, onClickRerun, canRerun, onClickRemovePassingItems, canRemovePassingItems, onClickExport, canExport, fileInput, onClickImport, onFileImport, props, emit, closeModal, handleKeydown, modal, ref, get i18n() { return i18n }, SessionUser, getTitle, getDataColumns, getDataRows, setDataRows, getSaveFunction, clearProgress, progress, getCompleted, setCompleted, getResponses, setResponses, getParsedDataFormatFunction, MassDataInsertTable, MassDataInsertControls, MassDataInsertButtonSave, MassDataInsertProgress };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$Q = {
  class: "modal is-active",
  ref: "modal",
  "data-testid": "mass-data-inserter-modal"
};
const _hoisted_2$G = { class: "modal-card" };
const _hoisted_3$C = { class: "modal-card-head" };
const _hoisted_4$B = { class: "modal-card-title" };
const _hoisted_5$A = { class: "modal-card-body" };
const _hoisted_6$y = { class: "notification is-warning" };
const _hoisted_7$w = { class: "modal-card-foot" };
const _hoisted_8$v = {
  class: "buttons is-fullwidth",
  style: {"width":"100%"}
};
const _hoisted_9$t = ["disabled"];
const _hoisted_10$s = ["disabled"];
const _hoisted_11$o = ["disabled"];

function _sfc_render$_(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$Q, [
    createBaseVNode("div", {
      class: "modal-background",
      onClick: $setup.closeModal
    }),
    createBaseVNode("div", _hoisted_2$G, [
      createBaseVNode("header", _hoisted_3$C, [
        createBaseVNode("p", _hoisted_4$B, toDisplayString($setup.getTitle()), 1 /* TEXT */),
        createBaseVNode("button", {
          class: "delete",
          "aria-label": "close",
          onClick: $setup.closeModal
        })
      ]),
      createBaseVNode("section", _hoisted_5$A, [
        createBaseVNode("div", _hoisted_6$y, [
          createBaseVNode("strong", null, toDisplayString($setup.t('modals.under_development')), 1 /* TEXT */),
          createBaseVNode("p", null, toDisplayString($setup.t('modals.mass_data_warning')), 1 /* TEXT */)
        ]),
        createCommentVNode(" Controls "),
        createVNode($setup["MassDataInsertControls"]),
        createCommentVNode(" Progress "),
        createVNode($setup["MassDataInsertProgress"]),
        createCommentVNode(" Table "),
        createVNode($setup["MassDataInsertTable"])
      ]),
      createBaseVNode("footer", _hoisted_7$w, [
        createBaseVNode("div", _hoisted_8$v, [
          createVNode($setup["MassDataInsertButtonSave"]),
          createBaseVNode("button", {
            class: "button is-warning is-fullwidth",
            disabled: !$setup.canRerun(),
            onClick: $setup.onClickRerun
          }, [
            _cache[0] || (_cache[0] = createBaseVNode("span", { class: "icon is-small" }, [
              createBaseVNode("i", { class: "fas fa-redo" })
            ], -1 /* CACHED */)),
            createBaseVNode("span", null, toDisplayString($setup.t('modals.run_again')), 1 /* TEXT */)
          ], 8 /* PROPS */, _hoisted_9$t),
          createBaseVNode("button", {
            class: "button is-success is-fullwidth",
            disabled: !$setup.canRemovePassingItems(),
            onClick: $setup.onClickRemovePassingItems
          }, [
            _cache[1] || (_cache[1] = createBaseVNode("span", { class: "icon is-small" }, [
              createBaseVNode("i", { class: "fas fa-check-circle" })
            ], -1 /* CACHED */)),
            createBaseVNode("span", null, toDisplayString($setup.t('modals.remove_passed')), 1 /* TEXT */)
          ], 8 /* PROPS */, _hoisted_10$s),
          createBaseVNode("button", {
            class: "button is-info is-fullwidth",
            disabled: !$setup.canExport(),
            onClick: $setup.onClickExport
          }, [
            _cache[2] || (_cache[2] = createBaseVNode("span", { class: "icon is-small" }, [
              createBaseVNode("i", { class: "fas fa-download" })
            ], -1 /* CACHED */)),
            createBaseVNode("span", null, toDisplayString($setup.t('modals.export')), 1 /* TEXT */)
          ], 8 /* PROPS */, _hoisted_11$o),
          createBaseVNode("button", {
            class: "button is-link is-fullwidth",
            onClick: $setup.onClickImport
          }, [
            _cache[3] || (_cache[3] = createBaseVNode("span", { class: "icon is-small" }, [
              createBaseVNode("i", { class: "fas fa-upload" })
            ], -1 /* CACHED */)),
            createBaseVNode("span", null, toDisplayString($setup.t('modals.import')), 1 /* TEXT */)
          ]),
          createBaseVNode("input", {
            type: "file",
            ref: "fileInput",
            accept: ".json",
            style: {"display":"none"},
            onChange: $setup.onFileImport
          }, null, 544 /* NEED_HYDRATION, NEED_PATCH */)
        ])
      ])
    ])
  ], 512 /* NEED_PATCH */))
}
const MassDataInserterModal = /*#__PURE__*/_export_sfc(_sfc_main$1D, [['render',_sfc_render$_],['__file',"MassDataInserterModal.vue"]]);

const showMassDataInsertModal = async (onSuccessFunction = () => {}) => {
  // Create a container element for the Vue component
  const div = document.createElement('div');

  // Dynamically create and mount the Vue component
  // And add a prop to the component "onCustomerSelected"
  const app = createApp(MassDataInserterModal, {
    onClose: () => {
      // Close the modal
      Swal.close();
      // Return
    }
  });


  // Mount the Vue app to the dynamically created `div`
  app.mount(div);

  // Show SweetAlert2 dialog with the Vue component rendered inside
  await Swal.fire({
    html: div, // Include the Vue component’s container
    showCancelButton: false,
    showConfirmButton: false,
    allowOutsideClick: false,
    heightAuto: true,
    // Add custom CSS to the modal 80% width on open
    didOpen(popup) {
      // Add custom CSS to the ".modal-card" element
      const modalCard = popup.querySelector('.modal-card');
      if (modalCard) {
        modalCard.style.width = '80%';
      }
    },
    didDestroy: () => {
      // Clean up the Vue app when the modal is closed
      app.unmount();
    }
  }).finally(() => {
    // Return the selected invoice collection ID
    return onSuccessFunction()
  });
};

const _sfc_main$1C = {};
const showModal = /*#__PURE__*/_export_sfc(_sfc_main$1C, [['__file',"showModal.vue"]]);

const _sfc_main$1B = {
  __name: 'CollectedOrderInvoicesListPagination',
  props: {
  setCustomerFilter: {
    type: Number,
    default: null
  },
  hideSearch: {
    type: Boolean,
    default: false
  },
  autoLoad: {
    type: Boolean,
    default: true
  },
  onlyReadyToInvoice: {
    type: Boolean,
    default: false
  },
  tableProps: {
    type: Object,
    default: () => ({})
  },
  displayClosed: {
    type: Boolean,
    default: true
  },
  displayBooked: {
    type: Boolean,
    default: true
  },
},
  setup(__props, { expose: __expose }) {
  __expose();


const props = __props;
const { t } = useI18n();

// Mass compare functionality
const isMassComparing = ref(false);

// Function to fetch all pages of invoices
const fetchAllPages = async () => {
  const safeItemsPerPage = Math.max(1, Number(metaItemsPerPage.value || 0));
  const totalPages = Math.ceil(Number(metaTotalItems.value || 0) / safeItemsPerPage);
  const token = localStorage.getItem('token');

  if (!token || totalPages <= 1) {
    return list.value;
  }

  // If more than 20 pages, ask user for confirmation
  if (totalPages > 20) {
    const result = await Swal.fire({
      icon: 'warning',
      title: 'Mange sider at hente',
      html: `Der er <b>${totalPages}</b> sider med fakturaer (${metaTotalItems.value} i alt).<br>Er du sikker på, at du vil sammenligne dem alle?`,
      showCancelButton: true,
      confirmButtonText: 'Ja, fortsæt',
      cancelButtonText: 'Annuller',
    });
    
    if (!result.isConfirmed) {
      return null; // User cancelled
    }
  }

  // Show loading dialog
  Swal.fire({
    title: 'Henter alle sider...',
    html: `Henter side <b>1</b> af <b>${totalPages}</b>...`,
    allowOutsideClick: false,
    allowEscapeKey: false,
    showConfirmButton: false,
    didOpen: () => {
      Swal.showLoading();
    }
  });

  // Start with current page data
  let allInvoices = [...list.value];
  
  // Fetch remaining pages
  for (let page = 2; page <= totalPages; page++) {
    Swal.update({
      html: `Henter side <b>${page}</b> af <b>${totalPages}</b>...`,
    });
    
    try {
      const response = await axios.get(API_URL + endpoint.value, {
        params: {
          page: page,
          limit: safeItemsPerPage,
          search: metaSearch.value,
          filters: filter.value,
          order: `${orderBy.value}:${orderDirection.value}`,
        },
        headers: {
          Authorization: `Bearer ${token}`
        }
      });

      allInvoices = [...allInvoices, ...(response?.data?.data || [])];
    } catch (error) {
      console.error(`Error fetching page ${page}:`, error);
      Swal.fire({
        icon: 'error',
        title: 'Fejl ved hentning',
        text: `Kunne ikke hente side ${page}. Prøv igen.`,
      });
      return null;
    }
  }
  
  return allInvoices;
};

const massCompareToEconomic = async () => {
  if (!list.value || list.value.length === 0) {
    Swal.fire({
      icon: 'warning',
      title: 'Ingen fakturaer',
      text: 'Der er ingen fakturaer at sammenligne.',
      timer: 2000,
    });
    return;
  }

  isMassComparing.value = true;

  try {
    // Fetch all pages of invoices
    const allInvoices = await fetchAllPages();
    if (allInvoices === null) {
      return;
    }

    // Initialize the data structure and clear previous progress
    init();
    clearProgress();
    setTitle('Sammenlign fakturaer med E-conomic');

    // Parse the invoices to populate the data rows
    getParsedDataFormatFunction()(allInvoices);

    // Show the mass data inserter modal (same display as vehicle inserter)
    await showMassDataInsertModal();
  } finally {
    isMassComparing.value = false;
  }
};

if (!props.onlyReadyToInvoice || props.onlyReadyToInvoice === false) {
  setEndpoint("/collected-invoices", false);
} else {
  setEndpoint("/collected-invoices/ready-to-invoice", false);
}
setOrder("closed_at", "asc", false);
// Hide the search field if the prop is set to true
setHideSearchField(props.hideSearch);

if (props.setCustomerFilter) {
  setFilter("customer_number", props.setCustomerFilter, false);
}

if (!props.displayClosed) {
  setFilter("closed_at", 'is_null', false);
}

if (!props.displayBooked) {
  setFilter("booked_invoice_id", 'is_null', false);
}

if (props.autoLoad) {
  loadList();
}


const __returned__ = { props, t, isMassComparing, fetchAllPages, massCompareToEconomic, CollectedOrderInvoicesDefaultTable, ref, isLoading: isLoading$1, list, loadList, metaCurrentPage, metaItemsPerPage, metaTotalItems, setEndpoint, setMetaItemsPerPage, setPage, metaSearch, search, setFilter, setOrder, hideSearchField, setHideSearchField, filter, orderBy, orderDirection, endpoint, PaginationNavigation, SessionUser, LoadButtonWhileAwait, PaginationDisplay, get Swal() { return Swal }, initCompareDataStructure: init, clearProgress, getParsedDataFormatFunction, setTitle, showMassDataInsertModal, get axios() { return axios }, get API_URL() { return API_URL }, get useI18n() { return useI18n } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$P = ["placeholder"];
const _hoisted_2$F = { class: "buttons" };
const _hoisted_3$B = ["disabled"];

function _sfc_render$Z(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock(Fragment, null, [
    (!$setup.hideSearchField)
      ? (openBlock(), createElementBlock("input", {
          key: 0,
          onInput: _cache[0] || (_cache[0] = $event => ($setup.search($event.target.value))),
          class: "input",
          type: "text",
          placeholder: _ctx.$t('global.search_for') + ' ' + $setup.SessionUser.objects.collectedOrderInvoices.meta.labels.single
        }, null, 40 /* PROPS, NEED_HYDRATION */, _hoisted_1$P))
      : createCommentVNode("v-if", true),
    createVNode($setup["PaginationDisplay"], {
      metaItemsPerPage: $setup.metaItemsPerPage,
      loadFunction: $setup.loadList,
      isLoading: $setup.isLoading,
      setMetaItemsPerPage: $setup.setMetaItemsPerPage
    }, null, 8 /* PROPS */, ["metaItemsPerPage", "loadFunction", "isLoading", "setMetaItemsPerPage"]),
    createVNode($setup["CollectedOrderInvoicesDefaultTable"], { objects: $setup.list }, null, 8 /* PROPS */, ["objects"]),
    createVNode($setup["PaginationNavigation"], {
      currentPage: $setup.metaCurrentPage,
      totalPages: Math.ceil($setup.metaTotalItems / $setup.metaItemsPerPage),
      loadFunction: $setup.loadList,
      setPage: $setup.setPage,
      isLoading: $setup.isLoading
    }, null, 8 /* PROPS */, ["currentPage", "totalPages", "loadFunction", "setPage", "isLoading"]),
    createBaseVNode("div", _hoisted_2$F, [
      createVNode($setup["LoadButtonWhileAwait"], {
        class: "is-dark",
        isLoading: $setup.isLoading,
        loadFunction: $setup.loadList,
        icon: "fas fa-sync-alt"
      }, {
        default: withCtx(() => [
          createTextVNode(toDisplayString($setup.t('pagination.reload')), 1 /* TEXT */)
        ]),
        _: 1 /* STABLE */
      }, 8 /* PROPS */, ["isLoading", "loadFunction"]),
      createBaseVNode("button", {
        class: "button is-info",
        onClick: $setup.massCompareToEconomic,
        disabled: $setup.isMassComparing || $setup.isLoading || !$setup.list || $setup.list.length === 0
      }, [...(_cache[1] || (_cache[1] = [
        createBaseVNode("span", { class: "icon" }, [
          createBaseVNode("i", { class: "fas fa-balance-scale" })
        ], -1 /* CACHED */),
        createBaseVNode("span", null, "Sammenlign alle med E-conomic", -1 /* CACHED */)
      ]))], 8 /* PROPS */, _hoisted_3$B)
    ])
  ], 64 /* STABLE_FRAGMENT */))
}
const CollectedOrderInvoicesListPagination = /*#__PURE__*/_export_sfc(_sfc_main$1B, [['render',_sfc_render$Z],['__file',"CollectedOrderInvoicesListPagination.vue"]]);

/**
 * ThemeConfig.vue
 * This file contains the color configurations for the application.
 * It defines global colors, menu colors, header colors, button colors, and input colors.
 */
const GlobalColors = {
  /** The primary color of the application */
  primaryColor: "#0787BB",
  /** The secondary color of the application */
  secondaryColor: "#063651",
  /** The secondary background color of the application */
  secondaryBackgroundColorDark: "#363636",
  /** The text color of the application */
  textColor: "#c8c8c8",
  /** The light text color of the application */
  lightTextColor: "#ffffff",
  /** The dark text color of the application */
  textColorDark: "#5a5a5a",
  /** The hover color of the application */
  hoverColor: "#e6e6e6",
  /** The active color of the application */
  activeColor: "#e6e6e6",
  /** The background color of the application */
  backgroundColor: "#e6efff",
  /** The secondary background color of the application */
  secondaryBackgroundColor: "#063651",
  /** Active Background Color */
  activeBackgroundColor: "#475c7c",
  /** Disabled Background Color */
  disabledBackgroundColor: "#f9f9f9",
  /** Disabled Text Color */
  disabledTextColor: "#c8c8c8",
};

const MenuColors = {
  /** The background color of the menu */
  backgroundColor: GlobalColors.secondaryBackgroundColor,
  /** The text color of the menu */
  textColor: GlobalColors.textColor,
  /** The hover color of the menu */
  hoverColor: GlobalColors.hoverColor,
  /** The active color of the menu */
  activeColor: GlobalColors.primaryColor,
  /** The active background color of the menu */
  activeBackgroundColor: GlobalColors.activeBackgroundColor,
  /** The parent background color of the menu */
  parentBackgroundColor: GlobalColors.secondaryBackgroundColor,
  /** The parent text color of the menu */
  parentTextColor: GlobalColors.textColor,
  /** The parent hover color of the menu */
  parentHoverColor: GlobalColors.hoverColor,
  /** The parent active color of the menu */
  parentActiveColor: GlobalColors.activeColor,
  /** The child background color of the menu */
  childBackgroundColor: GlobalColors.secondaryBackgroundColor,
  /** The child text color of the menu */
  childTextColor: GlobalColors.textColor,
  /** The child hover color of the menu */
  childHoverColor: GlobalColors.hoverColor,
  /** The child active color of the menu */
  childActiveColor: GlobalColors.activeColor,
};

const HeaderColors = {
  /** The background color of the header */
  backgroundColor: GlobalColors.primaryColor,
  /** The text color of the header */
  textColor: GlobalColors.lightTextColor,
  /** The secondary text color of the header */
  textColorSecondary: GlobalColors.secondaryBackgroundColorDark,
};

const ButtonColors = {
  success: {
    /** The background color of the button */
    backgroundColor: "#00be29",
    /** The text color of the button */
    textColor: GlobalColors.lightTextColor,
    /** The hover color of the button */
    hoverColor: "#00a226",
    /** The active color of the button */
    activeColor: "#00a226",
  },
  warning: {
    /** The background color of the button */
    backgroundColor: "#f0ad4e",
    /** The text color of the button */
    textColor: GlobalColors.lightTextColor,
    /** The hover color of the button */
    hoverColor: "#ec971f",
    /** The active color of the button */
    activeColor: "#ec971f",
  },
  default: {
    /** The background color of the button */
    backgroundColor: GlobalColors.secondaryBackgroundColor,
    /** The text color of the button */
    textColor: GlobalColors.lightTextColor,
    /** The hover color of the button */
    hoverColor: GlobalColors.hoverColor,
    /** The active color of the button */
    activeColor: GlobalColors.activeColor,
    /** The secondary background color of the button */
    secondaryBackgroundColor: GlobalColors.secondaryBackgroundColorDark,
  },
};

const InputColors = {
  default: {
    /** The background color of the input */
    backgroundColor: "#f9f9f9",
    /** The text color of the input */
    textColor: GlobalColors.textColor,
    /** The hover color of the input */
    hoverColor: GlobalColors.hoverColor,
    /** The active color of the input */
    activeColor: GlobalColors.activeColor,
  },
};

const Colors = {
  /** The colors of the application */
  global: GlobalColors,
  /** The colors of the menus */
  menus: MenuColors,
  /** The colors of the headers */
  headers: HeaderColors,
  /** The colors of the buttons */
  buttons: ButtonColors,
  /** The colors of the inputs */
  inputs: InputColors,
};

const _sfc_main$1A = {};
const ThemeConfig = /*#__PURE__*/_export_sfc(_sfc_main$1A, [['__file',"ThemeConfig.vue"]]);

const _sfc_main$1z = {
  __name: 'PageTitle',
  props: {
  title: String,
  subtitle: String
},
  setup(__props, { expose: __expose }) {
  __expose();




const __returned__ = { Colors };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$O = { class: "mb-4" };
const _hoisted_2$E = { class: "columns is-vcentered is-mobile" };
const _hoisted_3$A = { class: "column" };
const _hoisted_4$A = {
  style: {"margin-bottom":"0"},
  class: "title is-4 mb-4"
};
const _hoisted_5$z = {
  key: 0,
  class: "is-size-6"
};
const _hoisted_6$x = { class: "column is-narrow" };
const _hoisted_7$v = { class: "column is-narrow" };

function _sfc_render$Y(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$O, [
    createBaseVNode("div", _hoisted_2$E, [
      createBaseVNode("div", _hoisted_3$A, [
        createBaseVNode("h1", _hoisted_4$A, toDisplayString($props.title), 1 /* TEXT */),
        ($props.subtitle)
          ? (openBlock(), createElementBlock("p", _hoisted_5$z, toDisplayString($props.subtitle), 1 /* TEXT */))
          : createCommentVNode("v-if", true)
      ]),
      createBaseVNode("div", _hoisted_6$x, [
        renderSlot(_ctx.$slots, "navigation")
      ]),
      createBaseVNode("div", _hoisted_7$v, [
        renderSlot(_ctx.$slots, "buttons")
      ])
    ]),
    renderSlot(_ctx.$slots, "default")
  ]))
}
const PageTitle = /*#__PURE__*/_export_sfc(_sfc_main$1z, [['render',_sfc_render$Y],['__file',"PageTitle.vue"]]);

const _sfc_main$1y = {  };

const _hoisted_1$N = { class: "columns is-multiline" };
const _hoisted_2$D = { class: "column is-full" };
const _hoisted_3$z = { class: "column is-8" };
const _hoisted_4$z = { class: "column is-4" };
const _hoisted_5$y = { class: "column is-full" };

function _sfc_render$X(_ctx, _cache) {
  return (openBlock(), createElementBlock("div", _hoisted_1$N, [
    createCommentVNode(" Top column "),
    createBaseVNode("div", _hoisted_2$D, [
      renderSlot(_ctx.$slots, "content-top")
    ]),
    createCommentVNode(" Left column "),
    createBaseVNode("div", _hoisted_3$z, [
      renderSlot(_ctx.$slots, "content-left")
    ]),
    createCommentVNode(" Summary of the new invoicing billing period "),
    createBaseVNode("div", _hoisted_4$z, [
      renderSlot(_ctx.$slots, "summary"),
      createCommentVNode(" Additional slot "),
      renderSlot(_ctx.$slots, "content-right")
    ]),
    createCommentVNode(" Bottom column "),
    createBaseVNode("div", _hoisted_5$y, [
      renderSlot(_ctx.$slots, "content-bottom")
    ])
  ]))
}
const InvoicingBillingPeriodLayoutDefault = /*#__PURE__*/_export_sfc(_sfc_main$1y, [['render',_sfc_render$X],['__file',"InvoicingBillingPeriodLayoutDefault.vue"]]);

const startDate = ref(new Date((/* @__PURE__ */ new Date()).setHours(0, 0, 0, 0)));
const endDate = ref(new Date((/* @__PURE__ */ new Date()).setHours(23, 59, 59, 999)));
const variablesDates = {
  start: startDate,
  end: endDate
};
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};
const formatTime = (date) => {
  return date.toTimeString().split(" ")[0];
};
const setSelection = (start, end) => {
  const nextStart = new Date(start);
  nextStart.setHours(0, 0, 0, 0);
  const nextEnd = new Date(end);
  nextEnd.setHours(23, 59, 59, 999);
  startDate.value = nextStart;
  endDate.value = nextEnd;
};
const functionsDates = {
  formatDate,
  formatTime,
  setSelection
};
const formattedStartDate = computed(() => formatDate(startDate.value));
const formattedEndDate = computed(() => formatDate(endDate.value));
const formattedStartTime = computed(() => formatTime(startDate.value));
const formattedEndTime = computed(() => formatTime(endDate.value));
const formattedDateRange = computed(() => {
  return `${formattedStartDate.value} - ${formattedEndDate.value}`;
});
const computedDates = {
  formattedStartDate,
  formattedEndDate,
  formattedStartTime,
  formattedEndTime,
  formattedDateRange,
  isEntireMonth: computed(() => {
    const isSameMonth = startDate.value.getFullYear() === endDate.value.getFullYear() && startDate.value.getMonth() === endDate.value.getMonth();
    const isFirstDayOfMonth = startDate.value.getDate() === 1;
    const isLastDayOfMonth = endDate.value.getDate() === new Date(endDate.value.getFullYear(), endDate.value.getMonth() + 1, 0).getDate();
    return isSameMonth && isFirstDayOfMonth && isLastDayOfMonth;
  }),
  isMultiMonthSelection: computed(() => {
    return startDate.value.getMonth() !== endDate.value.getMonth() || startDate.value.getFullYear() !== endDate.value.getFullYear();
  })
};
const dates = {
  variables: variablesDates,
  functions: functionsDates,
  computed: computedDates
};
const _sfc_main$1x = {
  name: "InvoicingBillingPeriodImportDates",
  setup() {
    return {
      dates
    };
  }
};

const InvoicingBillingPeriodImportDates = /* @__PURE__ */ _export_sfc(_sfc_main$1x, [["__file", "InvoicingBillingPeriodImportDates.vue"]]);

const COLLECTED_INVOICE_ENQUEUE_ENDPOINT = "/collected-invoices/economic";
const COLLECTED_INVOICE_STATUS_ENDPOINT = "/collected-invoices/economic/queue/status";
const COLLECTED_INVOICE_RETRY_ENDPOINT = "/collected-invoices/economic/queue/retry";
const pollIntervalMs = DEFAULT_ECONOMIC_QUEUE_POLL_INTERVAL_MS;
const periodRefreshSignal = ref({
  sequence: 0,
  customerNumbers: [],
  invoiceCollectionIds: []
});
const notifyPeriodRefresh = (invoiceCollectionId) => {
  const parsedInvoiceCollectionId = parseInvoiceCollectionId(invoiceCollectionId);
  if (!parsedInvoiceCollectionId) {
    return;
  }
  const customerNumber = parseInvoiceCollectionId(
    invoiceCollectionCustomerNumbers.value[parsedInvoiceCollectionId] ?? null
  );
  if (!customerNumber) {
    return;
  }
  markPeriodRefreshLoading([customerNumber], [parsedInvoiceCollectionId]);
  periodRefreshSignal.value = {
    sequence: periodRefreshSignal.value.sequence + 1,
    customerNumbers: [customerNumber],
    invoiceCollectionIds: [parsedInvoiceCollectionId]
  };
};
const invoiceCollectionQueueInProgress = ref([]);
const invoiceCollectionQueueFailed = ref([]);
const invoiceCollectionQueueSuccess = ref([]);
const invoiceCollectionQueue = ref([]);
const collectionQueueLog = ref([]);
const invoiceCollectionQueueJobs = ref({});
const invoiceCollectionQueueJobIds = ref({});
const invoiceCollectionCustomerNumbers = ref({});
const periodCustomerRefreshInProgress = ref([]);
const periodInvoiceCollectionRefreshInProgress = ref([]);
const invoiceCollectionMaxConnections = 7;
const wait = (durationMs) => new Promise((resolve) => {
  setTimeout(resolve, durationMs);
});
const parseInvoiceCollectionId = (value) => {
  const parsed = Number.parseInt(String(value), 10);
  if (!Number.isInteger(parsed) || parsed <= 0) {
    return null;
  }
  return parsed;
};
const parseCustomerNumber = (value) => {
  return parseInvoiceCollectionId(value);
};
const normalizeUniqueIds = (ids) => Array.from(
  new Set(
    (Array.isArray(ids) ? ids : []).map((id) => parseInvoiceCollectionId(id)).filter((id) => id !== null)
  )
);
const rememberInvoiceCollectionContext = (invoiceCollectionId, context = {}) => {
  const parsedInvoiceCollectionId = parseInvoiceCollectionId(invoiceCollectionId);
  const customerNumber = parseCustomerNumber(context.customerNumber ?? null);
  if (!parsedInvoiceCollectionId || !customerNumber) {
    return;
  }
  invoiceCollectionCustomerNumbers.value = {
    ...invoiceCollectionCustomerNumbers.value,
    [parsedInvoiceCollectionId]: customerNumber
  };
};
const markPeriodRefreshLoading = (customerNumbers = [], invoiceCollectionIds = []) => {
  const normalizedCustomerNumbers = normalizeUniqueIds(customerNumbers);
  const normalizedInvoiceCollectionIds = normalizeUniqueIds(invoiceCollectionIds);
  periodCustomerRefreshInProgress.value = Array.from(/* @__PURE__ */ new Set([
    ...periodCustomerRefreshInProgress.value,
    ...normalizedCustomerNumbers
  ]));
  periodInvoiceCollectionRefreshInProgress.value = Array.from(/* @__PURE__ */ new Set([
    ...periodInvoiceCollectionRefreshInProgress.value,
    ...normalizedInvoiceCollectionIds
  ]));
};
const finishPeriodRefresh = (customerNumbers = [], invoiceCollectionIds = []) => {
  const normalizedCustomerNumbers = normalizeUniqueIds(customerNumbers);
  const normalizedInvoiceCollectionIds = normalizeUniqueIds(invoiceCollectionIds);
  periodInvoiceCollectionRefreshInProgress.value = periodInvoiceCollectionRefreshInProgress.value.filter(
    (invoiceCollectionId) => !normalizedInvoiceCollectionIds.includes(invoiceCollectionId)
  );
  const customersWithRemainingCollectionRefreshes = new Set(
    Object.entries(invoiceCollectionCustomerNumbers.value).filter(([invoiceCollectionId]) => {
      const parsedInvoiceCollectionId = parseInvoiceCollectionId(invoiceCollectionId);
      return parsedInvoiceCollectionId ? periodInvoiceCollectionRefreshInProgress.value.includes(parsedInvoiceCollectionId) : false;
    }).map(([, customerNumber]) => customerNumber)
  );
  periodCustomerRefreshInProgress.value = periodCustomerRefreshInProgress.value.filter((customerNumber) => {
    if (!normalizedCustomerNumbers.includes(customerNumber)) {
      return true;
    }
    return customersWithRemainingCollectionRefreshes.has(customerNumber);
  });
};
const isPeriodCustomerRefreshLoading = (customerNumber) => {
  const parsedCustomerNumber = parseCustomerNumber(customerNumber);
  return parsedCustomerNumber ? periodCustomerRefreshInProgress.value.includes(parsedCustomerNumber) : false;
};
const isPeriodInvoiceCollectionRefreshLoading = (invoiceCollectionId) => {
  const parsedInvoiceCollectionId = parseInvoiceCollectionId(invoiceCollectionId);
  return parsedInvoiceCollectionId ? periodInvoiceCollectionRefreshInProgress.value.includes(parsedInvoiceCollectionId) : false;
};
const upsertCollectionQueueLog = (entry) => {
  const existingIndex = collectionQueueLog.value.findIndex((item) => item.invoiceCollectionId === entry.invoiceCollectionId);
  const existingEntry = existingIndex >= 0 ? collectionQueueLog.value[existingIndex] : null;
  const nextEntry = {
    success: entry.success ?? existingEntry?.success ?? null,
    invoiceCollectionId: entry.invoiceCollectionId,
    errorMessage: entry.errorMessage ?? existingEntry?.errorMessage ?? "",
    status: entry.status ?? existingEntry?.status ?? null,
    progressPercent: entry.progressPercent ?? existingEntry?.progressPercent ?? 0,
    progressMessage: entry.progressMessage ?? existingEntry?.progressMessage ?? "",
    result: entry.result ?? existingEntry?.result ?? null,
    isTransportError: entry.isTransportError ?? existingEntry?.isTransportError ?? false,
    jobId: entry.jobId ?? existingEntry?.jobId ?? null
  };
  if (existingIndex >= 0) {
    collectionQueueLog.value.splice(existingIndex, 1, nextEntry);
    return;
  }
  collectionQueueLog.value.push(nextEntry);
};
const setQueueJobForInvoiceCollection = (invoiceCollectionId, queueJob) => {
  invoiceCollectionQueueJobs.value = {
    ...invoiceCollectionQueueJobs.value,
    [invoiceCollectionId]: queueJob
  };
  const parsedJobId = parseInvoiceCollectionId(queueJob?.id);
  if (parsedJobId) {
    invoiceCollectionQueueJobIds.value = {
      ...invoiceCollectionQueueJobIds.value,
      [invoiceCollectionId]: parsedJobId
    };
  }
};
const removeFromQueue = (invoiceCollectionId) => {
  invoiceCollectionQueue.value = invoiceCollectionQueue.value.filter((id) => id !== invoiceCollectionId);
};
const removeFromInProgress = (invoiceCollectionId) => {
  invoiceCollectionQueueInProgress.value = invoiceCollectionQueueInProgress.value.filter((id) => id !== invoiceCollectionId);
};
const removeFromFailed = (invoiceCollectionId) => {
  invoiceCollectionQueueFailed.value = invoiceCollectionQueueFailed.value.filter((id) => id !== invoiceCollectionId);
};
const removeFromSuccess = (invoiceCollectionId) => {
  invoiceCollectionQueueSuccess.value = invoiceCollectionQueueSuccess.value.filter((id) => id !== invoiceCollectionId);
};
const ensureInProgress = (invoiceCollectionId) => {
  if (!invoiceCollectionQueueInProgress.value.includes(invoiceCollectionId)) {
    invoiceCollectionQueueInProgress.value.push(invoiceCollectionId);
  }
};
const markAsFailed = (invoiceCollectionId) => {
  removeFromQueue(invoiceCollectionId);
  removeFromSuccess(invoiceCollectionId);
  if (!invoiceCollectionQueueFailed.value.includes(invoiceCollectionId)) {
    invoiceCollectionQueueFailed.value.push(invoiceCollectionId);
  }
};
const markAsSucceeded = (invoiceCollectionId) => {
  removeFromQueue(invoiceCollectionId);
  removeFromFailed(invoiceCollectionId);
  if (!invoiceCollectionQueueSuccess.value.includes(invoiceCollectionId)) {
    invoiceCollectionQueueSuccess.value.push(invoiceCollectionId);
  }
};
const getRetryJobIdForInvoiceCollection = (invoiceCollectionId) => {
  const byInvoiceCollection = invoiceCollectionQueueJobIds.value[invoiceCollectionId];
  const parsedFromMap = parseInvoiceCollectionId(byInvoiceCollection);
  if (parsedFromMap) {
    return parsedFromMap;
  }
  const queueJobId = parseInvoiceCollectionId(invoiceCollectionQueueJobs.value[invoiceCollectionId]?.id);
  if (queueJobId) {
    return queueJobId;
  }
  return null;
};
const pollInvoiceCollectionJobUntilTerminal = async (invoiceCollectionId, jobId) => {
  while (true) {
    const { job } = await fetchEconomicTransferJobStatus({
      endpoint: COLLECTED_INVOICE_STATUS_ENDPOINT,
      jobId,
      requestFn: SessionUser.request
    });
    setQueueJobForInvoiceCollection(invoiceCollectionId, job);
    upsertCollectionQueueLog({
      success: null,
      invoiceCollectionId,
      status: job.status ?? null,
      progressPercent: Number(job.progress_percent ?? 0),
      progressMessage: String(job.progress_message ?? ""),
      errorMessage: String(job.error_message ?? ""),
      result: job.result ?? null,
      isTransportError: false,
      jobId: parseInvoiceCollectionId(job.id)
    });
    if (isEconomicQueueStatusTerminal(job.status)) {
      return job;
    }
    await wait(pollIntervalMs);
  }
};
const processInvoiceCollection = async (invoiceCollectionId, options = {}) => {
  const parsedInvoiceCollectionId = parseInvoiceCollectionId(invoiceCollectionId);
  if (!parsedInvoiceCollectionId) {
    return;
  }
  if (invoiceCollectionQueueInProgress.value.includes(parsedInvoiceCollectionId)) {
    return;
  }
  removeFromQueue(parsedInvoiceCollectionId);
  removeFromFailed(parsedInvoiceCollectionId);
  removeFromSuccess(parsedInvoiceCollectionId);
  ensureInProgress(parsedInvoiceCollectionId);
  try {
    let initialJob;
    const retryJobId = parseInvoiceCollectionId(options.retryJobId ?? null);
    if (retryJobId) {
      const { job } = await retryEconomicTransferJob({
        endpoint: COLLECTED_INVOICE_RETRY_ENDPOINT,
        jobId: retryJobId,
        requestFn: SessionUser.request
      });
      initialJob = job;
    } else {
      const payload = buildCollectedInvoiceEconomicPayload({
        id: parsedInvoiceCollectionId,
        send_as_is: false
      });
      const { job } = await enqueueEconomicTransferJob({
        endpoint: COLLECTED_INVOICE_ENQUEUE_ENDPOINT,
        payload,
        requestFn: SessionUser.request
      });
      initialJob = job;
    }
    setQueueJobForInvoiceCollection(parsedInvoiceCollectionId, initialJob);
    upsertCollectionQueueLog({
      success: null,
      invoiceCollectionId: parsedInvoiceCollectionId,
      status: initialJob.status ?? null,
      progressPercent: Number(initialJob.progress_percent ?? 0),
      progressMessage: String(initialJob.progress_message ?? ""),
      errorMessage: String(initialJob.error_message ?? ""),
      result: initialJob.result ?? null,
      isTransportError: false,
      jobId: parseInvoiceCollectionId(initialJob.id)
    });
    const queueJobId = parseInvoiceCollectionId(initialJob.id);
    if (!queueJobId) {
      throw new Error("Missing queue job id.");
    }
    const finalJob = await pollInvoiceCollectionJobUntilTerminal(parsedInvoiceCollectionId, queueJobId);
    if (finalJob.status === ECONOMIC_QUEUE_STATUS.COMPLETED) {
      markAsSucceeded(parsedInvoiceCollectionId);
      upsertCollectionQueueLog({
        success: true,
        invoiceCollectionId: parsedInvoiceCollectionId,
        status: finalJob.status ?? null,
        progressPercent: Number(finalJob.progress_percent ?? 100),
        progressMessage: String(finalJob.progress_message ?? ""),
        errorMessage: "",
        result: finalJob.result ?? null,
        isTransportError: false,
        jobId: parseInvoiceCollectionId(finalJob.id)
      });
      notifyPeriodRefresh(parsedInvoiceCollectionId);
    } else {
      markAsFailed(parsedInvoiceCollectionId);
      upsertCollectionQueueLog({
        success: false,
        invoiceCollectionId: parsedInvoiceCollectionId,
        status: finalJob.status ?? ECONOMIC_QUEUE_STATUS.FAILED,
        progressPercent: Number(finalJob.progress_percent ?? 0),
        progressMessage: String(finalJob.progress_message ?? ""),
        errorMessage: String(finalJob.error_message ?? "Queue job failed."),
        result: finalJob.result ?? null,
        isTransportError: false,
        jobId: parseInvoiceCollectionId(finalJob.id)
      });
      notifyPeriodRefresh(parsedInvoiceCollectionId);
    }
  } catch (error) {
    markAsFailed(parsedInvoiceCollectionId);
    upsertCollectionQueueLog({
      success: false,
      invoiceCollectionId: parsedInvoiceCollectionId,
      status: ECONOMIC_QUEUE_STATUS.FAILED,
      progressPercent: 0,
      progressMessage: "",
      errorMessage: getEconomicApiErrorMessage(error, "Unable to process invoice collection."),
      result: null,
      isTransportError: true,
      jobId: getRetryJobIdForInvoiceCollection(parsedInvoiceCollectionId)
    });
    notifyPeriodRefresh(parsedInvoiceCollectionId);
  } finally {
    removeFromInProgress(parsedInvoiceCollectionId);
    processInvoiceCollectionQueue();
  }
};
const addInvoiceCollectionToQueue = (invoiceCollectionId, context = {}) => {
  const parsedInvoiceCollectionId = parseInvoiceCollectionId(invoiceCollectionId);
  if (!parsedInvoiceCollectionId) {
    return;
  }
  rememberInvoiceCollectionContext(parsedInvoiceCollectionId, context);
  const customerNumber = parseCustomerNumber(context.customerNumber ?? null);
  if (customerNumber) {
    markPeriodRefreshLoading([customerNumber], [parsedInvoiceCollectionId]);
  }
  if (invoiceCollectionQueueInProgress.value.includes(parsedInvoiceCollectionId) || invoiceCollectionQueue.value.includes(parsedInvoiceCollectionId)) {
    return;
  }
  removeFromFailed(parsedInvoiceCollectionId);
  removeFromSuccess(parsedInvoiceCollectionId);
  invoiceCollectionQueue.value.push(parsedInvoiceCollectionId);
  upsertCollectionQueueLog({
    success: null,
    invoiceCollectionId: parsedInvoiceCollectionId,
    status: ECONOMIC_QUEUE_STATUS.QUEUED,
    progressPercent: 0,
    progressMessage: "Queued",
    errorMessage: "",
    result: null,
    isTransportError: false,
    jobId: getRetryJobIdForInvoiceCollection(parsedInvoiceCollectionId)
  });
};
const addInvoiceCollectionsToQueue = (invoiceCollectionIds, context = {}) => {
  (Array.isArray(invoiceCollectionIds) ? invoiceCollectionIds : []).forEach((id) => {
    addInvoiceCollectionToQueue(id, context);
  });
};
const processInvoiceCollectionQueue = () => {
  while (invoiceCollectionQueueInProgress.value.length < invoiceCollectionMaxConnections && invoiceCollectionQueue.value.length > 0) {
    const nextInvoiceCollectionId = invoiceCollectionQueue.value.shift();
    if (nextInvoiceCollectionId !== void 0) {
      void processInvoiceCollection(nextInvoiceCollectionId);
    }
  }
};
const retryInvoiceCollection = (invoiceCollectionId) => {
  const parsedInvoiceCollectionId = parseInvoiceCollectionId(invoiceCollectionId);
  if (!parsedInvoiceCollectionId) {
    return;
  }
  if (invoiceCollectionQueueInProgress.value.includes(parsedInvoiceCollectionId)) {
    return;
  }
  const retryJobId = getRetryJobIdForInvoiceCollection(parsedInvoiceCollectionId);
  if (!retryJobId) {
    addInvoiceCollectionToQueue(parsedInvoiceCollectionId);
    processInvoiceCollectionQueue();
    return;
  }
  void processInvoiceCollection(parsedInvoiceCollectionId, {
    retryJobId
  });
};
const queueStats = computed(() => ({
  total: invoiceCollectionQueueSuccess.value.length + invoiceCollectionQueueFailed.value.length + invoiceCollectionQueueInProgress.value.length + invoiceCollectionQueue.value.length,
  success: invoiceCollectionQueueSuccess.value.length,
  failed: invoiceCollectionQueueFailed.value.length,
  inProgress: invoiceCollectionQueueInProgress.value.length,
  queued: invoiceCollectionQueue.value.length
}));
const clearQueue = () => {
  invoiceCollectionQueueInProgress.value = [];
  invoiceCollectionQueueFailed.value = [];
  invoiceCollectionQueueSuccess.value = [];
  invoiceCollectionQueue.value = [];
  collectionQueueLog.value = [];
  invoiceCollectionQueueJobs.value = {};
  invoiceCollectionQueueJobIds.value = {};
  invoiceCollectionCustomerNumbers.value = {};
  periodCustomerRefreshInProgress.value = [];
  periodInvoiceCollectionRefreshInProgress.value = [];
};
const dismissProgressBar = () => {
};
const getProgressOfQueueItems = (invoiceCollectionIds) => {
  const normalizedIds = (Array.isArray(invoiceCollectionIds) ? invoiceCollectionIds : []).map((id) => parseInvoiceCollectionId(id)).filter((id) => id !== null);
  const total = normalizedIds.length;
  const success = normalizedIds.filter((id) => invoiceCollectionQueueSuccess.value.includes(id)).length;
  const failed = normalizedIds.filter((id) => invoiceCollectionQueueFailed.value.includes(id)).length;
  const inProgress = normalizedIds.filter((id) => invoiceCollectionQueueInProgress.value.includes(id)).length;
  const queued = normalizedIds.filter((id) => invoiceCollectionQueue.value.includes(id)).length;
  const percentage = total > 0 ? (total - queued) / total * 100 : 0;
  return {
    total,
    success,
    failed,
    inProgress,
    queued,
    percentage
  };
};
const invoiceQueue = {
  addInvoiceCollectionToQueue,
  addInvoiceCollectionsToQueue,
  processInvoiceCollectionQueue,
  retryInvoiceCollection,
  clearQueue,
  queueStats,
  periodRefreshSignal,
  invoiceCollectionQueue,
  invoiceCollectionQueueInProgress,
  invoiceCollectionQueueFailed,
  invoiceCollectionQueueSuccess,
  invoiceCollectionQueueJobs,
  invoiceCollectionQueueJobIds,
  invoiceCollectionCustomerNumbers,
  periodCustomerRefreshInProgress,
  periodInvoiceCollectionRefreshInProgress,
  collectionQueueLog,
  dismissProgressBar,
  markPeriodRefreshLoading,
  finishPeriodRefresh,
  isPeriodCustomerRefreshLoading,
  isPeriodInvoiceCollectionRefreshLoading,
  getProgressOfQueueItems
};
const _sfc_main$1w = {
  name: "InvoicingBillingPeriodImportInvoiceQueue"
};

const InvoicingBillingPeriodImportInvoiceQueue = /* @__PURE__ */ _export_sfc(_sfc_main$1w, [["__file", "InvoicingBillingPeriodImportInvoiceQueue.vue"]]);

const _sfc_main$1v = {
  __name: 'WhiteBox',
  props: {
  hasBorder: {
    type: Boolean,
    default: false
  }
},
  setup(__props, { expose: __expose }) {
  __expose();

const slots = useSlots();

const isSlotEmpty = () => {
  return Object.keys(slots).length === 0;
};

const props = __props;

const __returned__ = { slots, isSlotEmpty, props, useSlots };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

function _sfc_render$W(_ctx, _cache, $props, $setup, $data, $options) {
  return (!$setup.isSlotEmpty())
    ? (openBlock(), createElementBlock("div", {
        key: 0,
        class: normalizeClass(["box has-sharp-edges", {'has-custom-border': $props.hasBorder}])
      }, [
        renderSlot(_ctx.$slots, "default", {}, undefined, true)
      ], 2 /* CLASS */))
    : createCommentVNode("v-if", true)
}
const WhiteBox = /*#__PURE__*/_export_sfc(_sfc_main$1v, [['render',_sfc_render$W],['__scopeId',"data-v-faf5fc97"],['__file',"WhiteBox.vue"]]);

const _sfc_main$1u = /* @__PURE__ */ defineComponent({
  __name: "ColorIndicator",
  props: {
    label: {
      type: Object,
      default: () => ({
        text: null,
        classes: [],
        max_length: null
      })
    },
    visibility: {
      type: Object,
      default: () => ({
        icon: true,
        dropdown: true
      })
    },
    is_narrow: {
      type: Boolean,
      default: false
    },
    color_class: {
      type: String,
      default: "has-text-grey"
    },
    is_loading: {
      type: Boolean,
      default: false
    },
    icon_class: {
      type: String,
      default: "fas fa-circle"
    },
    error_icon_class: {
      type: String,
      default: "fas fa-exclamation-triangle"
    },
    error_class: {
      type: String,
      default: "has-text-danger"
    },
    error: {
      type: Boolean,
      default: false
    },
    error_message: {
      type: String,
      default: "An error occurred"
    },
    dropdown_direction: {
      type: String,
      default: "down"
      // Alternative values: "up", "left", "right"
    },
    loading_message: {
      type: String,
      default: "Loading..."
    },
    loading_icon_class: {
      type: String,
      default: "fas fa-circle-notch"
    },
    loading_timeout_ms: {
      type: Number,
      default: 0
      // 5 seconds
    },
    dropdown_content: {
      type: Object,
      default: () => ({
        title: null,
        content: [
          /**
          { text: "Item #1", action: () => {}, icon: "fas fa-circle-notch", class: "has-text-info" },
          { text: "Item #2", action: () => {}, icon: "fas fa-circle-notch", class: "has-text-info" },
          { text: "Item #3", action: () => {}, icon: "fas fa-circle-notch", class: "has-text-info" }
           */
        ],
        buttons_title: null,
        buttons: [
          /**
          { text: "Example button #1", action: () => {}, icon: "fas fa-circle-notch", class: ["has-text-info", "is-small"], button_text: "Button #1", disabled: false },
          { text: "Example button #2", action: () => {}, icon: "fas fa-circle-notch", class: "has-text-info" },
          { text: "Example button #3", action: () => {}, icon: "fas fa-circle-notch", class: "has-text-info" }
           */
        ]
      })
    },
    is_button_hover_effect: {
      type: Boolean,
      default: false
      // If true, the button will have a hover effect
    }
  },
  emits: ["onClick", "onHover", "onLeave", "onScroll", "onCopyToClipboard", "onLoadingTimeout"],
  setup(__props, { expose: __expose, emit: __emit }) {
    __expose();
    const props = __props;
    const emits = __emit;
    const is_currently_hovered = ref(false);
    const onClick = () => {
      emits("onClick");
    };
    const onHover = () => {
      is_currently_hovered.value = true;
      emits("onHover");
    };
    const onLeave = () => {
      is_currently_hovered.value = false;
      emits("onLeave");
    };
    const onScroll = () => {
      emits("onScroll");
    };
    const onLoadingTimeout = () => {
      if (props.is_loading) {
        console.warn("Loading timeout reached, but the element is still loading.");
        emits("onLoadingTimeout");
      }
    };
    const copyToClipboard = (text) => {
      navigator.clipboard.writeText(text).then(() => {
        emits("onCopyToClipboard", text);
      }).catch((err) => {
        console.error("Failed to copy: ", err);
      });
    };
    watch(() => props.is_loading, (newValue) => {
      if (newValue) {
        window.addEventListener("scroll", onScroll);
      } else {
        window.removeEventListener("scroll", onScroll);
      }
    });
    watch(() => props.loading_timeout_ms, (newValue) => {
      if (newValue > 0) {
        setTimeout(() => {
          onLoadingTimeout();
        }, newValue);
      }
    });
    watch(() => props.is_loading, (newValue) => {
      if (newValue) {
        if (props.loading_timeout_ms > 0) {
          setTimeout(() => {
            onLoadingTimeout();
          }, props.loading_timeout_ms);
        }
      }
    });
    onMounted(() => {
      if (props.is_loading && props.loading_timeout_ms > 0) {
        setTimeout(() => {
          onLoadingTimeout();
        }, props.loading_timeout_ms);
      }
    });
    const label_shortened = computed(() => {
      if (props.label && props.label.text && props.label.max_length) {
        return props.label.text.length > props.label.max_length ? props.label.text.substring(0, props.label.max_length) + "..." : props.label.text;
      }
      return props.label.text;
    });
    const __returned__ = { props, emits, is_currently_hovered, onClick, onHover, onLeave, onScroll, onLoadingTimeout, copyToClipboard, label_shortened };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$M = { class: "icon-text is-flex-wrap-nowrap" };
const _hoisted_2$C = { class: "icon" };
const _hoisted_3$y = {
  key: 0,
  class: "fas fa-circle-notch fa-spin"
};
const _hoisted_4$y = { class: "dropdown-menu" };
const _hoisted_5$x = {
  key: 0,
  class: "dropdown-content"
};
const _hoisted_6$w = {
  key: 0,
  class: "dropdown-item has-text-danger"
};
const _hoisted_7$u = { class: "is-pulled-right" };
const _hoisted_8$u = { class: "has-text-left" };
const _hoisted_9$s = { class: "dropdown-item has-text-info" };
const _hoisted_10$r = {
  key: 0,
  class: "dropdown-divider"
};
const _hoisted_11$n = {
  key: 0,
  class: "dropdown-divider"
};
const _hoisted_12$m = { class: "dropdown-item" };
const _hoisted_13$k = { class: "column is-auto-fill" };
const _hoisted_14$i = { class: "is-pulled-left" };
const _hoisted_15$h = {
  key: 0,
  class: "column is-auto-fill"
};
const _hoisted_16$h = { class: "is-pulled-right" };
const _hoisted_17$f = ["onClick", "disabled"];
const _hoisted_18$f = {
  key: 0,
  class: "icon"
};
const _hoisted_19$d = {
  key: 0,
  class: "dropdown-item has-text-info"
};
const _hoisted_20$c = { class: "is-pulled-right" };
const _hoisted_21$c = ["onClick", "disabled"];
const _hoisted_22$c = { class: "icon" };
const _hoisted_23$c = { class: "has-text-left" };
const _hoisted_24$c = {
  key: 2,
  class: "dropdown-item has-text-info"
};
function _sfc_render$V(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock(
    "div",
    {
      class: normalizeClass(["color-indicator", { "is-button-hover-effect": $setup.props.is_button_hover_effect }]),
      onClick: $setup.onClick,
      onMouseover: $setup.onHover,
      onMouseleave: $setup.onLeave
    },
    [
      createBaseVNode("span", _hoisted_1$M, [
        withDirectives(createBaseVNode(
          "span",
          _hoisted_2$C,
          [
            createCommentVNode(" Loading "),
            $props.is_loading ? (openBlock(), createElementBlock("i", _hoisted_3$y)) : $props.error ? (openBlock(), createElementBlock(
              Fragment,
              { key: 1 },
              [
                createCommentVNode(" Error state "),
                createBaseVNode(
                  "i",
                  {
                    class: normalizeClass([$props.error_icon_class, $props.error_class])
                  },
                  null,
                  2
                  /* CLASS */
                )
              ],
              64
              /* STABLE_FRAGMENT */
            )) : !$props.is_loading && !$setup.is_currently_hovered ? (openBlock(), createElementBlock(
              Fragment,
              { key: 2 },
              [
                createCommentVNode(" Not loading and not hovered "),
                createBaseVNode(
                  "i",
                  {
                    class: normalizeClass([$props.icon_class, $props.color_class])
                  },
                  null,
                  2
                  /* CLASS */
                )
              ],
              64
              /* STABLE_FRAGMENT */
            )) : !$props.is_loading && $setup.is_currently_hovered ? (openBlock(), createElementBlock(
              Fragment,
              { key: 3 },
              [
                createCommentVNode(" Not loading and hovered "),
                createBaseVNode(
                  "i",
                  {
                    class: normalizeClass([$props.icon_class, $props.color_class])
                  },
                  null,
                  2
                  /* CLASS */
                )
              ],
              64
              /* STABLE_FRAGMENT */
            )) : $props.is_loading && $setup.is_currently_hovered ? (openBlock(), createElementBlock(
              Fragment,
              { key: 4 },
              [
                createCommentVNode(" Loading and hovered "),
                _cache[1] || (_cache[1] = createBaseVNode(
                  "i",
                  { class: "fas fa-circle-notch fa-spin" },
                  null,
                  -1
                  /* CACHED */
                ))
              ],
              64
              /* STABLE_FRAGMENT */
            )) : !$props.is_loading && $setup.is_currently_hovered ? (openBlock(), createElementBlock(
              Fragment,
              { key: 5 },
              [
                createCommentVNode(" Not loading and hovered "),
                createBaseVNode(
                  "i",
                  {
                    class: normalizeClass([$props.icon_class, $props.color_class])
                  },
                  null,
                  2
                  /* CLASS */
                )
              ],
              64
              /* STABLE_FRAGMENT */
            )) : !$props.is_loading && !$setup.is_currently_hovered ? (openBlock(), createElementBlock(
              Fragment,
              { key: 6 },
              [
                createCommentVNode(" Not loading and not hovered "),
                createBaseVNode(
                  "i",
                  {
                    class: normalizeClass([$props.icon_class, $props.color_class])
                  },
                  null,
                  2
                  /* CLASS */
                )
              ],
              64
              /* STABLE_FRAGMENT */
            )) : createCommentVNode("v-if", true)
          ],
          512
          /* NEED_PATCH */
        ), [
          [vShow, $props.visibility.icon]
        ]),
        createCommentVNode(" Label "),
        $props.label && $props.label.text ? (openBlock(), createElementBlock(
          "span",
          {
            key: 0,
            class: normalizeClass([...$props.label.classes])
          },
          toDisplayString($setup.label_shortened),
          3
          /* TEXT, CLASS */
        )) : createCommentVNode("v-if", true)
      ]),
      createCommentVNode(" Dropdown menu "),
      $setup.props.visibility.dropdown ? (openBlock(), createElementBlock(
        "div",
        {
          key: 0,
          class: normalizeClass(["dropdown", { "is-active": $setup.is_currently_hovered, "is-up": $props.dropdown_direction === "up", "is-left": $props.dropdown_direction === "left", "is-right": $props.dropdown_direction === "right", "is-down": $props.dropdown_direction === "down" }])
        },
        [
          createBaseVNode("div", _hoisted_4$y, [
            $setup.is_currently_hovered ? (openBlock(), createElementBlock("div", _hoisted_5$x, [
              createCommentVNode(" Error message, with copy button "),
              $props.error ? (openBlock(), createElementBlock("div", _hoisted_6$w, [
                createBaseVNode("span", null, [
                  createBaseVNode("span", _hoisted_7$u, [
                    createBaseVNode("button", {
                      class: "button is-small is-light",
                      onClick: _cache[0] || (_cache[0] = () => {
                        $setup.copyToClipboard($props.error_message);
                      })
                    }, [..._cache[2] || (_cache[2] = [
                      createBaseVNode(
                        "i",
                        { class: "fas fa-copy" },
                        null,
                        -1
                        /* CACHED */
                      )
                    ])])
                  ]),
                  createBaseVNode("span", _hoisted_8$u, [
                    _cache[3] || (_cache[3] = createBaseVNode(
                      "strong",
                      null,
                      "Error:",
                      -1
                      /* CACHED */
                    )),
                    _cache[4] || (_cache[4] = createBaseVNode(
                      "br",
                      null,
                      null,
                      -1
                      /* CACHED */
                    )),
                    createTextVNode(
                      " " + toDisplayString($props.error_message),
                      1
                      /* TEXT */
                    )
                  ])
                ])
              ])) : $props.is_loading ? (openBlock(), createElementBlock(
                Fragment,
                { key: 1 },
                [
                  createCommentVNode(" Loading message "),
                  _cache[5] || (_cache[5] = createBaseVNode(
                    "div",
                    { class: "dropdown-item has-text-info" },
                    [
                      createBaseVNode("strong", null, "Loading...")
                    ],
                    -1
                    /* CACHED */
                  ))
                ],
                64
                /* STABLE_FRAGMENT */
              )) : (openBlock(), createElementBlock(
                Fragment,
                { key: 2 },
                [
                  createCommentVNode(" Normal state "),
                  createCommentVNode(" Dropdown content "),
                  $props.dropdown_content && $props.dropdown_content.content ? (openBlock(), createElementBlock(
                    Fragment,
                    { key: 0 },
                    [
                      createCommentVNode(" Dropdown label "),
                      $props.dropdown_content.title ? (openBlock(), createElementBlock(
                        Fragment,
                        { key: 0 },
                        [
                          createBaseVNode("div", _hoisted_9$s, [
                            createBaseVNode(
                              "strong",
                              null,
                              toDisplayString($props.dropdown_content.title),
                              1
                              /* TEXT */
                            )
                          ]),
                          createCommentVNode(" Divider "),
                          !$setup.props.is_narrow ? (openBlock(), createElementBlock("hr", _hoisted_10$r)) : createCommentVNode("v-if", true)
                        ],
                        64
                        /* STABLE_FRAGMENT */
                      )) : createCommentVNode("v-if", true),
                      (openBlock(true), createElementBlock(
                        Fragment,
                        null,
                        renderList($props.dropdown_content.content, (item, index) => {
                          return openBlock(), createElementBlock(
                            Fragment,
                            { key: index },
                            [
                              createCommentVNode(" Add divider if not the first item "),
                              index > 0 && !$setup.props.is_narrow ? (openBlock(), createElementBlock("hr", _hoisted_11$n)) : createCommentVNode("v-if", true),
                              createCommentVNode(" Dropdown item "),
                              createBaseVNode("div", _hoisted_12$m, [
                                createBaseVNode(
                                  "div",
                                  {
                                    class: normalizeClass(["columns is-mobile", { "is-vcentered": item.v_centered }])
                                  },
                                  [
                                    createCommentVNode(" Optional text "),
                                    createBaseVNode("div", _hoisted_13$k, [
                                      createBaseVNode(
                                        "span",
                                        _hoisted_14$i,
                                        toDisplayString(item.text),
                                        1
                                        /* TEXT */
                                      )
                                    ]),
                                    createCommentVNode(" Optional button "),
                                    item.button ? (openBlock(), createElementBlock("div", _hoisted_15$h, [
                                      createBaseVNode("span", _hoisted_16$h, [
                                        createBaseVNode("button", {
                                          class: normalizeClass(["button is-small is-light", item.button_classes]),
                                          onClick: () => {
                                            item.action();
                                          },
                                          disabled: item.disabled
                                        }, [
                                          createCommentVNode(" Optional button icon "),
                                          item.icon ? (openBlock(), createElementBlock("span", _hoisted_18$f, [
                                            createBaseVNode(
                                              "i",
                                              {
                                                class: normalizeClass([item.icon, item.classes ? item.classes : []])
                                              },
                                              null,
                                              2
                                              /* CLASS */
                                            )
                                          ])) : createCommentVNode("v-if", true),
                                          createCommentVNode(" Optional button text, breaks lines if too long "),
                                          item.button_text ? (openBlock(), createElementBlock(
                                            "span",
                                            {
                                              key: 1,
                                              class: normalizeClass({ "ml-2": item.icon })
                                            },
                                            toDisplayString(item.button_text),
                                            3
                                            /* TEXT, CLASS */
                                          )) : createCommentVNode("v-if", true)
                                        ], 10, _hoisted_17$f)
                                      ])
                                    ])) : createCommentVNode("v-if", true)
                                  ],
                                  2
                                  /* CLASS */
                                )
                              ])
                            ],
                            64
                            /* STABLE_FRAGMENT */
                          );
                        }),
                        128
                        /* KEYED_FRAGMENT */
                      ))
                    ],
                    64
                    /* STABLE_FRAGMENT */
                  )) : createCommentVNode("v-if", true),
                  createCommentVNode(" Dropdown buttons "),
                  $props.dropdown_content && $props.dropdown_content.buttons ? (openBlock(), createElementBlock(
                    Fragment,
                    { key: 1 },
                    [
                      createCommentVNode(" Dropdown label "),
                      $props.dropdown_content.buttons_title ? (openBlock(), createElementBlock("div", _hoisted_19$d, [
                        createBaseVNode(
                          "strong",
                          null,
                          toDisplayString($props.dropdown_content.buttons_title),
                          1
                          /* TEXT */
                        ),
                        createCommentVNode(" Divider "),
                        _cache[6] || (_cache[6] = createBaseVNode(
                          "hr",
                          { class: "dropdown-divider" },
                          null,
                          -1
                          /* CACHED */
                        ))
                      ])) : createCommentVNode("v-if", true),
                      (openBlock(true), createElementBlock(
                        Fragment,
                        null,
                        renderList($props.dropdown_content.buttons, (button, index) => {
                          return openBlock(), createElementBlock("div", {
                            key: index,
                            class: "dropdown-item"
                          }, [
                            createBaseVNode("span", _hoisted_20$c, [
                              createBaseVNode("button", {
                                class: normalizeClass(["button is-small is-light", button.button_classes]),
                                onClick: () => {
                                  button.action();
                                },
                                disabled: button.disabled
                              }, [
                                createBaseVNode("span", _hoisted_22$c, [
                                  createBaseVNode(
                                    "i",
                                    {
                                      class: normalizeClass([button.icon, button.classes ? button.classes : []])
                                    },
                                    null,
                                    2
                                    /* CLASS */
                                  )
                                ]),
                                createCommentVNode(" Optional button text "),
                                button.button_text ? (openBlock(), createElementBlock(
                                  Fragment,
                                  { key: 0 },
                                  [
                                    button.icon ? (openBlock(), createElementBlock(
                                      "span",
                                      {
                                        key: 0,
                                        class: normalizeClass({ "ml-2": button.icon })
                                      },
                                      toDisplayString(button.button_text),
                                      3
                                      /* TEXT, CLASS */
                                    )) : createCommentVNode("v-if", true)
                                  ],
                                  64
                                  /* STABLE_FRAGMENT */
                                )) : createCommentVNode("v-if", true)
                              ], 10, _hoisted_21$c)
                            ]),
                            createBaseVNode(
                              "span",
                              _hoisted_23$c,
                              toDisplayString(button.text),
                              1
                              /* TEXT */
                            )
                          ]);
                        }),
                        128
                        /* KEYED_FRAGMENT */
                      ))
                    ],
                    64
                    /* STABLE_FRAGMENT */
                  )) : createCommentVNode("v-if", true),
                  createCommentVNode(' Slot "content" for additional content '),
                  renderSlot(_ctx.$slots, "content", {}, void 0, true),
                  createCommentVNode(" If there's neither content nor buttons, show a message "),
                  (!$props.dropdown_content || !$props.dropdown_content.content || $props.dropdown_content.content.length === 0) && (!$props.dropdown_content.buttons || $props.dropdown_content.buttons.length === 0) ? (openBlock(), createElementBlock("div", _hoisted_24$c, [..._cache[7] || (_cache[7] = [
                    createBaseVNode(
                      "strong",
                      null,
                      "No content available",
                      -1
                      /* CACHED */
                    )
                  ])])) : createCommentVNode("v-if", true)
                ],
                64
                /* STABLE_FRAGMENT */
              ))
            ])) : createCommentVNode("v-if", true)
          ])
        ],
        2
        /* CLASS */
      )) : createCommentVNode("v-if", true)
    ],
    34
    /* CLASS, NEED_HYDRATION */
  );
}
const ColorIndicator = /* @__PURE__ */ _export_sfc(_sfc_main$1u, [["render", _sfc_render$V], ["__scopeId", "data-v-e521f487"], ["__file", "ColorIndicator.vue"]]);

const createNoopToastMethod = () => null;

const fallbackToast = {
  open: createNoopToastMethod,
  success: createNoopToastMethod,
  error: createNoopToastMethod,
  info: createNoopToastMethod,
  warning: createNoopToastMethod,
  default: createNoopToastMethod,
  clear() {},
};

function useAppToast() {
  const instance = getCurrentInstance();
  return instance?.appContext?.config?.globalProperties?.$toast ?? fallbackToast;
}

const _sfc_main$1t = /* @__PURE__ */ defineComponent({
  __name: "InvoicingBillingPeriodInvoiceProgressBar",
  props: {
    initialProgress: {
      type: Number,
      default: 0
    },
    maxProgress: {
      type: Number,
      default: 0
    },
    message: {
      type: String,
      default: ""
    },
    progress: {
      type: Number,
      default: 0
    },
    failed: {
      type: Number,
      default: 0
    },
    succeeded: {
      type: Number,
      default: 0
    },
    queued: {
      type: Number,
      default: 0
    }
  },
  emits: ["progressUpdate", "success", "fail", "dismissed"],
  setup(__props, { expose: __expose, emit: __emit }) {
    const { t } = useI18n();
    const uniqueElementId = Math.random().toString(36).substring(2, 15);
    const message = ref();
    const props = __props;
    const emits = __emit;
    const generateMessage = computed(() => {
      return message.value || t("invoicing.progress.sending_invoices");
    });
    const fail = (msg) => {
      if (props.progress > 0 && props.progress < 100) {
        message.value = msg || t("invoicing.progress.failed_to_send");
      }
    };
    const success = (msg) => {
      if (props.progress >= 0 && props.progress < 100) {
      }
      if (msg) {
        message.value = msg;
      } else {
        message.value = t("common.success");
      }
    };
    const progressBarStyle = computed(() => {
      return {
        width: `200px`
      };
    });
    const methods = {
      fail,
      success
    };
    __expose({
      methods
    });
    const progressPercentage = computed(() => {
      return props.progress >= 0 && props.progress <= props.maxProgress ? `${Math.round(props.progress / props.maxProgress * 100)}%` : "0%";
    });
    const html = ref(`
<div id="progress-bar-` + uniqueElementId + `" style="width: ${progressBarStyle.value.width}"
    <div class="container">
        <h4 class="label is-6 has-text-white">${t("invoicing.progress.sending_invoices")}</h4>
        <div class="columns">
            <div class="column is-8">
                <progress class="progress is-white" max="100"></progress>
            </div>
        <div class="column is-4 has-text-right">
            <span class="has-text-white">` + progressPercentage.value + `</span>
        </div
    </div>
</div>
`);
    const toastMessage = ref("Progress updated: " + progressPercentage.value);
    const toastDuration = ref(0);
    let instance = null;
    const $toast = useAppToast();
    const createToast = () => {
      if (!(props.queued > 0 || props.succeeded > 0 || props.failed > 0)) {
        return;
      }
      return instance = $toast.info(
        generateProgressBarHtml(),
        {
          position: "bottom-right",
          duration: toastDuration.value,
          dismissible: true,
          pauseOnHover: false,
          onDismiss: () => {
            emits("dismissed");
            instance = null;
          }
        }
      );
    };
    const getElementById = () => {
      return document.getElementById(`progress-bar-${uniqueElementId}`);
    };
    const generateActionAndCustomerLevelTextHtml = () => {
      return `<div class="level is-mobile">
            <div class="level-item has-text-white is-size-6 level-left">
              <span class="has-text-white">` + generateMessage.value + `</span>
            </div>
            <div class="level-item has-text-white is-size-6 level-right">
                <!-- Add any additional text or information here -->
            </div>
          </div>`;
    };
    const getTotalProcessedCount = computed(() => {
      return props.failed + props.succeeded;
    });
    const getTotalProcessesCount = computed(() => {
      return getTotalProcessedCount.value + props.queued;
    });
    const generateProgressBarHtml = () => {
      return `<div id="progress-bar-${uniqueElementId}" style="width: ${progressBarStyle.value.width}">
            <div class="container">
              ` + generateActionAndCustomerLevelTextHtml() + `
              <span class="has-text-white">${t("invoicing.progress.failed")}: ` + props.failed + `</span>
              <span class="has-text-white">${t("invoicing.progress.succeeded")}: ` + props.succeeded + `</span>
              <span class="has-text-white">${t("invoicing.progress.queued")}: ` + props.queued + `</span>
              <span class="has-text-white">${t("invoicing.progress.progress")}: ` + props.progress + ` / ` + props.maxProgress + `</span>
              <nav class="level is-mobile">
                  <div class="level-item" style="width: 80%;">
                      <progress class="progress ` + (props.progress > 0 ? "is-link" : props.failed > 0 ? "is-danger" : "is-success") + `" max="` + getTotalProcessesCount.value + `" value="` + getTotalProcessedCount.value + `"></progress>
                  </div>
                  <div class="level-item has-text-right">
                    <span class="has-text-white">` + (getTotalProcessedCount.value > 0 ? Math.round(getTotalProcessedCount.value / getTotalProcessesCount.value * 100) + "%" : "0%") + `</span>
                  </div>
              </nav>
            </div>
          </div>`;
    };
    const updateProgressBarStyle = () => {
      let element = getElementById();
      if (element) {
      }
    };
    const setToastHtml = () => {
      let element = getElementById();
      if (element) {
        element.innerHTML = generateProgressBarHtml();
        updateProgressBarStyle();
      } else {
        console.error("Element not found: progress-bar-" + uniqueElementId);
      }
    };
    const updateToast = () => {
      if (instance !== null) {
        setToastHtml();
      } else {
        createToast();
        setToastHtml();
      }
    };
    watch(() => getTotalProcessedCount.value, () => {
      updateToast();
    });
    onMounted(() => {
      createToast();
    });
    const __returned__ = { t, uniqueElementId, message, props, emits, generateMessage, fail, success, progressBarStyle, methods, progressPercentage, html, toastMessage, toastDuration, get instance() {
      return instance;
    }, set instance(v) {
      instance = v;
    }, $toast, createToast, getElementById, generateActionAndCustomerLevelTextHtml, getTotalProcessedCount, getTotalProcessesCount, generateProgressBarHtml, updateProgressBarStyle, setToastHtml, updateToast };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

function _sfc_render$U(_ctx, _cache, $props, $setup, $data, $options) {
  return null;
}
const InvoicingBillingPeriodInvoiceProgressBar = /* @__PURE__ */ _export_sfc(_sfc_main$1t, [["render", _sfc_render$U], ["__file", "InvoicingBillingPeriodInvoiceProgressBar.vue"]]);

const _sfc_main$1s = /* @__PURE__ */ defineComponent({
  __name: "InvoicingBillingPeriodViewHome",
  setup(__props, { expose: __expose }) {
    __expose();
    const __returned__ = { InvoicingBillingPeriodInvoiceProgressBar };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

function _sfc_render$T(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createBlock($setup["InvoicingBillingPeriodInvoiceProgressBar"]);
}
const InvoicingBillingPeriodViewHome = /* @__PURE__ */ _export_sfc(_sfc_main$1s, [["render", _sfc_render$T], ["__file", "InvoicingBillingPeriodViewHome.vue"]]);

const PERIOD_CACHE_TTL_MS = 10 * 60 * 1000;
const PERIOD_LIMIT_OPTIONS = [10, 25, 50, 100, 200, 500, "all"];

const CACHE_PREFIX$1 = "invoicing-period-page:v2:";
const SELF_WASH_COUNTS_CACHE_PREFIX = "invoicing-period-self-wash-counts:v2:";
const DEFAULT_LIMIT$1 = 100;
const ALL_LIMIT = "all";

const defaultMeta = () => ({
  page: 1,
  per_page: DEFAULT_LIMIT$1,
  total: 0,
  search: "",
  filters: {
    includeRequiresAction: true,
    includeBooked: true,
  },
  order: null,
});

const periodPaging = reactive({
  page: 1,
  limit: DEFAULT_LIMIT$1,
  search: "",
  flagTab: "all",
  includeRequiresAction: true,
  includeBooked: true,
  meta: defaultMeta(),
  typeCounts: {},
  isRefreshing: false,
  isFromCache: false,
  isDateLoading: false,
  cacheUpdatedAt: null,
  reloadSequence: 0,
});

const periodPageCount = computed(() => {
  const total = Number(periodPaging.meta?.total || 0);
  const perPageValue = periodPaging.meta?.per_page ?? periodPaging.limit ?? DEFAULT_LIMIT$1;
  if (perPageValue === ALL_LIMIT) {
    return 1;
  }

  const perPage = Number(perPageValue);
  return Math.max(1, Math.ceil(total / Math.max(1, perPage)));
});

const normalizeLimit = (value) => {
  if (
    String(value || "")
      .trim()
      .toLowerCase() === ALL_LIMIT
  ) {
    return ALL_LIMIT;
  }

  const parsed = Number.parseInt(String(value), 10);
  if (!Number.isInteger(parsed) || parsed < 1) {
    return DEFAULT_LIMIT$1;
  }

  return Math.min(500, parsed);
};

const normalizePage = (value) => {
  const parsed = Number.parseInt(String(value), 10);
  return Number.isInteger(parsed) && parsed > 0 ? parsed : 1;
};

const safeSessionStorage$1 = () => {
  try {
    if (typeof window === "undefined" || !window.sessionStorage) {
      return null;
    }
    return window.sessionStorage;
  } catch {
    return null;
  }
};

const getStorageValue$1 = (key) => {
  try {
    if (typeof window === "undefined" || !window.localStorage) {
      return "";
    }
    return window.localStorage.getItem(key) || "";
  } catch {
    return "";
  }
};

const hashCacheScopePart$1 = (value) => {
  let hash = 5381;
  for (let index = 0; index < value.length; index += 1) {
    hash = ((hash << 5) + hash) ^ value.charCodeAt(index);
  }
  return (hash >>> 0).toString(36);
};

const getAuthenticatedCacheScope$1 = () => {
  const token = getStorageValue$1("token");
  if (!token) {
    return "";
  }

  return [
    hashCacheScopePart$1(token),
    getStorageValue$1("is_subuser") === "true" ? "subuser" : "user",
    getStorageValue$1("selected_customer_number"),
  ]
    .map((part) => encodeURIComponent(String(part ?? "")))
    .join("|");
};

const getScopedCacheKey$1 = (cacheKey) => {
  const scope = getAuthenticatedCacheScope$1();
  return scope ? `${scope}:${cacheKey}` : "";
};

const memoryCache$1 = new Map();
const selfWashCountsMemoryCache = new Map();

const resetPeriodPagingState = ({ clearCache = true } = {}) => {
  periodPaging.page = 1;
  periodPaging.limit = DEFAULT_LIMIT$1;
  periodPaging.search = "";
  periodPaging.flagTab = "all";
  periodPaging.includeRequiresAction = true;
  periodPaging.includeBooked = true;
  periodPaging.meta = defaultMeta();
  periodPaging.typeCounts = {};
  periodPaging.isRefreshing = false;
  periodPaging.isFromCache = false;
  periodPaging.isDateLoading = false;
  periodPaging.cacheUpdatedAt = null;
  periodPaging.reloadSequence = 0;
  if (clearCache) {
    clearPeriodCache();
    clearSelfWashCountsCache();
  }
};

const setPeriodPagingMeta = (meta = {}, typeCounts = {}) => {
  periodPaging.meta = {
    ...defaultMeta(),
    ...(meta || {}),
    page: normalizePage(meta?.page),
    per_page: normalizeLimit(meta?.per_page ?? periodPaging.limit),
    total: Math.max(0, Number.parseInt(String(meta?.total ?? 0), 10) || 0),
    search: String(meta?.search ?? periodPaging.search ?? ""),
    filters: {
      includeRequiresAction: periodPaging.includeRequiresAction,
      includeBooked: periodPaging.includeBooked,
      ...(meta?.filters || {}),
    },
  };
  periodPaging.typeCounts = typeCounts && typeof typeCounts === "object" ? typeCounts : {};
};

const requestPeriodReload = () => {
  periodPaging.reloadSequence += 1;
};

const buildPeriodCacheKey = ({
  dateFrom,
  dateTo,
  periodView,
  page,
  limit,
  search,
  flagTab,
  includeRequiresAction,
  includeBooked,
}) =>
  [
    dateFrom,
    dateTo,
    periodView,
    normalizePage(page),
    normalizeLimit(limit),
    String(search || "").trim(),
    String(flagTab || "all").trim(),
    includeRequiresAction ? "1" : "0",
    includeBooked ? "1" : "0",
  ]
    .map((part) => encodeURIComponent(String(part ?? "")))
    .join("|");

const isFreshCacheEntry = (entry) => {
  const storedAt = Number(entry?.storedAt || 0);
  return storedAt > 0 && Date.now() - storedAt <= PERIOD_CACHE_TTL_MS;
};

const getCachedPeriodPage = (cacheKey) => {
  const scopedCacheKey = getScopedCacheKey$1(cacheKey);
  if (!scopedCacheKey) {
    return null;
  }

  const memoryEntry = memoryCache$1.get(scopedCacheKey);
  if (isFreshCacheEntry(memoryEntry)) {
    return memoryEntry;
  }

  if (memoryEntry) {
    memoryCache$1.delete(scopedCacheKey);
  }

  const storage = safeSessionStorage$1();
  if (!storage) {
    return null;
  }

  const storageKey = `${CACHE_PREFIX$1}${scopedCacheKey}`;
  try {
    const parsed = JSON.parse(storage.getItem(storageKey) || "null");
    if (!isFreshCacheEntry(parsed)) {
      storage.removeItem(storageKey);
      return null;
    }
    memoryCache$1.set(scopedCacheKey, parsed);
    return parsed;
  } catch {
    storage.removeItem(storageKey);
    return null;
  }
};

const setCachedPeriodPage = (cacheKey, periodResult, paginationMeta) => {
  const scopedCacheKey = getScopedCacheKey$1(cacheKey);
  if (!scopedCacheKey) {
    return;
  }

  const entry = {
    storedAt: Date.now(),
    data: periodResult,
    pagination: paginationMeta,
  };
  memoryCache$1.set(scopedCacheKey, entry);

  const storage = safeSessionStorage$1();
  if (!storage) {
    return;
  }

  try {
    storage.setItem(`${CACHE_PREFIX$1}${scopedCacheKey}`, JSON.stringify(entry));
  } catch {
    // Best-effort cache. Quota errors should not block the period view.
  }
};

const clearPeriodCache = () => {
  memoryCache$1.clear();
  const storage = safeSessionStorage$1();
  if (!storage) {
    return;
  }

  try {
    Object.keys(storage)
      .filter((key) => key.startsWith(CACHE_PREFIX$1))
      .forEach((key) => storage.removeItem(key));
  } catch {
    // Best-effort cache cleanup.
  }
};

const buildSelfWashCountsCacheKey = ({ dateFrom, dateTo, filters }) =>
  [dateFrom, dateTo, filters].map((part) => encodeURIComponent(String(part ?? ""))).join("|");

const getCachedSelfWashCounts = (cacheKey) => {
  const scopedCacheKey = getScopedCacheKey$1(cacheKey);
  if (!scopedCacheKey) {
    return null;
  }

  const memoryEntry = selfWashCountsMemoryCache.get(scopedCacheKey);
  if (isFreshCacheEntry(memoryEntry)) {
    return memoryEntry.data;
  }

  if (memoryEntry) {
    selfWashCountsMemoryCache.delete(scopedCacheKey);
  }

  const storage = safeSessionStorage$1();
  if (!storage) {
    return null;
  }

  const storageKey = `${SELF_WASH_COUNTS_CACHE_PREFIX}${scopedCacheKey}`;
  try {
    const parsed = JSON.parse(storage.getItem(storageKey) || "null");
    if (!isFreshCacheEntry(parsed)) {
      storage.removeItem(storageKey);
      return null;
    }
    selfWashCountsMemoryCache.set(scopedCacheKey, parsed);
    return parsed.data;
  } catch {
    storage.removeItem(storageKey);
    return null;
  }
};

const setCachedSelfWashCounts = (cacheKey, counts) => {
  const scopedCacheKey = getScopedCacheKey$1(cacheKey);
  if (!scopedCacheKey) {
    return;
  }

  const entry = {
    storedAt: Date.now(),
    data: counts,
  };
  selfWashCountsMemoryCache.set(scopedCacheKey, entry);

  const storage = safeSessionStorage$1();
  if (!storage) {
    return;
  }

  try {
    storage.setItem(`${SELF_WASH_COUNTS_CACHE_PREFIX}${scopedCacheKey}`, JSON.stringify(entry));
  } catch {
    // Best-effort cache. Quota errors should not block the period view.
  }
};

const clearSelfWashCountsCache = () => {
  selfWashCountsMemoryCache.clear();
  const storage = safeSessionStorage$1();
  if (!storage) {
    return;
  }

  try {
    Object.keys(storage)
      .filter((key) => key.startsWith(SELF_WASH_COUNTS_CACHE_PREFIX))
      .forEach((key) => storage.removeItem(key));
  } catch {
    // Best-effort cache cleanup.
  }
};

const normalizePeriodPage = normalizePage;
const normalizePeriodLimit = normalizeLimit;

/*!
 * @kurkle/color v0.3.4
 * https://github.com/kurkle/color#readme
 * (c) 2024 Jukka Kurkela
 * Released under the MIT License
 */
function round$1(v) {
  return v + 0.5 | 0;
}
const lim = (v, l, h) => Math.max(Math.min(v, h), l);
function p2b(v) {
  return lim(round$1(v * 2.55), 0, 255);
}
function b2p(v) {
  return lim(round$1(v / 2.55), 0, 100);
}
function n2b(v) {
  return lim(round$1(v * 255), 0, 255);
}
function b2n(v) {
  return lim(round$1(v / 2.55) / 100, 0, 1);
}
function n2p(v) {
  return lim(round$1(v * 100), 0, 100);
}

const map$1 = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15};
const hex = [...'0123456789ABCDEF'];
const h1 = b => hex[b & 0xF];
const h2 = b => hex[(b & 0xF0) >> 4] + hex[b & 0xF];
const eq = b => ((b & 0xF0) >> 4) === (b & 0xF);
const isShort = v => eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a);
function hexParse(str) {
  var len = str.length;
  var ret;
  if (str[0] === '#') {
    if (len === 4 || len === 5) {
      ret = {
        r: 255 & map$1[str[1]] * 17,
        g: 255 & map$1[str[2]] * 17,
        b: 255 & map$1[str[3]] * 17,
        a: len === 5 ? map$1[str[4]] * 17 : 255
      };
    } else if (len === 7 || len === 9) {
      ret = {
        r: map$1[str[1]] << 4 | map$1[str[2]],
        g: map$1[str[3]] << 4 | map$1[str[4]],
        b: map$1[str[5]] << 4 | map$1[str[6]],
        a: len === 9 ? (map$1[str[7]] << 4 | map$1[str[8]]) : 255
      };
    }
  }
  return ret;
}
const alpha = (a, f) => a < 255 ? f(a) : '';
function hexString(v) {
  var f = isShort(v) ? h1 : h2;
  return v
    ? '#' + f(v.r) + f(v.g) + f(v.b) + alpha(v.a, f)
    : undefined;
}

const HUE_RE = /^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;
function hsl2rgbn(h, s, l) {
  const a = s * Math.min(l, 1 - l);
  const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
  return [f(0), f(8), f(4)];
}
function hsv2rgbn(h, s, v) {
  const f = (n, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);
  return [f(5), f(3), f(1)];
}
function hwb2rgbn(h, w, b) {
  const rgb = hsl2rgbn(h, 1, 0.5);
  let i;
  if (w + b > 1) {
    i = 1 / (w + b);
    w *= i;
    b *= i;
  }
  for (i = 0; i < 3; i++) {
    rgb[i] *= 1 - w - b;
    rgb[i] += w;
  }
  return rgb;
}
function hueValue(r, g, b, d, max) {
  if (r === max) {
    return ((g - b) / d) + (g < b ? 6 : 0);
  }
  if (g === max) {
    return (b - r) / d + 2;
  }
  return (r - g) / d + 4;
}
function rgb2hsl(v) {
  const range = 255;
  const r = v.r / range;
  const g = v.g / range;
  const b = v.b / range;
  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  const l = (max + min) / 2;
  let h, s, d;
  if (max !== min) {
    d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    h = hueValue(r, g, b, d, max);
    h = h * 60 + 0.5;
  }
  return [h | 0, s || 0, l];
}
function calln(f, a, b, c) {
  return (
    Array.isArray(a)
      ? f(a[0], a[1], a[2])
      : f(a, b, c)
  ).map(n2b);
}
function hsl2rgb(h, s, l) {
  return calln(hsl2rgbn, h, s, l);
}
function hwb2rgb(h, w, b) {
  return calln(hwb2rgbn, h, w, b);
}
function hsv2rgb(h, s, v) {
  return calln(hsv2rgbn, h, s, v);
}
function hue(h) {
  return (h % 360 + 360) % 360;
}
function hueParse(str) {
  const m = HUE_RE.exec(str);
  let a = 255;
  let v;
  if (!m) {
    return;
  }
  if (m[5] !== v) {
    a = m[6] ? p2b(+m[5]) : n2b(+m[5]);
  }
  const h = hue(+m[2]);
  const p1 = +m[3] / 100;
  const p2 = +m[4] / 100;
  if (m[1] === 'hwb') {
    v = hwb2rgb(h, p1, p2);
  } else if (m[1] === 'hsv') {
    v = hsv2rgb(h, p1, p2);
  } else {
    v = hsl2rgb(h, p1, p2);
  }
  return {
    r: v[0],
    g: v[1],
    b: v[2],
    a: a
  };
}
function rotate(v, deg) {
  var h = rgb2hsl(v);
  h[0] = hue(h[0] + deg);
  h = hsl2rgb(h);
  v.r = h[0];
  v.g = h[1];
  v.b = h[2];
}
function hslString(v) {
  if (!v) {
    return;
  }
  const a = rgb2hsl(v);
  const h = a[0];
  const s = n2p(a[1]);
  const l = n2p(a[2]);
  return v.a < 255
    ? `hsla(${h}, ${s}%, ${l}%, ${b2n(v.a)})`
    : `hsl(${h}, ${s}%, ${l}%)`;
}

const map$2 = {
	x: 'dark',
	Z: 'light',
	Y: 're',
	X: 'blu',
	W: 'gr',
	V: 'medium',
	U: 'slate',
	A: 'ee',
	T: 'ol',
	S: 'or',
	B: 'ra',
	C: 'lateg',
	D: 'ights',
	R: 'in',
	Q: 'turquois',
	E: 'hi',
	P: 'ro',
	O: 'al',
	N: 'le',
	M: 'de',
	L: 'yello',
	F: 'en',
	K: 'ch',
	G: 'arks',
	H: 'ea',
	I: 'ightg',
	J: 'wh'
};
const names$1 = {
	OiceXe: 'f0f8ff',
	antiquewEte: 'faebd7',
	aqua: 'ffff',
	aquamarRe: '7fffd4',
	azuY: 'f0ffff',
	beige: 'f5f5dc',
	bisque: 'ffe4c4',
	black: '0',
	blanKedOmond: 'ffebcd',
	Xe: 'ff',
	XeviTet: '8a2be2',
	bPwn: 'a52a2a',
	burlywood: 'deb887',
	caMtXe: '5f9ea0',
	KartYuse: '7fff00',
	KocTate: 'd2691e',
	cSO: 'ff7f50',
	cSnflowerXe: '6495ed',
	cSnsilk: 'fff8dc',
	crimson: 'dc143c',
	cyan: 'ffff',
	xXe: '8b',
	xcyan: '8b8b',
	xgTMnPd: 'b8860b',
	xWay: 'a9a9a9',
	xgYF: '6400',
	xgYy: 'a9a9a9',
	xkhaki: 'bdb76b',
	xmagFta: '8b008b',
	xTivegYF: '556b2f',
	xSange: 'ff8c00',
	xScEd: '9932cc',
	xYd: '8b0000',
	xsOmon: 'e9967a',
	xsHgYF: '8fbc8f',
	xUXe: '483d8b',
	xUWay: '2f4f4f',
	xUgYy: '2f4f4f',
	xQe: 'ced1',
	xviTet: '9400d3',
	dAppRk: 'ff1493',
	dApskyXe: 'bfff',
	dimWay: '696969',
	dimgYy: '696969',
	dodgerXe: '1e90ff',
	fiYbrick: 'b22222',
	flSOwEte: 'fffaf0',
	foYstWAn: '228b22',
	fuKsia: 'ff00ff',
	gaRsbSo: 'dcdcdc',
	ghostwEte: 'f8f8ff',
	gTd: 'ffd700',
	gTMnPd: 'daa520',
	Way: '808080',
	gYF: '8000',
	gYFLw: 'adff2f',
	gYy: '808080',
	honeyMw: 'f0fff0',
	hotpRk: 'ff69b4',
	RdianYd: 'cd5c5c',
	Rdigo: '4b0082',
	ivSy: 'fffff0',
	khaki: 'f0e68c',
	lavFMr: 'e6e6fa',
	lavFMrXsh: 'fff0f5',
	lawngYF: '7cfc00',
	NmoncEffon: 'fffacd',
	ZXe: 'add8e6',
	ZcSO: 'f08080',
	Zcyan: 'e0ffff',
	ZgTMnPdLw: 'fafad2',
	ZWay: 'd3d3d3',
	ZgYF: '90ee90',
	ZgYy: 'd3d3d3',
	ZpRk: 'ffb6c1',
	ZsOmon: 'ffa07a',
	ZsHgYF: '20b2aa',
	ZskyXe: '87cefa',
	ZUWay: '778899',
	ZUgYy: '778899',
	ZstAlXe: 'b0c4de',
	ZLw: 'ffffe0',
	lime: 'ff00',
	limegYF: '32cd32',
	lRF: 'faf0e6',
	magFta: 'ff00ff',
	maPon: '800000',
	VaquamarRe: '66cdaa',
	VXe: 'cd',
	VScEd: 'ba55d3',
	VpurpN: '9370db',
	VsHgYF: '3cb371',
	VUXe: '7b68ee',
	VsprRggYF: 'fa9a',
	VQe: '48d1cc',
	VviTetYd: 'c71585',
	midnightXe: '191970',
	mRtcYam: 'f5fffa',
	mistyPse: 'ffe4e1',
	moccasR: 'ffe4b5',
	navajowEte: 'ffdead',
	navy: '80',
	Tdlace: 'fdf5e6',
	Tive: '808000',
	TivedBb: '6b8e23',
	Sange: 'ffa500',
	SangeYd: 'ff4500',
	ScEd: 'da70d6',
	pOegTMnPd: 'eee8aa',
	pOegYF: '98fb98',
	pOeQe: 'afeeee',
	pOeviTetYd: 'db7093',
	papayawEp: 'ffefd5',
	pHKpuff: 'ffdab9',
	peru: 'cd853f',
	pRk: 'ffc0cb',
	plum: 'dda0dd',
	powMrXe: 'b0e0e6',
	purpN: '800080',
	YbeccapurpN: '663399',
	Yd: 'ff0000',
	Psybrown: 'bc8f8f',
	PyOXe: '4169e1',
	saddNbPwn: '8b4513',
	sOmon: 'fa8072',
	sandybPwn: 'f4a460',
	sHgYF: '2e8b57',
	sHshell: 'fff5ee',
	siFna: 'a0522d',
	silver: 'c0c0c0',
	skyXe: '87ceeb',
	UXe: '6a5acd',
	UWay: '708090',
	UgYy: '708090',
	snow: 'fffafa',
	sprRggYF: 'ff7f',
	stAlXe: '4682b4',
	tan: 'd2b48c',
	teO: '8080',
	tEstN: 'd8bfd8',
	tomato: 'ff6347',
	Qe: '40e0d0',
	viTet: 'ee82ee',
	JHt: 'f5deb3',
	wEte: 'ffffff',
	wEtesmoke: 'f5f5f5',
	Lw: 'ffff00',
	LwgYF: '9acd32'
};
function unpack() {
  const unpacked = {};
  const keys = Object.keys(names$1);
  const tkeys = Object.keys(map$2);
  let i, j, k, ok, nk;
  for (i = 0; i < keys.length; i++) {
    ok = nk = keys[i];
    for (j = 0; j < tkeys.length; j++) {
      k = tkeys[j];
      nk = nk.replace(k, map$2[k]);
    }
    k = parseInt(names$1[ok], 16);
    unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF];
  }
  return unpacked;
}

let names;
function nameParse(str) {
  if (!names) {
    names = unpack();
    names.transparent = [0, 0, 0, 0];
  }
  const a = names[str.toLowerCase()];
  return a && {
    r: a[0],
    g: a[1],
    b: a[2],
    a: a.length === 4 ? a[3] : 255
  };
}

const RGB_RE = /^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;
function rgbParse(str) {
  const m = RGB_RE.exec(str);
  let a = 255;
  let r, g, b;
  if (!m) {
    return;
  }
  if (m[7] !== r) {
    const v = +m[7];
    a = m[8] ? p2b(v) : lim(v * 255, 0, 255);
  }
  r = +m[1];
  g = +m[3];
  b = +m[5];
  r = 255 & (m[2] ? p2b(r) : lim(r, 0, 255));
  g = 255 & (m[4] ? p2b(g) : lim(g, 0, 255));
  b = 255 & (m[6] ? p2b(b) : lim(b, 0, 255));
  return {
    r: r,
    g: g,
    b: b,
    a: a
  };
}
function rgbString(v) {
  return v && (
    v.a < 255
      ? `rgba(${v.r}, ${v.g}, ${v.b}, ${b2n(v.a)})`
      : `rgb(${v.r}, ${v.g}, ${v.b})`
  );
}

const to = v => v <= 0.0031308 ? v * 12.92 : Math.pow(v, 1.0 / 2.4) * 1.055 - 0.055;
const from = v => v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
function interpolate$1(rgb1, rgb2, t) {
  const r = from(b2n(rgb1.r));
  const g = from(b2n(rgb1.g));
  const b = from(b2n(rgb1.b));
  return {
    r: n2b(to(r + t * (from(b2n(rgb2.r)) - r))),
    g: n2b(to(g + t * (from(b2n(rgb2.g)) - g))),
    b: n2b(to(b + t * (from(b2n(rgb2.b)) - b))),
    a: rgb1.a + t * (rgb2.a - rgb1.a)
  };
}

function modHSL(v, i, ratio) {
  if (v) {
    let tmp = rgb2hsl(v);
    tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1));
    tmp = hsl2rgb(tmp);
    v.r = tmp[0];
    v.g = tmp[1];
    v.b = tmp[2];
  }
}
function clone$1(v, proto) {
  return v ? Object.assign(proto || {}, v) : v;
}
function fromObject(input) {
  var v = {r: 0, g: 0, b: 0, a: 255};
  if (Array.isArray(input)) {
    if (input.length >= 3) {
      v = {r: input[0], g: input[1], b: input[2], a: 255};
      if (input.length > 3) {
        v.a = n2b(input[3]);
      }
    }
  } else {
    v = clone$1(input, {r: 0, g: 0, b: 0, a: 1});
    v.a = n2b(v.a);
  }
  return v;
}
function functionParse(str) {
  if (str.charAt(0) === 'r') {
    return rgbParse(str);
  }
  return hueParse(str);
}
class Color {
  constructor(input) {
    if (input instanceof Color) {
      return input;
    }
    const type = typeof input;
    let v;
    if (type === 'object') {
      v = fromObject(input);
    } else if (type === 'string') {
      v = hexParse(input) || nameParse(input) || functionParse(input);
    }
    this._rgb = v;
    this._valid = !!v;
  }
  get valid() {
    return this._valid;
  }
  get rgb() {
    var v = clone$1(this._rgb);
    if (v) {
      v.a = b2n(v.a);
    }
    return v;
  }
  set rgb(obj) {
    this._rgb = fromObject(obj);
  }
  rgbString() {
    return this._valid ? rgbString(this._rgb) : undefined;
  }
  hexString() {
    return this._valid ? hexString(this._rgb) : undefined;
  }
  hslString() {
    return this._valid ? hslString(this._rgb) : undefined;
  }
  mix(color, weight) {
    if (color) {
      const c1 = this.rgb;
      const c2 = color.rgb;
      let w2;
      const p = weight === w2 ? 0.5 : weight;
      const w = 2 * p - 1;
      const a = c1.a - c2.a;
      const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
      w2 = 1 - w1;
      c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5;
      c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5;
      c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5;
      c1.a = p * c1.a + (1 - p) * c2.a;
      this.rgb = c1;
    }
    return this;
  }
  interpolate(color, t) {
    if (color) {
      this._rgb = interpolate$1(this._rgb, color._rgb, t);
    }
    return this;
  }
  clone() {
    return new Color(this.rgb);
  }
  alpha(a) {
    this._rgb.a = n2b(a);
    return this;
  }
  clearer(ratio) {
    const rgb = this._rgb;
    rgb.a *= 1 - ratio;
    return this;
  }
  greyscale() {
    const rgb = this._rgb;
    const val = round$1(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11);
    rgb.r = rgb.g = rgb.b = val;
    return this;
  }
  opaquer(ratio) {
    const rgb = this._rgb;
    rgb.a *= 1 + ratio;
    return this;
  }
  negate() {
    const v = this._rgb;
    v.r = 255 - v.r;
    v.g = 255 - v.g;
    v.b = 255 - v.b;
    return this;
  }
  lighten(ratio) {
    modHSL(this._rgb, 2, ratio);
    return this;
  }
  darken(ratio) {
    modHSL(this._rgb, 2, -ratio);
    return this;
  }
  saturate(ratio) {
    modHSL(this._rgb, 1, ratio);
    return this;
  }
  desaturate(ratio) {
    modHSL(this._rgb, 1, -ratio);
    return this;
  }
  rotate(deg) {
    rotate(this._rgb, deg);
    return this;
  }
}

function index_esm(input) {
  return new Color(input);
}

/*!
 * Chart.js v4.5.1
 * https://www.chartjs.org
 * (c) 2025 Chart.js Contributors
 * Released under the MIT License
 */

/**
 * @namespace Chart.helpers
 */ /**
 * An empty function that can be used, for example, for optional callback.
 */ function noop() {
/* noop */ }
/**
 * Returns a unique id, sequentially generated from a global variable.
 */ const uid = (()=>{
    let id = 0;
    return ()=>id++;
})();
/**
 * Returns true if `value` is neither null nor undefined, else returns false.
 * @param value - The value to test.
 * @since 2.7.0
 */ function isNullOrUndef(value) {
    return value === null || value === undefined;
}
/**
 * Returns true if `value` is an array (including typed arrays), else returns false.
 * @param value - The value to test.
 * @function
 */ function isArray(value) {
    if (Array.isArray && Array.isArray(value)) {
        return true;
    }
    const type = Object.prototype.toString.call(value);
    if (type.slice(0, 7) === '[object' && type.slice(-6) === 'Array]') {
        return true;
    }
    return false;
}
/**
 * Returns true if `value` is an object (excluding null), else returns false.
 * @param value - The value to test.
 * @since 2.7.0
 */ function isObject(value) {
    return value !== null && Object.prototype.toString.call(value) === '[object Object]';
}
/**
 * Returns true if `value` is a finite number, else returns false
 * @param value  - The value to test.
 */ function isNumberFinite(value) {
    return (typeof value === 'number' || value instanceof Number) && isFinite(+value);
}
/**
 * Returns `value` if finite, else returns `defaultValue`.
 * @param value - The value to return if defined.
 * @param defaultValue - The value to return if `value` is not finite.
 */ function finiteOrDefault(value, defaultValue) {
    return isNumberFinite(value) ? value : defaultValue;
}
/**
 * Returns `value` if defined, else returns `defaultValue`.
 * @param value - The value to return if defined.
 * @param defaultValue - The value to return if `value` is undefined.
 */ function valueOrDefault(value, defaultValue) {
    return typeof value === 'undefined' ? defaultValue : value;
}
const toPercentage = (value, dimension)=>typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 : +value / dimension;
const toDimension = (value, dimension)=>typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 * dimension : +value;
/**
 * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
 * value returned by `fn`. If `fn` is not a function, this method returns undefined.
 * @param fn - The function to call.
 * @param args - The arguments with which `fn` should be called.
 * @param [thisArg] - The value of `this` provided for the call to `fn`.
 */ function callback(fn, args, thisArg) {
    if (fn && typeof fn.call === 'function') {
        return fn.apply(thisArg, args);
    }
}
function each(loopable, fn, thisArg, reverse) {
    let i, len, keys;
    if (isArray(loopable)) {
        len = loopable.length;
        if (reverse) {
            for(i = len - 1; i >= 0; i--){
                fn.call(thisArg, loopable[i], i);
            }
        } else {
            for(i = 0; i < len; i++){
                fn.call(thisArg, loopable[i], i);
            }
        }
    } else if (isObject(loopable)) {
        keys = Object.keys(loopable);
        len = keys.length;
        for(i = 0; i < len; i++){
            fn.call(thisArg, loopable[keys[i]], keys[i]);
        }
    }
}
/**
 * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
 * @param a0 - The array to compare
 * @param a1 - The array to compare
 * @private
 */ function _elementsEqual(a0, a1) {
    let i, ilen, v0, v1;
    if (!a0 || !a1 || a0.length !== a1.length) {
        return false;
    }
    for(i = 0, ilen = a0.length; i < ilen; ++i){
        v0 = a0[i];
        v1 = a1[i];
        if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) {
            return false;
        }
    }
    return true;
}
/**
 * Returns a deep copy of `source` without keeping references on objects and arrays.
 * @param source - The value to clone.
 */ function clone(source) {
    if (isArray(source)) {
        return source.map(clone);
    }
    if (isObject(source)) {
        const target = Object.create(null);
        const keys = Object.keys(source);
        const klen = keys.length;
        let k = 0;
        for(; k < klen; ++k){
            target[keys[k]] = clone(source[keys[k]]);
        }
        return target;
    }
    return source;
}
function isValidKey(key) {
    return [
        '__proto__',
        'prototype',
        'constructor'
    ].indexOf(key) === -1;
}
/**
 * The default merger when Chart.helpers.merge is called without merger option.
 * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
 * @private
 */ function _merger(key, target, source, options) {
    if (!isValidKey(key)) {
        return;
    }
    const tval = target[key];
    const sval = source[key];
    if (isObject(tval) && isObject(sval)) {
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        merge(tval, sval, options);
    } else {
        target[key] = clone(sval);
    }
}
function merge(target, source, options) {
    const sources = isArray(source) ? source : [
        source
    ];
    const ilen = sources.length;
    if (!isObject(target)) {
        return target;
    }
    options = options || {};
    const merger = options.merger || _merger;
    let current;
    for(let i = 0; i < ilen; ++i){
        current = sources[i];
        if (!isObject(current)) {
            continue;
        }
        const keys = Object.keys(current);
        for(let k = 0, klen = keys.length; k < klen; ++k){
            merger(keys[k], target, current, options);
        }
    }
    return target;
}
function mergeIf(target, source) {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    return merge(target, source, {
        merger: _mergerIf
    });
}
/**
 * Merges source[key] in target[key] only if target[key] is undefined.
 * @private
 */ function _mergerIf(key, target, source) {
    if (!isValidKey(key)) {
        return;
    }
    const tval = target[key];
    const sval = source[key];
    if (isObject(tval) && isObject(sval)) {
        mergeIf(tval, sval);
    } else if (!Object.prototype.hasOwnProperty.call(target, key)) {
        target[key] = clone(sval);
    }
}
/**
 * @private
 */ function _deprecated(scope, value, previous, current) {
    if (value !== undefined) {
        console.warn(scope + ': "' + previous + '" is deprecated. Please use "' + current + '" instead');
    }
}
// resolveObjectKey resolver cache
const keyResolvers = {
    // Chart.helpers.core resolveObjectKey should resolve empty key to root object
    '': (v)=>v,
    // default resolvers
    x: (o)=>o.x,
    y: (o)=>o.y
};
/**
 * @private
 */ function _splitKey(key) {
    const parts = key.split('.');
    const keys = [];
    let tmp = '';
    for (const part of parts){
        tmp += part;
        if (tmp.endsWith('\\')) {
            tmp = tmp.slice(0, -1) + '.';
        } else {
            keys.push(tmp);
            tmp = '';
        }
    }
    return keys;
}
function _getKeyResolver(key) {
    const keys = _splitKey(key);
    return (obj)=>{
        for (const k of keys){
            if (k === '') {
                break;
            }
            obj = obj && obj[k];
        }
        return obj;
    };
}
function resolveObjectKey(obj, key) {
    const resolver = keyResolvers[key] || (keyResolvers[key] = _getKeyResolver(key));
    return resolver(obj);
}
/**
 * @private
 */ function _capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}
const defined = (value)=>typeof value !== 'undefined';
const isFunction = (value)=>typeof value === 'function';
// Adapted from https://stackoverflow.com/questions/31128855/comparing-ecma6-sets-for-equality#31129384
const setsEqual = (a, b)=>{
    if (a.size !== b.size) {
        return false;
    }
    for (const item of a){
        if (!b.has(item)) {
            return false;
        }
    }
    return true;
};
/**
 * @param e - The event
 * @private
 */ function _isClickEvent(e) {
    return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu';
}

/**
 * @alias Chart.helpers.math
 * @namespace
 */ const PI = Math.PI;
const TAU = 2 * PI;
const PITAU = TAU + PI;
const INFINITY = Number.POSITIVE_INFINITY;
const RAD_PER_DEG = PI / 180;
const HALF_PI = PI / 2;
const QUARTER_PI = PI / 4;
const TWO_THIRDS_PI = PI * 2 / 3;
const log10 = Math.log10;
const sign = Math.sign;
function almostEquals(x, y, epsilon) {
    return Math.abs(x - y) < epsilon;
}
/**
 * Implementation of the nice number algorithm used in determining where axis labels will go
 */ function niceNum(range) {
    const roundedRange = Math.round(range);
    range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range;
    const niceRange = Math.pow(10, Math.floor(log10(range)));
    const fraction = range / niceRange;
    const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
    return niceFraction * niceRange;
}
/**
 * Returns an array of factors sorted from 1 to sqrt(value)
 * @private
 */ function _factorize(value) {
    const result = [];
    const sqrt = Math.sqrt(value);
    let i;
    for(i = 1; i < sqrt; i++){
        if (value % i === 0) {
            result.push(i);
            result.push(value / i);
        }
    }
    if (sqrt === (sqrt | 0)) {
        result.push(sqrt);
    }
    result.sort((a, b)=>a - b).pop();
    return result;
}
/**
 * Verifies that attempting to coerce n to string or number won't throw a TypeError.
 */ function isNonPrimitive(n) {
    return typeof n === 'symbol' || typeof n === 'object' && n !== null && !(Symbol.toPrimitive in n || 'toString' in n || 'valueOf' in n);
}
function isNumber(n) {
    return !isNonPrimitive(n) && !isNaN(parseFloat(n)) && isFinite(n);
}
function almostWhole(x, epsilon) {
    const rounded = Math.round(x);
    return rounded - epsilon <= x && rounded + epsilon >= x;
}
/**
 * @private
 */ function _setMinAndMaxByKey(array, target, property) {
    let i, ilen, value;
    for(i = 0, ilen = array.length; i < ilen; i++){
        value = array[i][property];
        if (!isNaN(value)) {
            target.min = Math.min(target.min, value);
            target.max = Math.max(target.max, value);
        }
    }
}
function toRadians(degrees) {
    return degrees * (PI / 180);
}
function toDegrees(radians) {
    return radians * (180 / PI);
}
/**
 * Returns the number of decimal places
 * i.e. the number of digits after the decimal point, of the value of this Number.
 * @param x - A number.
 * @returns The number of decimal places.
 * @private
 */ function _decimalPlaces(x) {
    if (!isNumberFinite(x)) {
        return;
    }
    let e = 1;
    let p = 0;
    while(Math.round(x * e) / e !== x){
        e *= 10;
        p++;
    }
    return p;
}
// Gets the angle from vertical upright to the point about a centre.
function getAngleFromPoint(centrePoint, anglePoint) {
    const distanceFromXCenter = anglePoint.x - centrePoint.x;
    const distanceFromYCenter = anglePoint.y - centrePoint.y;
    const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
    let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
    if (angle < -0.5 * PI) {
        angle += TAU; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
    }
    return {
        angle,
        distance: radialDistanceFromCenter
    };
}
function distanceBetweenPoints(pt1, pt2) {
    return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
}
/**
 * Shortest distance between angles, in either direction.
 * @private
 */ function _angleDiff(a, b) {
    return (a - b + PITAU) % TAU - PI;
}
/**
 * Normalize angle to be between 0 and 2*PI
 * @private
 */ function _normalizeAngle(a) {
    return (a % TAU + TAU) % TAU;
}
/**
 * @private
 */ function _angleBetween(angle, start, end, sameAngleIsFullCircle) {
    const a = _normalizeAngle(angle);
    const s = _normalizeAngle(start);
    const e = _normalizeAngle(end);
    const angleToStart = _normalizeAngle(s - a);
    const angleToEnd = _normalizeAngle(e - a);
    const startToAngle = _normalizeAngle(a - s);
    const endToAngle = _normalizeAngle(a - e);
    return a === s || a === e || sameAngleIsFullCircle && s === e || angleToStart > angleToEnd && startToAngle < endToAngle;
}
/**
 * Limit `value` between `min` and `max`
 * @param value
 * @param min
 * @param max
 * @private
 */ function _limitValue(value, min, max) {
    return Math.max(min, Math.min(max, value));
}
/**
 * @param {number} value
 * @private
 */ function _int16Range(value) {
    return _limitValue(value, -32768, 32767);
}
/**
 * @param value
 * @param start
 * @param end
 * @param [epsilon]
 * @private
 */ function _isBetween(value, start, end, epsilon = 1e-6) {
    return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon;
}

function _lookup(table, value, cmp) {
    cmp = cmp || ((index)=>table[index] < value);
    let hi = table.length - 1;
    let lo = 0;
    let mid;
    while(hi - lo > 1){
        mid = lo + hi >> 1;
        if (cmp(mid)) {
            lo = mid;
        } else {
            hi = mid;
        }
    }
    return {
        lo,
        hi
    };
}
/**
 * Binary search
 * @param table - the table search. must be sorted!
 * @param key - property name for the value in each entry
 * @param value - value to find
 * @param last - lookup last index
 * @private
 */ const _lookupByKey = (table, key, value, last)=>_lookup(table, value, last ? (index)=>{
        const ti = table[index][key];
        return ti < value || ti === value && table[index + 1][key] === value;
    } : (index)=>table[index][key] < value);
/**
 * Reverse binary search
 * @param table - the table search. must be sorted!
 * @param key - property name for the value in each entry
 * @param value - value to find
 * @private
 */ const _rlookupByKey = (table, key, value)=>_lookup(table, value, (index)=>table[index][key] >= value);
/**
 * Return subset of `values` between `min` and `max` inclusive.
 * Values are assumed to be in sorted order.
 * @param values - sorted array of values
 * @param min - min value
 * @param max - max value
 */ function _filterBetween(values, min, max) {
    let start = 0;
    let end = values.length;
    while(start < end && values[start] < min){
        start++;
    }
    while(end > start && values[end - 1] > max){
        end--;
    }
    return start > 0 || end < values.length ? values.slice(start, end) : values;
}
const arrayEvents = [
    'push',
    'pop',
    'shift',
    'splice',
    'unshift'
];
function listenArrayEvents(array, listener) {
    if (array._chartjs) {
        array._chartjs.listeners.push(listener);
        return;
    }
    Object.defineProperty(array, '_chartjs', {
        configurable: true,
        enumerable: false,
        value: {
            listeners: [
                listener
            ]
        }
    });
    arrayEvents.forEach((key)=>{
        const method = '_onData' + _capitalize(key);
        const base = array[key];
        Object.defineProperty(array, key, {
            configurable: true,
            enumerable: false,
            value (...args) {
                const res = base.apply(this, args);
                array._chartjs.listeners.forEach((object)=>{
                    if (typeof object[method] === 'function') {
                        object[method](...args);
                    }
                });
                return res;
            }
        });
    });
}
function unlistenArrayEvents(array, listener) {
    const stub = array._chartjs;
    if (!stub) {
        return;
    }
    const listeners = stub.listeners;
    const index = listeners.indexOf(listener);
    if (index !== -1) {
        listeners.splice(index, 1);
    }
    if (listeners.length > 0) {
        return;
    }
    arrayEvents.forEach((key)=>{
        delete array[key];
    });
    delete array._chartjs;
}
/**
 * @param items
 */ function _arrayUnique(items) {
    const set = new Set(items);
    if (set.size === items.length) {
        return items;
    }
    return Array.from(set);
}

function fontString(pixelSize, fontStyle, fontFamily) {
    return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
}
/**
* Request animation polyfill
*/ const requestAnimFrame = function() {
    if (typeof window === 'undefined') {
        return function(callback) {
            return callback();
        };
    }
    return window.requestAnimationFrame;
}();
/**
 * Throttles calling `fn` once per animation frame
 * Latest arguments are used on the actual call
 */ function throttled(fn, thisArg) {
    let argsToUse = [];
    let ticking = false;
    return function(...args) {
        // Save the args for use later
        argsToUse = args;
        if (!ticking) {
            ticking = true;
            requestAnimFrame.call(window, ()=>{
                ticking = false;
                fn.apply(thisArg, argsToUse);
            });
        }
    };
}
/**
 * Debounces calling `fn` for `delay` ms
 */ function debounce$1(fn, delay) {
    let timeout;
    return function(...args) {
        if (delay) {
            clearTimeout(timeout);
            timeout = setTimeout(fn, delay, args);
        } else {
            fn.apply(this, args);
        }
        return delay;
    };
}
/**
 * Converts 'start' to 'left', 'end' to 'right' and others to 'center'
 * @private
 */ const _toLeftRightCenter = (align)=>align === 'start' ? 'left' : align === 'end' ? 'right' : 'center';
/**
 * Returns `start`, `end` or `(start + end) / 2` depending on `align`. Defaults to `center`
 * @private
 */ const _alignStartEnd = (align, start, end)=>align === 'start' ? start : align === 'end' ? end : (start + end) / 2;
/**
 * Returns `left`, `right` or `(left + right) / 2` depending on `align`. Defaults to `left`
 * @private
 */ const _textX = (align, left, right, rtl)=>{
    const check = rtl ? 'left' : 'right';
    return align === check ? right : align === 'center' ? (left + right) / 2 : left;
};
/**
 * Return start and count of visible points.
 * @private
 */ function _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) {
    const pointCount = points.length;
    let start = 0;
    let count = pointCount;
    if (meta._sorted) {
        const { iScale , vScale , _parsed  } = meta;
        const spanGaps = meta.dataset ? meta.dataset.options ? meta.dataset.options.spanGaps : null : null;
        const axis = iScale.axis;
        const { min , max , minDefined , maxDefined  } = iScale.getUserBounds();
        if (minDefined) {
            start = Math.min(// @ts-expect-error Need to type _parsed
            _lookupByKey(_parsed, axis, min).lo, // @ts-expect-error Need to fix types on _lookupByKey
            animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo);
            if (spanGaps) {
                const distanceToDefinedLo = _parsed.slice(0, start + 1).reverse().findIndex((point)=>!isNullOrUndef(point[vScale.axis]));
                start -= Math.max(0, distanceToDefinedLo);
            }
            start = _limitValue(start, 0, pointCount - 1);
        }
        if (maxDefined) {
            let end = Math.max(// @ts-expect-error Need to type _parsed
            _lookupByKey(_parsed, iScale.axis, max, true).hi + 1, // @ts-expect-error Need to fix types on _lookupByKey
            animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max), true).hi + 1);
            if (spanGaps) {
                const distanceToDefinedHi = _parsed.slice(end - 1).findIndex((point)=>!isNullOrUndef(point[vScale.axis]));
                end += Math.max(0, distanceToDefinedHi);
            }
            count = _limitValue(end, start, pointCount) - start;
        } else {
            count = pointCount - start;
        }
    }
    return {
        start,
        count
    };
}
/**
 * Checks if the scale ranges have changed.
 * @param {object} meta - dataset meta.
 * @returns {boolean}
 * @private
 */ function _scaleRangesChanged(meta) {
    const { xScale , yScale , _scaleRanges  } = meta;
    const newRanges = {
        xmin: xScale.min,
        xmax: xScale.max,
        ymin: yScale.min,
        ymax: yScale.max
    };
    if (!_scaleRanges) {
        meta._scaleRanges = newRanges;
        return true;
    }
    const changed = _scaleRanges.xmin !== xScale.min || _scaleRanges.xmax !== xScale.max || _scaleRanges.ymin !== yScale.min || _scaleRanges.ymax !== yScale.max;
    Object.assign(_scaleRanges, newRanges);
    return changed;
}

const atEdge = (t)=>t === 0 || t === 1;
const elasticIn = (t, s, p)=>-(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p));
const elasticOut = (t, s, p)=>Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1;
/**
 * Easing functions adapted from Robert Penner's easing equations.
 * @namespace Chart.helpers.easing.effects
 * @see http://www.robertpenner.com/easing/
 */ const effects = {
    linear: (t)=>t,
    easeInQuad: (t)=>t * t,
    easeOutQuad: (t)=>-t * (t - 2),
    easeInOutQuad: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t : -0.5 * (--t * (t - 2) - 1),
    easeInCubic: (t)=>t * t * t,
    easeOutCubic: (t)=>(t -= 1) * t * t + 1,
    easeInOutCubic: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t : 0.5 * ((t -= 2) * t * t + 2),
    easeInQuart: (t)=>t * t * t * t,
    easeOutQuart: (t)=>-((t -= 1) * t * t * t - 1),
    easeInOutQuart: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t * t : -0.5 * ((t -= 2) * t * t * t - 2),
    easeInQuint: (t)=>t * t * t * t * t,
    easeOutQuint: (t)=>(t -= 1) * t * t * t * t + 1,
    easeInOutQuint: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t * t * t : 0.5 * ((t -= 2) * t * t * t * t + 2),
    easeInSine: (t)=>-Math.cos(t * HALF_PI) + 1,
    easeOutSine: (t)=>Math.sin(t * HALF_PI),
    easeInOutSine: (t)=>-0.5 * (Math.cos(PI * t) - 1),
    easeInExpo: (t)=>t === 0 ? 0 : Math.pow(2, 10 * (t - 1)),
    easeOutExpo: (t)=>t === 1 ? 1 : -Math.pow(2, -10 * t) + 1,
    easeInOutExpo: (t)=>atEdge(t) ? t : t < 0.5 ? 0.5 * Math.pow(2, 10 * (t * 2 - 1)) : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2),
    easeInCirc: (t)=>t >= 1 ? t : -(Math.sqrt(1 - t * t) - 1),
    easeOutCirc: (t)=>Math.sqrt(1 - (t -= 1) * t),
    easeInOutCirc: (t)=>(t /= 0.5) < 1 ? -0.5 * (Math.sqrt(1 - t * t) - 1) : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1),
    easeInElastic: (t)=>atEdge(t) ? t : elasticIn(t, 0.075, 0.3),
    easeOutElastic: (t)=>atEdge(t) ? t : elasticOut(t, 0.075, 0.3),
    easeInOutElastic (t) {
        const s = 0.1125;
        const p = 0.45;
        return atEdge(t) ? t : t < 0.5 ? 0.5 * elasticIn(t * 2, s, p) : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p);
    },
    easeInBack (t) {
        const s = 1.70158;
        return t * t * ((s + 1) * t - s);
    },
    easeOutBack (t) {
        const s = 1.70158;
        return (t -= 1) * t * ((s + 1) * t + s) + 1;
    },
    easeInOutBack (t) {
        let s = 1.70158;
        if ((t /= 0.5) < 1) {
            return 0.5 * (t * t * (((s *= 1.525) + 1) * t - s));
        }
        return 0.5 * ((t -= 2) * t * (((s *= 1.525) + 1) * t + s) + 2);
    },
    easeInBounce: (t)=>1 - effects.easeOutBounce(1 - t),
    easeOutBounce (t) {
        const m = 7.5625;
        const d = 2.75;
        if (t < 1 / d) {
            return m * t * t;
        }
        if (t < 2 / d) {
            return m * (t -= 1.5 / d) * t + 0.75;
        }
        if (t < 2.5 / d) {
            return m * (t -= 2.25 / d) * t + 0.9375;
        }
        return m * (t -= 2.625 / d) * t + 0.984375;
    },
    easeInOutBounce: (t)=>t < 0.5 ? effects.easeInBounce(t * 2) * 0.5 : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5
};

function isPatternOrGradient(value) {
    if (value && typeof value === 'object') {
        const type = value.toString();
        return type === '[object CanvasPattern]' || type === '[object CanvasGradient]';
    }
    return false;
}
function color(value) {
    return isPatternOrGradient(value) ? value : new Color(value);
}
function getHoverColor(value) {
    return isPatternOrGradient(value) ? value : new Color(value).saturate(0.5).darken(0.1).hexString();
}

const numbers = [
    'x',
    'y',
    'borderWidth',
    'radius',
    'tension'
];
const colors = [
    'color',
    'borderColor',
    'backgroundColor'
];
function applyAnimationsDefaults(defaults) {
    defaults.set('animation', {
        delay: undefined,
        duration: 1000,
        easing: 'easeOutQuart',
        fn: undefined,
        from: undefined,
        loop: undefined,
        to: undefined,
        type: undefined
    });
    defaults.describe('animation', {
        _fallback: false,
        _indexable: false,
        _scriptable: (name)=>name !== 'onProgress' && name !== 'onComplete' && name !== 'fn'
    });
    defaults.set('animations', {
        colors: {
            type: 'color',
            properties: colors
        },
        numbers: {
            type: 'number',
            properties: numbers
        }
    });
    defaults.describe('animations', {
        _fallback: 'animation'
    });
    defaults.set('transitions', {
        active: {
            animation: {
                duration: 400
            }
        },
        resize: {
            animation: {
                duration: 0
            }
        },
        show: {
            animations: {
                colors: {
                    from: 'transparent'
                },
                visible: {
                    type: 'boolean',
                    duration: 0
                }
            }
        },
        hide: {
            animations: {
                colors: {
                    to: 'transparent'
                },
                visible: {
                    type: 'boolean',
                    easing: 'linear',
                    fn: (v)=>v | 0
                }
            }
        }
    });
}

function applyLayoutsDefaults(defaults) {
    defaults.set('layout', {
        autoPadding: true,
        padding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        }
    });
}

const intlCache = new Map();
function getNumberFormat(locale, options) {
    options = options || {};
    const cacheKey = locale + JSON.stringify(options);
    let formatter = intlCache.get(cacheKey);
    if (!formatter) {
        formatter = new Intl.NumberFormat(locale, options);
        intlCache.set(cacheKey, formatter);
    }
    return formatter;
}
function formatNumber(num, locale, options) {
    return getNumberFormat(locale, options).format(num);
}

const formatters = {
 values (value) {
        return isArray(value) ?  value : '' + value;
    },
 numeric (tickValue, index, ticks) {
        if (tickValue === 0) {
            return '0';
        }
        const locale = this.chart.options.locale;
        let notation;
        let delta = tickValue;
        if (ticks.length > 1) {
            const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));
            if (maxTick < 1e-4 || maxTick > 1e+15) {
                notation = 'scientific';
            }
            delta = calculateDelta(tickValue, ticks);
        }
        const logDelta = log10(Math.abs(delta));
        const numDecimal = isNaN(logDelta) ? 1 : Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);
        const options = {
            notation,
            minimumFractionDigits: numDecimal,
            maximumFractionDigits: numDecimal
        };
        Object.assign(options, this.options.ticks.format);
        return formatNumber(tickValue, locale, options);
    },
 logarithmic (tickValue, index, ticks) {
        if (tickValue === 0) {
            return '0';
        }
        const remain = ticks[index].significand || tickValue / Math.pow(10, Math.floor(log10(tickValue)));
        if ([
            1,
            2,
            3,
            5,
            10,
            15
        ].includes(remain) || index > 0.8 * ticks.length) {
            return formatters.numeric.call(this, tickValue, index, ticks);
        }
        return '';
    }
};
function calculateDelta(tickValue, ticks) {
    let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;
    if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {
        delta = tickValue - Math.floor(tickValue);
    }
    return delta;
}
 var Ticks = {
    formatters
};

function applyScaleDefaults(defaults) {
    defaults.set('scale', {
        display: true,
        offset: false,
        reverse: false,
        beginAtZero: false,
 bounds: 'ticks',
        clip: true,
 grace: 0,
        grid: {
            display: true,
            lineWidth: 1,
            drawOnChartArea: true,
            drawTicks: true,
            tickLength: 8,
            tickWidth: (_ctx, options)=>options.lineWidth,
            tickColor: (_ctx, options)=>options.color,
            offset: false
        },
        border: {
            display: true,
            dash: [],
            dashOffset: 0.0,
            width: 1
        },
        title: {
            display: false,
            text: '',
            padding: {
                top: 4,
                bottom: 4
            }
        },
        ticks: {
            minRotation: 0,
            maxRotation: 50,
            mirror: false,
            textStrokeWidth: 0,
            textStrokeColor: '',
            padding: 3,
            display: true,
            autoSkip: true,
            autoSkipPadding: 3,
            labelOffset: 0,
            callback: Ticks.formatters.values,
            minor: {},
            major: {},
            align: 'center',
            crossAlign: 'near',
            showLabelBackdrop: false,
            backdropColor: 'rgba(255, 255, 255, 0.75)',
            backdropPadding: 2
        }
    });
    defaults.route('scale.ticks', 'color', '', 'color');
    defaults.route('scale.grid', 'color', '', 'borderColor');
    defaults.route('scale.border', 'color', '', 'borderColor');
    defaults.route('scale.title', 'color', '', 'color');
    defaults.describe('scale', {
        _fallback: false,
        _scriptable: (name)=>!name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',
        _indexable: (name)=>name !== 'borderDash' && name !== 'tickBorderDash' && name !== 'dash'
    });
    defaults.describe('scales', {
        _fallback: 'scale'
    });
    defaults.describe('scale.ticks', {
        _scriptable: (name)=>name !== 'backdropPadding' && name !== 'callback',
        _indexable: (name)=>name !== 'backdropPadding'
    });
}

const overrides = Object.create(null);
const descriptors = Object.create(null);
 function getScope$1(node, key) {
    if (!key) {
        return node;
    }
    const keys = key.split('.');
    for(let i = 0, n = keys.length; i < n; ++i){
        const k = keys[i];
        node = node[k] || (node[k] = Object.create(null));
    }
    return node;
}
function set(root, scope, values) {
    if (typeof scope === 'string') {
        return merge(getScope$1(root, scope), values);
    }
    return merge(getScope$1(root, ''), scope);
}
 class Defaults {
    constructor(_descriptors, _appliers){
        this.animation = undefined;
        this.backgroundColor = 'rgba(0,0,0,0.1)';
        this.borderColor = 'rgba(0,0,0,0.1)';
        this.color = '#666';
        this.datasets = {};
        this.devicePixelRatio = (context)=>context.chart.platform.getDevicePixelRatio();
        this.elements = {};
        this.events = [
            'mousemove',
            'mouseout',
            'click',
            'touchstart',
            'touchmove'
        ];
        this.font = {
            family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
            size: 12,
            style: 'normal',
            lineHeight: 1.2,
            weight: null
        };
        this.hover = {};
        this.hoverBackgroundColor = (ctx, options)=>getHoverColor(options.backgroundColor);
        this.hoverBorderColor = (ctx, options)=>getHoverColor(options.borderColor);
        this.hoverColor = (ctx, options)=>getHoverColor(options.color);
        this.indexAxis = 'x';
        this.interaction = {
            mode: 'nearest',
            intersect: true,
            includeInvisible: false
        };
        this.maintainAspectRatio = true;
        this.onHover = null;
        this.onClick = null;
        this.parsing = true;
        this.plugins = {};
        this.responsive = true;
        this.scale = undefined;
        this.scales = {};
        this.showLine = true;
        this.drawActiveElementsOnTop = true;
        this.describe(_descriptors);
        this.apply(_appliers);
    }
 set(scope, values) {
        return set(this, scope, values);
    }
 get(scope) {
        return getScope$1(this, scope);
    }
 describe(scope, values) {
        return set(descriptors, scope, values);
    }
    override(scope, values) {
        return set(overrides, scope, values);
    }
 route(scope, name, targetScope, targetName) {
        const scopeObject = getScope$1(this, scope);
        const targetScopeObject = getScope$1(this, targetScope);
        const privateName = '_' + name;
        Object.defineProperties(scopeObject, {
            [privateName]: {
                value: scopeObject[name],
                writable: true
            },
            [name]: {
                enumerable: true,
                get () {
                    const local = this[privateName];
                    const target = targetScopeObject[targetName];
                    if (isObject(local)) {
                        return Object.assign({}, target, local);
                    }
                    return valueOrDefault(local, target);
                },
                set (value) {
                    this[privateName] = value;
                }
            }
        });
    }
    apply(appliers) {
        appliers.forEach((apply)=>apply(this));
    }
}
var defaults = /* #__PURE__ */ new Defaults({
    _scriptable: (name)=>!name.startsWith('on'),
    _indexable: (name)=>name !== 'events',
    hover: {
        _fallback: 'interaction'
    },
    interaction: {
        _scriptable: false,
        _indexable: false
    }
}, [
    applyAnimationsDefaults,
    applyLayoutsDefaults,
    applyScaleDefaults
]);

/**
 * Converts the given font object into a CSS font string.
 * @param font - A font object.
 * @return The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
 * @private
 */ function toFontString(font) {
    if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) {
        return null;
    }
    return (font.style ? font.style + ' ' : '') + (font.weight ? font.weight + ' ' : '') + font.size + 'px ' + font.family;
}
/**
 * @private
 */ function _measureText(ctx, data, gc, longest, string) {
    let textWidth = data[string];
    if (!textWidth) {
        textWidth = data[string] = ctx.measureText(string).width;
        gc.push(string);
    }
    if (textWidth > longest) {
        longest = textWidth;
    }
    return longest;
}
/**
 * @private
 */ // eslint-disable-next-line complexity
function _longestText(ctx, font, arrayOfThings, cache) {
    cache = cache || {};
    let data = cache.data = cache.data || {};
    let gc = cache.garbageCollect = cache.garbageCollect || [];
    if (cache.font !== font) {
        data = cache.data = {};
        gc = cache.garbageCollect = [];
        cache.font = font;
    }
    ctx.save();
    ctx.font = font;
    let longest = 0;
    const ilen = arrayOfThings.length;
    let i, j, jlen, thing, nestedThing;
    for(i = 0; i < ilen; i++){
        thing = arrayOfThings[i];
        // Undefined strings and arrays should not be measured
        if (thing !== undefined && thing !== null && !isArray(thing)) {
            longest = _measureText(ctx, data, gc, longest, thing);
        } else if (isArray(thing)) {
            // if it is an array lets measure each element
            // to do maybe simplify this function a bit so we can do this more recursively?
            for(j = 0, jlen = thing.length; j < jlen; j++){
                nestedThing = thing[j];
                // Undefined strings and arrays should not be measured
                if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {
                    longest = _measureText(ctx, data, gc, longest, nestedThing);
                }
            }
        }
    }
    ctx.restore();
    const gcLen = gc.length / 2;
    if (gcLen > arrayOfThings.length) {
        for(i = 0; i < gcLen; i++){
            delete data[gc[i]];
        }
        gc.splice(0, gcLen);
    }
    return longest;
}
/**
 * Returns the aligned pixel value to avoid anti-aliasing blur
 * @param chart - The chart instance.
 * @param pixel - A pixel value.
 * @param width - The width of the element.
 * @returns The aligned pixel value.
 * @private
 */ function _alignPixel(chart, pixel, width) {
    const devicePixelRatio = chart.currentDevicePixelRatio;
    const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0;
    return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
}
/**
 * Clears the entire canvas.
 */ function clearCanvas(canvas, ctx) {
    if (!ctx && !canvas) {
        return;
    }
    ctx = ctx || canvas.getContext('2d');
    ctx.save();
    // canvas.width and canvas.height do not consider the canvas transform,
    // while clearRect does
    ctx.resetTransform();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.restore();
}
function drawPoint(ctx, options, x, y) {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    drawPointLegend(ctx, options, x, y, null);
}
// eslint-disable-next-line complexity
function drawPointLegend(ctx, options, x, y, w) {
    let type, xOffset, yOffset, size, cornerRadius, width, xOffsetW, yOffsetW;
    const style = options.pointStyle;
    const rotation = options.rotation;
    const radius = options.radius;
    let rad = (rotation || 0) * RAD_PER_DEG;
    if (style && typeof style === 'object') {
        type = style.toString();
        if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
            ctx.save();
            ctx.translate(x, y);
            ctx.rotate(rad);
            ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
            ctx.restore();
            return;
        }
    }
    if (isNaN(radius) || radius <= 0) {
        return;
    }
    ctx.beginPath();
    switch(style){
        // Default includes circle
        default:
            if (w) {
                ctx.ellipse(x, y, w / 2, radius, 0, 0, TAU);
            } else {
                ctx.arc(x, y, radius, 0, TAU);
            }
            ctx.closePath();
            break;
        case 'triangle':
            width = w ? w / 2 : radius;
            ctx.moveTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);
            rad += TWO_THIRDS_PI;
            ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);
            rad += TWO_THIRDS_PI;
            ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);
            ctx.closePath();
            break;
        case 'rectRounded':
            // NOTE: the rounded rect implementation changed to use `arc` instead of
            // `quadraticCurveTo` since it generates better results when rect is
            // almost a circle. 0.516 (instead of 0.5) produces results with visually
            // closer proportion to the previous impl and it is inscribed in the
            // circle with `radius`. For more details, see the following PRs:
            // https://github.com/chartjs/Chart.js/issues/5597
            // https://github.com/chartjs/Chart.js/issues/5858
            cornerRadius = radius * 0.516;
            size = radius - cornerRadius;
            xOffset = Math.cos(rad + QUARTER_PI) * size;
            xOffsetW = Math.cos(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);
            yOffset = Math.sin(rad + QUARTER_PI) * size;
            yOffsetW = Math.sin(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);
            ctx.arc(x - xOffsetW, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
            ctx.arc(x + yOffsetW, y - xOffset, cornerRadius, rad - HALF_PI, rad);
            ctx.arc(x + xOffsetW, y + yOffset, cornerRadius, rad, rad + HALF_PI);
            ctx.arc(x - yOffsetW, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
            ctx.closePath();
            break;
        case 'rect':
            if (!rotation) {
                size = Math.SQRT1_2 * radius;
                width = w ? w / 2 : size;
                ctx.rect(x - width, y - size, 2 * width, 2 * size);
                break;
            }
            rad += QUARTER_PI;
        /* falls through */ case 'rectRot':
            xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);
            xOffset = Math.cos(rad) * radius;
            yOffset = Math.sin(rad) * radius;
            yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);
            ctx.moveTo(x - xOffsetW, y - yOffset);
            ctx.lineTo(x + yOffsetW, y - xOffset);
            ctx.lineTo(x + xOffsetW, y + yOffset);
            ctx.lineTo(x - yOffsetW, y + xOffset);
            ctx.closePath();
            break;
        case 'crossRot':
            rad += QUARTER_PI;
        /* falls through */ case 'cross':
            xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);
            xOffset = Math.cos(rad) * radius;
            yOffset = Math.sin(rad) * radius;
            yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);
            ctx.moveTo(x - xOffsetW, y - yOffset);
            ctx.lineTo(x + xOffsetW, y + yOffset);
            ctx.moveTo(x + yOffsetW, y - xOffset);
            ctx.lineTo(x - yOffsetW, y + xOffset);
            break;
        case 'star':
            xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);
            xOffset = Math.cos(rad) * radius;
            yOffset = Math.sin(rad) * radius;
            yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);
            ctx.moveTo(x - xOffsetW, y - yOffset);
            ctx.lineTo(x + xOffsetW, y + yOffset);
            ctx.moveTo(x + yOffsetW, y - xOffset);
            ctx.lineTo(x - yOffsetW, y + xOffset);
            rad += QUARTER_PI;
            xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);
            xOffset = Math.cos(rad) * radius;
            yOffset = Math.sin(rad) * radius;
            yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);
            ctx.moveTo(x - xOffsetW, y - yOffset);
            ctx.lineTo(x + xOffsetW, y + yOffset);
            ctx.moveTo(x + yOffsetW, y - xOffset);
            ctx.lineTo(x - yOffsetW, y + xOffset);
            break;
        case 'line':
            xOffset = w ? w / 2 : Math.cos(rad) * radius;
            yOffset = Math.sin(rad) * radius;
            ctx.moveTo(x - xOffset, y - yOffset);
            ctx.lineTo(x + xOffset, y + yOffset);
            break;
        case 'dash':
            ctx.moveTo(x, y);
            ctx.lineTo(x + Math.cos(rad) * (w ? w / 2 : radius), y + Math.sin(rad) * radius);
            break;
        case false:
            ctx.closePath();
            break;
    }
    ctx.fill();
    if (options.borderWidth > 0) {
        ctx.stroke();
    }
}
/**
 * Returns true if the point is inside the rectangle
 * @param point - The point to test
 * @param area - The rectangle
 * @param margin - allowed margin
 * @private
 */ function _isPointInArea(point, area, margin) {
    margin = margin || 0.5; // margin - default is to match rounded decimals
    return !area || point && point.x > area.left - margin && point.x < area.right + margin && point.y > area.top - margin && point.y < area.bottom + margin;
}
function clipArea(ctx, area) {
    ctx.save();
    ctx.beginPath();
    ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
    ctx.clip();
}
function unclipArea(ctx) {
    ctx.restore();
}
/**
 * @private
 */ function _steppedLineTo(ctx, previous, target, flip, mode) {
    if (!previous) {
        return ctx.lineTo(target.x, target.y);
    }
    if (mode === 'middle') {
        const midpoint = (previous.x + target.x) / 2.0;
        ctx.lineTo(midpoint, previous.y);
        ctx.lineTo(midpoint, target.y);
    } else if (mode === 'after' !== !!flip) {
        ctx.lineTo(previous.x, target.y);
    } else {
        ctx.lineTo(target.x, previous.y);
    }
    ctx.lineTo(target.x, target.y);
}
/**
 * @private
 */ function _bezierCurveTo(ctx, previous, target, flip) {
    if (!previous) {
        return ctx.lineTo(target.x, target.y);
    }
    ctx.bezierCurveTo(flip ? previous.cp1x : previous.cp2x, flip ? previous.cp1y : previous.cp2y, flip ? target.cp2x : target.cp1x, flip ? target.cp2y : target.cp1y, target.x, target.y);
}
function setRenderOpts(ctx, opts) {
    if (opts.translation) {
        ctx.translate(opts.translation[0], opts.translation[1]);
    }
    if (!isNullOrUndef(opts.rotation)) {
        ctx.rotate(opts.rotation);
    }
    if (opts.color) {
        ctx.fillStyle = opts.color;
    }
    if (opts.textAlign) {
        ctx.textAlign = opts.textAlign;
    }
    if (opts.textBaseline) {
        ctx.textBaseline = opts.textBaseline;
    }
}
function decorateText(ctx, x, y, line, opts) {
    if (opts.strikethrough || opts.underline) {
        /**
     * Now that IE11 support has been dropped, we can use more
     * of the TextMetrics object. The actual bounding boxes
     * are unflagged in Chrome, Firefox, Edge, and Safari so they
     * can be safely used.
     * See https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics#Browser_compatibility
     */ const metrics = ctx.measureText(line);
        const left = x - metrics.actualBoundingBoxLeft;
        const right = x + metrics.actualBoundingBoxRight;
        const top = y - metrics.actualBoundingBoxAscent;
        const bottom = y + metrics.actualBoundingBoxDescent;
        const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom;
        ctx.strokeStyle = ctx.fillStyle;
        ctx.beginPath();
        ctx.lineWidth = opts.decorationWidth || 2;
        ctx.moveTo(left, yDecoration);
        ctx.lineTo(right, yDecoration);
        ctx.stroke();
    }
}
function drawBackdrop(ctx, opts) {
    const oldColor = ctx.fillStyle;
    ctx.fillStyle = opts.color;
    ctx.fillRect(opts.left, opts.top, opts.width, opts.height);
    ctx.fillStyle = oldColor;
}
/**
 * Render text onto the canvas
 */ function renderText(ctx, text, x, y, font, opts = {}) {
    const lines = isArray(text) ? text : [
        text
    ];
    const stroke = opts.strokeWidth > 0 && opts.strokeColor !== '';
    let i, line;
    ctx.save();
    ctx.font = font.string;
    setRenderOpts(ctx, opts);
    for(i = 0; i < lines.length; ++i){
        line = lines[i];
        if (opts.backdrop) {
            drawBackdrop(ctx, opts.backdrop);
        }
        if (stroke) {
            if (opts.strokeColor) {
                ctx.strokeStyle = opts.strokeColor;
            }
            if (!isNullOrUndef(opts.strokeWidth)) {
                ctx.lineWidth = opts.strokeWidth;
            }
            ctx.strokeText(line, x, y, opts.maxWidth);
        }
        ctx.fillText(line, x, y, opts.maxWidth);
        decorateText(ctx, x, y, line, opts);
        y += Number(font.lineHeight);
    }
    ctx.restore();
}
/**
 * Add a path of a rectangle with rounded corners to the current sub-path
 * @param ctx - Context
 * @param rect - Bounding rect
 */ function addRoundedRectPath(ctx, rect) {
    const { x , y , w , h , radius  } = rect;
    // top left arc
    ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, 1.5 * PI, PI, true);
    // line from top left to bottom left
    ctx.lineTo(x, y + h - radius.bottomLeft);
    // bottom left arc
    ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true);
    // line from bottom left to bottom right
    ctx.lineTo(x + w - radius.bottomRight, y + h);
    // bottom right arc
    ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true);
    // line from bottom right to top right
    ctx.lineTo(x + w, y + radius.topRight);
    // top right arc
    ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true);
    // line from top right to top left
    ctx.lineTo(x + radius.topLeft, y);
}

const LINE_HEIGHT = /^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/;
const FONT_STYLE = /^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;
/**
 * @alias Chart.helpers.options
 * @namespace
 */ /**
 * Converts the given line height `value` in pixels for a specific font `size`.
 * @param value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
 * @param size - The font size (in pixels) used to resolve relative `value`.
 * @returns The effective line height in pixels (size * 1.2 if value is invalid).
 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
 * @since 2.7.0
 */ function toLineHeight(value, size) {
    const matches = ('' + value).match(LINE_HEIGHT);
    if (!matches || matches[1] === 'normal') {
        return size * 1.2;
    }
    value = +matches[2];
    switch(matches[3]){
        case 'px':
            return value;
        case '%':
            value /= 100;
            break;
    }
    return size * value;
}
const numberOrZero = (v)=>+v || 0;
function _readValueToProps(value, props) {
    const ret = {};
    const objProps = isObject(props);
    const keys = objProps ? Object.keys(props) : props;
    const read = isObject(value) ? objProps ? (prop)=>valueOrDefault(value[prop], value[props[prop]]) : (prop)=>value[prop] : ()=>value;
    for (const prop of keys){
        ret[prop] = numberOrZero(read(prop));
    }
    return ret;
}
/**
 * Converts the given value into a TRBL object.
 * @param value - If a number, set the value to all TRBL component,
 *  else, if an object, use defined properties and sets undefined ones to 0.
 *  x / y are shorthands for same value for left/right and top/bottom.
 * @returns The padding values (top, right, bottom, left)
 * @since 3.0.0
 */ function toTRBL(value) {
    return _readValueToProps(value, {
        top: 'y',
        right: 'x',
        bottom: 'y',
        left: 'x'
    });
}
/**
 * Converts the given value into a TRBL corners object (similar with css border-radius).
 * @param value - If a number, set the value to all TRBL corner components,
 *  else, if an object, use defined properties and sets undefined ones to 0.
 * @returns The TRBL corner values (topLeft, topRight, bottomLeft, bottomRight)
 * @since 3.0.0
 */ function toTRBLCorners(value) {
    return _readValueToProps(value, [
        'topLeft',
        'topRight',
        'bottomLeft',
        'bottomRight'
    ]);
}
/**
 * Converts the given value into a padding object with pre-computed width/height.
 * @param value - If a number, set the value to all TRBL component,
 *  else, if an object, use defined properties and sets undefined ones to 0.
 *  x / y are shorthands for same value for left/right and top/bottom.
 * @returns The padding values (top, right, bottom, left, width, height)
 * @since 2.7.0
 */ function toPadding(value) {
    const obj = toTRBL(value);
    obj.width = obj.left + obj.right;
    obj.height = obj.top + obj.bottom;
    return obj;
}
/**
 * Parses font options and returns the font object.
 * @param options - A object that contains font options to be parsed.
 * @param fallback - A object that contains fallback font options.
 * @return The font object.
 * @private
 */ function toFont(options, fallback) {
    options = options || {};
    fallback = fallback || defaults.font;
    let size = valueOrDefault(options.size, fallback.size);
    if (typeof size === 'string') {
        size = parseInt(size, 10);
    }
    let style = valueOrDefault(options.style, fallback.style);
    if (style && !('' + style).match(FONT_STYLE)) {
        console.warn('Invalid font style specified: "' + style + '"');
        style = undefined;
    }
    const font = {
        family: valueOrDefault(options.family, fallback.family),
        lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size),
        size,
        style,
        weight: valueOrDefault(options.weight, fallback.weight),
        string: ''
    };
    font.string = toFontString(font);
    return font;
}
/**
 * Evaluates the given `inputs` sequentially and returns the first defined value.
 * @param inputs - An array of values, falling back to the last value.
 * @param context - If defined and the current value is a function, the value
 * is called with `context` as first argument and the result becomes the new input.
 * @param index - If defined and the current value is an array, the value
 * at `index` become the new input.
 * @param info - object to return information about resolution in
 * @param info.cacheable - Will be set to `false` if option is not cacheable.
 * @since 2.7.0
 */ function resolve(inputs, context, index, info) {
    let cacheable = true;
    let i, ilen, value;
    for(i = 0, ilen = inputs.length; i < ilen; ++i){
        value = inputs[i];
        if (value === undefined) {
            continue;
        }
        if (context !== undefined && typeof value === 'function') {
            value = value(context);
            cacheable = false;
        }
        if (index !== undefined && isArray(value)) {
            value = value[index % value.length];
            cacheable = false;
        }
        if (value !== undefined) {
            if (info && !cacheable) {
                info.cacheable = false;
            }
            return value;
        }
    }
}
/**
 * @param minmax
 * @param grace
 * @param beginAtZero
 * @private
 */ function _addGrace(minmax, grace, beginAtZero) {
    const { min , max  } = minmax;
    const change = toDimension(grace, (max - min) / 2);
    const keepZero = (value, add)=>beginAtZero && value === 0 ? 0 : value + add;
    return {
        min: keepZero(min, -Math.abs(change)),
        max: keepZero(max, change)
    };
}
function createContext(parentContext, context) {
    return Object.assign(Object.create(parentContext), context);
}

/**
 * Creates a Proxy for resolving raw values for options.
 * @param scopes - The option scopes to look for values, in resolution order
 * @param prefixes - The prefixes for values, in resolution order.
 * @param rootScopes - The root option scopes
 * @param fallback - Parent scopes fallback
 * @param getTarget - callback for getting the target for changed values
 * @returns Proxy
 * @private
 */ function _createResolver(scopes, prefixes = [
    ''
], rootScopes, fallback, getTarget = ()=>scopes[0]) {
    const finalRootScopes = rootScopes || scopes;
    if (typeof fallback === 'undefined') {
        fallback = _resolve('_fallback', scopes);
    }
    const cache = {
        [Symbol.toStringTag]: 'Object',
        _cacheable: true,
        _scopes: scopes,
        _rootScopes: finalRootScopes,
        _fallback: fallback,
        _getTarget: getTarget,
        override: (scope)=>_createResolver([
                scope,
                ...scopes
            ], prefixes, finalRootScopes, fallback)
    };
    return new Proxy(cache, {
        /**
     * A trap for the delete operator.
     */ deleteProperty (target, prop) {
            delete target[prop]; // remove from cache
            delete target._keys; // remove cached keys
            delete scopes[0][prop]; // remove from top level scope
            return true;
        },
        /**
     * A trap for getting property values.
     */ get (target, prop) {
            return _cached(target, prop, ()=>_resolveWithPrefixes(prop, prefixes, scopes, target));
        },
        /**
     * A trap for Object.getOwnPropertyDescriptor.
     * Also used by Object.hasOwnProperty.
     */ getOwnPropertyDescriptor (target, prop) {
            return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop);
        },
        /**
     * A trap for Object.getPrototypeOf.
     */ getPrototypeOf () {
            return Reflect.getPrototypeOf(scopes[0]);
        },
        /**
     * A trap for the in operator.
     */ has (target, prop) {
            return getKeysFromAllScopes(target).includes(prop);
        },
        /**
     * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.
     */ ownKeys (target) {
            return getKeysFromAllScopes(target);
        },
        /**
     * A trap for setting property values.
     */ set (target, prop, value) {
            const storage = target._storage || (target._storage = getTarget());
            target[prop] = storage[prop] = value; // set to top level scope + cache
            delete target._keys; // remove cached keys
            return true;
        }
    });
}
/**
 * Returns an Proxy for resolving option values with context.
 * @param proxy - The Proxy returned by `_createResolver`
 * @param context - Context object for scriptable/indexable options
 * @param subProxy - The proxy provided for scriptable options
 * @param descriptorDefaults - Defaults for descriptors
 * @private
 */ function _attachContext(proxy, context, subProxy, descriptorDefaults) {
    const cache = {
        _cacheable: false,
        _proxy: proxy,
        _context: context,
        _subProxy: subProxy,
        _stack: new Set(),
        _descriptors: _descriptors(proxy, descriptorDefaults),
        setContext: (ctx)=>_attachContext(proxy, ctx, subProxy, descriptorDefaults),
        override: (scope)=>_attachContext(proxy.override(scope), context, subProxy, descriptorDefaults)
    };
    return new Proxy(cache, {
        /**
     * A trap for the delete operator.
     */ deleteProperty (target, prop) {
            delete target[prop]; // remove from cache
            delete proxy[prop]; // remove from proxy
            return true;
        },
        /**
     * A trap for getting property values.
     */ get (target, prop, receiver) {
            return _cached(target, prop, ()=>_resolveWithContext(target, prop, receiver));
        },
        /**
     * A trap for Object.getOwnPropertyDescriptor.
     * Also used by Object.hasOwnProperty.
     */ getOwnPropertyDescriptor (target, prop) {
            return target._descriptors.allKeys ? Reflect.has(proxy, prop) ? {
                enumerable: true,
                configurable: true
            } : undefined : Reflect.getOwnPropertyDescriptor(proxy, prop);
        },
        /**
     * A trap for Object.getPrototypeOf.
     */ getPrototypeOf () {
            return Reflect.getPrototypeOf(proxy);
        },
        /**
     * A trap for the in operator.
     */ has (target, prop) {
            return Reflect.has(proxy, prop);
        },
        /**
     * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.
     */ ownKeys () {
            return Reflect.ownKeys(proxy);
        },
        /**
     * A trap for setting property values.
     */ set (target, prop, value) {
            proxy[prop] = value; // set to proxy
            delete target[prop]; // remove from cache
            return true;
        }
    });
}
/**
 * @private
 */ function _descriptors(proxy, defaults = {
    scriptable: true,
    indexable: true
}) {
    const { _scriptable =defaults.scriptable , _indexable =defaults.indexable , _allKeys =defaults.allKeys  } = proxy;
    return {
        allKeys: _allKeys,
        scriptable: _scriptable,
        indexable: _indexable,
        isScriptable: isFunction(_scriptable) ? _scriptable : ()=>_scriptable,
        isIndexable: isFunction(_indexable) ? _indexable : ()=>_indexable
    };
}
const readKey = (prefix, name)=>prefix ? prefix + _capitalize(name) : name;
const needsSubResolver = (prop, value)=>isObject(value) && prop !== 'adapters' && (Object.getPrototypeOf(value) === null || value.constructor === Object);
function _cached(target, prop, resolve) {
    if (Object.prototype.hasOwnProperty.call(target, prop) || prop === 'constructor') {
        return target[prop];
    }
    const value = resolve();
    // cache the resolved value
    target[prop] = value;
    return value;
}
function _resolveWithContext(target, prop, receiver) {
    const { _proxy , _context , _subProxy , _descriptors: descriptors  } = target;
    let value = _proxy[prop]; // resolve from proxy
    // resolve with context
    if (isFunction(value) && descriptors.isScriptable(prop)) {
        value = _resolveScriptable(prop, value, target, receiver);
    }
    if (isArray(value) && value.length) {
        value = _resolveArray(prop, value, target, descriptors.isIndexable);
    }
    if (needsSubResolver(prop, value)) {
        // if the resolved value is an object, create a sub resolver for it
        value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors);
    }
    return value;
}
function _resolveScriptable(prop, getValue, target, receiver) {
    const { _proxy , _context , _subProxy , _stack  } = target;
    if (_stack.has(prop)) {
        throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop);
    }
    _stack.add(prop);
    let value = getValue(_context, _subProxy || receiver);
    _stack.delete(prop);
    if (needsSubResolver(prop, value)) {
        // When scriptable option returns an object, create a resolver on that.
        value = createSubResolver(_proxy._scopes, _proxy, prop, value);
    }
    return value;
}
function _resolveArray(prop, value, target, isIndexable) {
    const { _proxy , _context , _subProxy , _descriptors: descriptors  } = target;
    if (typeof _context.index !== 'undefined' && isIndexable(prop)) {
        return value[_context.index % value.length];
    } else if (isObject(value[0])) {
        // Array of objects, return array or resolvers
        const arr = value;
        const scopes = _proxy._scopes.filter((s)=>s !== arr);
        value = [];
        for (const item of arr){
            const resolver = createSubResolver(scopes, _proxy, prop, item);
            value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors));
        }
    }
    return value;
}
function resolveFallback(fallback, prop, value) {
    return isFunction(fallback) ? fallback(prop, value) : fallback;
}
const getScope = (key, parent)=>key === true ? parent : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined;
function addScopes(set, parentScopes, key, parentFallback, value) {
    for (const parent of parentScopes){
        const scope = getScope(key, parent);
        if (scope) {
            set.add(scope);
            const fallback = resolveFallback(scope._fallback, key, value);
            if (typeof fallback !== 'undefined' && fallback !== key && fallback !== parentFallback) {
                // When we reach the descriptor that defines a new _fallback, return that.
                // The fallback will resume to that new scope.
                return fallback;
            }
        } else if (scope === false && typeof parentFallback !== 'undefined' && key !== parentFallback) {
            // Fallback to `false` results to `false`, when falling back to different key.
            // For example `interaction` from `hover` or `plugins.tooltip` and `animation` from `animations`
            return null;
        }
    }
    return false;
}
function createSubResolver(parentScopes, resolver, prop, value) {
    const rootScopes = resolver._rootScopes;
    const fallback = resolveFallback(resolver._fallback, prop, value);
    const allScopes = [
        ...parentScopes,
        ...rootScopes
    ];
    const set = new Set();
    set.add(value);
    let key = addScopesFromKey(set, allScopes, prop, fallback || prop, value);
    if (key === null) {
        return false;
    }
    if (typeof fallback !== 'undefined' && fallback !== prop) {
        key = addScopesFromKey(set, allScopes, fallback, key, value);
        if (key === null) {
            return false;
        }
    }
    return _createResolver(Array.from(set), [
        ''
    ], rootScopes, fallback, ()=>subGetTarget(resolver, prop, value));
}
function addScopesFromKey(set, allScopes, key, fallback, item) {
    while(key){
        key = addScopes(set, allScopes, key, fallback, item);
    }
    return key;
}
function subGetTarget(resolver, prop, value) {
    const parent = resolver._getTarget();
    if (!(prop in parent)) {
        parent[prop] = {};
    }
    const target = parent[prop];
    if (isArray(target) && isObject(value)) {
        // For array of objects, the object is used to store updated values
        return value;
    }
    return target || {};
}
function _resolveWithPrefixes(prop, prefixes, scopes, proxy) {
    let value;
    for (const prefix of prefixes){
        value = _resolve(readKey(prefix, prop), scopes);
        if (typeof value !== 'undefined') {
            return needsSubResolver(prop, value) ? createSubResolver(scopes, proxy, prop, value) : value;
        }
    }
}
function _resolve(key, scopes) {
    for (const scope of scopes){
        if (!scope) {
            continue;
        }
        const value = scope[key];
        if (typeof value !== 'undefined') {
            return value;
        }
    }
}
function getKeysFromAllScopes(target) {
    let keys = target._keys;
    if (!keys) {
        keys = target._keys = resolveKeysFromAllScopes(target._scopes);
    }
    return keys;
}
function resolveKeysFromAllScopes(scopes) {
    const set = new Set();
    for (const scope of scopes){
        for (const key of Object.keys(scope).filter((k)=>!k.startsWith('_'))){
            set.add(key);
        }
    }
    return Array.from(set);
}
function _parseObjectDataRadialScale(meta, data, start, count) {
    const { iScale  } = meta;
    const { key ='r'  } = this._parsing;
    const parsed = new Array(count);
    let i, ilen, index, item;
    for(i = 0, ilen = count; i < ilen; ++i){
        index = i + start;
        item = data[index];
        parsed[i] = {
            r: iScale.parse(resolveObjectKey(item, key), index)
        };
    }
    return parsed;
}

const EPSILON = Number.EPSILON || 1e-14;
const getPoint = (points, i)=>i < points.length && !points[i].skip && points[i];
const getValueAxis = (indexAxis)=>indexAxis === 'x' ? 'y' : 'x';
function splineCurve(firstPoint, middlePoint, afterPoint, t) {
    // Props to Rob Spencer at scaled innovation for his post on splining between points
    // http://scaledinnovation.com/analytics/splines/aboutSplines.html
    // This function must also respect "skipped" points
    const previous = firstPoint.skip ? middlePoint : firstPoint;
    const current = middlePoint;
    const next = afterPoint.skip ? middlePoint : afterPoint;
    const d01 = distanceBetweenPoints(current, previous);
    const d12 = distanceBetweenPoints(next, current);
    let s01 = d01 / (d01 + d12);
    let s12 = d12 / (d01 + d12);
    // If all points are the same, s01 & s02 will be inf
    s01 = isNaN(s01) ? 0 : s01;
    s12 = isNaN(s12) ? 0 : s12;
    const fa = t * s01; // scaling factor for triangle Ta
    const fb = t * s12;
    return {
        previous: {
            x: current.x - fa * (next.x - previous.x),
            y: current.y - fa * (next.y - previous.y)
        },
        next: {
            x: current.x + fb * (next.x - previous.x),
            y: current.y + fb * (next.y - previous.y)
        }
    };
}
/**
 * Adjust tangents to ensure monotonic properties
 */ function monotoneAdjust(points, deltaK, mK) {
    const pointsLen = points.length;
    let alphaK, betaK, tauK, squaredMagnitude, pointCurrent;
    let pointAfter = getPoint(points, 0);
    for(let i = 0; i < pointsLen - 1; ++i){
        pointCurrent = pointAfter;
        pointAfter = getPoint(points, i + 1);
        if (!pointCurrent || !pointAfter) {
            continue;
        }
        if (almostEquals(deltaK[i], 0, EPSILON)) {
            mK[i] = mK[i + 1] = 0;
            continue;
        }
        alphaK = mK[i] / deltaK[i];
        betaK = mK[i + 1] / deltaK[i];
        squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
        if (squaredMagnitude <= 9) {
            continue;
        }
        tauK = 3 / Math.sqrt(squaredMagnitude);
        mK[i] = alphaK * tauK * deltaK[i];
        mK[i + 1] = betaK * tauK * deltaK[i];
    }
}
function monotoneCompute(points, mK, indexAxis = 'x') {
    const valueAxis = getValueAxis(indexAxis);
    const pointsLen = points.length;
    let delta, pointBefore, pointCurrent;
    let pointAfter = getPoint(points, 0);
    for(let i = 0; i < pointsLen; ++i){
        pointBefore = pointCurrent;
        pointCurrent = pointAfter;
        pointAfter = getPoint(points, i + 1);
        if (!pointCurrent) {
            continue;
        }
        const iPixel = pointCurrent[indexAxis];
        const vPixel = pointCurrent[valueAxis];
        if (pointBefore) {
            delta = (iPixel - pointBefore[indexAxis]) / 3;
            pointCurrent[`cp1${indexAxis}`] = iPixel - delta;
            pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i];
        }
        if (pointAfter) {
            delta = (pointAfter[indexAxis] - iPixel) / 3;
            pointCurrent[`cp2${indexAxis}`] = iPixel + delta;
            pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i];
        }
    }
}
/**
 * This function calculates Bézier control points in a similar way than |splineCurve|,
 * but preserves monotonicity of the provided data and ensures no local extremums are added
 * between the dataset discrete points due to the interpolation.
 * See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
 */ function splineCurveMonotone(points, indexAxis = 'x') {
    const valueAxis = getValueAxis(indexAxis);
    const pointsLen = points.length;
    const deltaK = Array(pointsLen).fill(0);
    const mK = Array(pointsLen);
    // Calculate slopes (deltaK) and initialize tangents (mK)
    let i, pointBefore, pointCurrent;
    let pointAfter = getPoint(points, 0);
    for(i = 0; i < pointsLen; ++i){
        pointBefore = pointCurrent;
        pointCurrent = pointAfter;
        pointAfter = getPoint(points, i + 1);
        if (!pointCurrent) {
            continue;
        }
        if (pointAfter) {
            const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis];
            // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
            deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0;
        }
        mK[i] = !pointBefore ? deltaK[i] : !pointAfter ? deltaK[i - 1] : sign(deltaK[i - 1]) !== sign(deltaK[i]) ? 0 : (deltaK[i - 1] + deltaK[i]) / 2;
    }
    monotoneAdjust(points, deltaK, mK);
    monotoneCompute(points, mK, indexAxis);
}
function capControlPoint(pt, min, max) {
    return Math.max(Math.min(pt, max), min);
}
function capBezierPoints(points, area) {
    let i, ilen, point, inArea, inAreaPrev;
    let inAreaNext = _isPointInArea(points[0], area);
    for(i = 0, ilen = points.length; i < ilen; ++i){
        inAreaPrev = inArea;
        inArea = inAreaNext;
        inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area);
        if (!inArea) {
            continue;
        }
        point = points[i];
        if (inAreaPrev) {
            point.cp1x = capControlPoint(point.cp1x, area.left, area.right);
            point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);
        }
        if (inAreaNext) {
            point.cp2x = capControlPoint(point.cp2x, area.left, area.right);
            point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);
        }
    }
}
/**
 * @private
 */ function _updateBezierControlPoints(points, options, area, loop, indexAxis) {
    let i, ilen, point, controlPoints;
    // Only consider points that are drawn in case the spanGaps option is used
    if (options.spanGaps) {
        points = points.filter((pt)=>!pt.skip);
    }
    if (options.cubicInterpolationMode === 'monotone') {
        splineCurveMonotone(points, indexAxis);
    } else {
        let prev = loop ? points[points.length - 1] : points[0];
        for(i = 0, ilen = points.length; i < ilen; ++i){
            point = points[i];
            controlPoints = splineCurve(prev, point, points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen], options.tension);
            point.cp1x = controlPoints.previous.x;
            point.cp1y = controlPoints.previous.y;
            point.cp2x = controlPoints.next.x;
            point.cp2y = controlPoints.next.y;
            prev = point;
        }
    }
    if (options.capBezierPoints) {
        capBezierPoints(points, area);
    }
}

/**
 * @private
 */ function _isDomSupported() {
    return typeof window !== 'undefined' && typeof document !== 'undefined';
}
/**
 * @private
 */ function _getParentNode(domNode) {
    let parent = domNode.parentNode;
    if (parent && parent.toString() === '[object ShadowRoot]') {
        parent = parent.host;
    }
    return parent;
}
/**
 * convert max-width/max-height values that may be percentages into a number
 * @private
 */ function parseMaxStyle(styleValue, node, parentProperty) {
    let valueInPixels;
    if (typeof styleValue === 'string') {
        valueInPixels = parseInt(styleValue, 10);
        if (styleValue.indexOf('%') !== -1) {
            // percentage * size in dimension
            valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
        }
    } else {
        valueInPixels = styleValue;
    }
    return valueInPixels;
}
const getComputedStyle$2 = (element)=>element.ownerDocument.defaultView.getComputedStyle(element, null);
function getStyle(el, property) {
    return getComputedStyle$2(el).getPropertyValue(property);
}
const positions = [
    'top',
    'right',
    'bottom',
    'left'
];
function getPositionedStyle(styles, style, suffix) {
    const result = {};
    suffix = suffix ? '-' + suffix : '';
    for(let i = 0; i < 4; i++){
        const pos = positions[i];
        result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0;
    }
    result.width = result.left + result.right;
    result.height = result.top + result.bottom;
    return result;
}
const useOffsetPos = (x, y, target)=>(x > 0 || y > 0) && (!target || !target.shadowRoot);
/**
 * @param e
 * @param canvas
 * @returns Canvas position
 */ function getCanvasPosition(e, canvas) {
    const touches = e.touches;
    const source = touches && touches.length ? touches[0] : e;
    const { offsetX , offsetY  } = source;
    let box = false;
    let x, y;
    if (useOffsetPos(offsetX, offsetY, e.target)) {
        x = offsetX;
        y = offsetY;
    } else {
        const rect = canvas.getBoundingClientRect();
        x = source.clientX - rect.left;
        y = source.clientY - rect.top;
        box = true;
    }
    return {
        x,
        y,
        box
    };
}
/**
 * Gets an event's x, y coordinates, relative to the chart area
 * @param event
 * @param chart
 * @returns x and y coordinates of the event
 */ function getRelativePosition(event, chart) {
    if ('native' in event) {
        return event;
    }
    const { canvas , currentDevicePixelRatio  } = chart;
    const style = getComputedStyle$2(canvas);
    const borderBox = style.boxSizing === 'border-box';
    const paddings = getPositionedStyle(style, 'padding');
    const borders = getPositionedStyle(style, 'border', 'width');
    const { x , y , box  } = getCanvasPosition(event, canvas);
    const xOffset = paddings.left + (box && borders.left);
    const yOffset = paddings.top + (box && borders.top);
    let { width , height  } = chart;
    if (borderBox) {
        width -= paddings.width + borders.width;
        height -= paddings.height + borders.height;
    }
    return {
        x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio),
        y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio)
    };
}
function getContainerSize(canvas, width, height) {
    let maxWidth, maxHeight;
    if (width === undefined || height === undefined) {
        const container = canvas && _getParentNode(canvas);
        if (!container) {
            width = canvas.clientWidth;
            height = canvas.clientHeight;
        } else {
            const rect = container.getBoundingClientRect(); // this is the border box of the container
            const containerStyle = getComputedStyle$2(container);
            const containerBorder = getPositionedStyle(containerStyle, 'border', 'width');
            const containerPadding = getPositionedStyle(containerStyle, 'padding');
            width = rect.width - containerPadding.width - containerBorder.width;
            height = rect.height - containerPadding.height - containerBorder.height;
            maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth');
            maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight');
        }
    }
    return {
        width,
        height,
        maxWidth: maxWidth || INFINITY,
        maxHeight: maxHeight || INFINITY
    };
}
const round1 = (v)=>Math.round(v * 10) / 10;
// eslint-disable-next-line complexity
function getMaximumSize(canvas, bbWidth, bbHeight, aspectRatio) {
    const style = getComputedStyle$2(canvas);
    const margins = getPositionedStyle(style, 'margin');
    const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY;
    const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY;
    const containerSize = getContainerSize(canvas, bbWidth, bbHeight);
    let { width , height  } = containerSize;
    if (style.boxSizing === 'content-box') {
        const borders = getPositionedStyle(style, 'border', 'width');
        const paddings = getPositionedStyle(style, 'padding');
        width -= paddings.width + borders.width;
        height -= paddings.height + borders.height;
    }
    width = Math.max(0, width - margins.width);
    height = Math.max(0, aspectRatio ? width / aspectRatio : height - margins.height);
    width = round1(Math.min(width, maxWidth, containerSize.maxWidth));
    height = round1(Math.min(height, maxHeight, containerSize.maxHeight));
    if (width && !height) {
        // https://github.com/chartjs/Chart.js/issues/4659
        // If the canvas has width, but no height, default to aspectRatio of 2 (canvas default)
        height = round1(width / 2);
    }
    const maintainHeight = bbWidth !== undefined || bbHeight !== undefined;
    if (maintainHeight && aspectRatio && containerSize.height && height > containerSize.height) {
        height = containerSize.height;
        width = round1(Math.floor(height * aspectRatio));
    }
    return {
        width,
        height
    };
}
/**
 * @param chart
 * @param forceRatio
 * @param forceStyle
 * @returns True if the canvas context size or transformation has changed.
 */ function retinaScale(chart, forceRatio, forceStyle) {
    const pixelRatio = forceRatio || 1;
    const deviceHeight = round1(chart.height * pixelRatio);
    const deviceWidth = round1(chart.width * pixelRatio);
    chart.height = round1(chart.height);
    chart.width = round1(chart.width);
    const canvas = chart.canvas;
    // If no style has been set on the canvas, the render size is used as display size,
    // making the chart visually bigger, so let's enforce it to the "correct" values.
    // See https://github.com/chartjs/Chart.js/issues/3575
    if (canvas.style && (forceStyle || !canvas.style.height && !canvas.style.width)) {
        canvas.style.height = `${chart.height}px`;
        canvas.style.width = `${chart.width}px`;
    }
    if (chart.currentDevicePixelRatio !== pixelRatio || canvas.height !== deviceHeight || canvas.width !== deviceWidth) {
        chart.currentDevicePixelRatio = pixelRatio;
        canvas.height = deviceHeight;
        canvas.width = deviceWidth;
        chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
        return true;
    }
    return false;
}
/**
 * Detects support for options object argument in addEventListener.
 * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
 * @private
 */ const supportsEventListenerOptions = function() {
    let passiveSupported = false;
    try {
        const options = {
            get passive () {
                passiveSupported = true;
                return false;
            }
        };
        if (_isDomSupported()) {
            window.addEventListener('test', null, options);
            window.removeEventListener('test', null, options);
        }
    } catch (e) {
    // continue regardless of error
    }
    return passiveSupported;
}();
/**
 * The "used" size is the final value of a dimension property after all calculations have
 * been performed. This method uses the computed style of `element` but returns undefined
 * if the computed style is not expressed in pixels. That can happen in some cases where
 * `element` has a size relative to its parent and this last one is not yet displayed,
 * for example because of `display: none` on a parent node.
 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
 * @returns Size in pixels or undefined if unknown.
 */ function readUsedSize(element, property) {
    const value = getStyle(element, property);
    const matches = value && value.match(/^(\d+)(\.\d+)?px$/);
    return matches ? +matches[1] : undefined;
}

/**
 * @private
 */ function _pointInLine(p1, p2, t, mode) {
    return {
        x: p1.x + t * (p2.x - p1.x),
        y: p1.y + t * (p2.y - p1.y)
    };
}
/**
 * @private
 */ function _steppedInterpolation(p1, p2, t, mode) {
    return {
        x: p1.x + t * (p2.x - p1.x),
        y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y : mode === 'after' ? t < 1 ? p1.y : p2.y : t > 0 ? p2.y : p1.y
    };
}
/**
 * @private
 */ function _bezierInterpolation(p1, p2, t, mode) {
    const cp1 = {
        x: p1.cp2x,
        y: p1.cp2y
    };
    const cp2 = {
        x: p2.cp1x,
        y: p2.cp1y
    };
    const a = _pointInLine(p1, cp1, t);
    const b = _pointInLine(cp1, cp2, t);
    const c = _pointInLine(cp2, p2, t);
    const d = _pointInLine(a, b, t);
    const e = _pointInLine(b, c, t);
    return _pointInLine(d, e, t);
}

const getRightToLeftAdapter = function(rectX, width) {
    return {
        x (x) {
            return rectX + rectX + width - x;
        },
        setWidth (w) {
            width = w;
        },
        textAlign (align) {
            if (align === 'center') {
                return align;
            }
            return align === 'right' ? 'left' : 'right';
        },
        xPlus (x, value) {
            return x - value;
        },
        leftForLtr (x, itemWidth) {
            return x - itemWidth;
        }
    };
};
const getLeftToRightAdapter = function() {
    return {
        x (x) {
            return x;
        },
        setWidth (w) {},
        textAlign (align) {
            return align;
        },
        xPlus (x, value) {
            return x + value;
        },
        leftForLtr (x, _itemWidth) {
            return x;
        }
    };
};
function getRtlAdapter(rtl, rectX, width) {
    return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter();
}
function overrideTextDirection(ctx, direction) {
    let style, original;
    if (direction === 'ltr' || direction === 'rtl') {
        style = ctx.canvas.style;
        original = [
            style.getPropertyValue('direction'),
            style.getPropertyPriority('direction')
        ];
        style.setProperty('direction', direction, 'important');
        ctx.prevTextDirection = original;
    }
}
function restoreTextDirection(ctx, original) {
    if (original !== undefined) {
        delete ctx.prevTextDirection;
        ctx.canvas.style.setProperty('direction', original[0], original[1]);
    }
}

function propertyFn(property) {
    if (property === 'angle') {
        return {
            between: _angleBetween,
            compare: _angleDiff,
            normalize: _normalizeAngle
        };
    }
    return {
        between: _isBetween,
        compare: (a, b)=>a - b,
        normalize: (x)=>x
    };
}
function normalizeSegment({ start , end , count , loop , style  }) {
    return {
        start: start % count,
        end: end % count,
        loop: loop && (end - start + 1) % count === 0,
        style
    };
}
function getSegment(segment, points, bounds) {
    const { property , start: startBound , end: endBound  } = bounds;
    const { between , normalize  } = propertyFn(property);
    const count = points.length;
    let { start , end , loop  } = segment;
    let i, ilen;
    if (loop) {
        start += count;
        end += count;
        for(i = 0, ilen = count; i < ilen; ++i){
            if (!between(normalize(points[start % count][property]), startBound, endBound)) {
                break;
            }
            start--;
            end--;
        }
        start %= count;
        end %= count;
    }
    if (end < start) {
        end += count;
    }
    return {
        start,
        end,
        loop,
        style: segment.style
    };
}
 function _boundSegment(segment, points, bounds) {
    if (!bounds) {
        return [
            segment
        ];
    }
    const { property , start: startBound , end: endBound  } = bounds;
    const count = points.length;
    const { compare , between , normalize  } = propertyFn(property);
    const { start , end , loop , style  } = getSegment(segment, points, bounds);
    const result = [];
    let inside = false;
    let subStart = null;
    let value, point, prevValue;
    const startIsBefore = ()=>between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0;
    const endIsBefore = ()=>compare(endBound, value) === 0 || between(endBound, prevValue, value);
    const shouldStart = ()=>inside || startIsBefore();
    const shouldStop = ()=>!inside || endIsBefore();
    for(let i = start, prev = start; i <= end; ++i){
        point = points[i % count];
        if (point.skip) {
            continue;
        }
        value = normalize(point[property]);
        if (value === prevValue) {
            continue;
        }
        inside = between(value, startBound, endBound);
        if (subStart === null && shouldStart()) {
            subStart = compare(value, startBound) === 0 ? i : prev;
        }
        if (subStart !== null && shouldStop()) {
            result.push(normalizeSegment({
                start: subStart,
                end: i,
                loop,
                count,
                style
            }));
            subStart = null;
        }
        prev = i;
        prevValue = value;
    }
    if (subStart !== null) {
        result.push(normalizeSegment({
            start: subStart,
            end,
            loop,
            count,
            style
        }));
    }
    return result;
}
 function _boundSegments(line, bounds) {
    const result = [];
    const segments = line.segments;
    for(let i = 0; i < segments.length; i++){
        const sub = _boundSegment(segments[i], line.points, bounds);
        if (sub.length) {
            result.push(...sub);
        }
    }
    return result;
}
 function findStartAndEnd(points, count, loop, spanGaps) {
    let start = 0;
    let end = count - 1;
    if (loop && !spanGaps) {
        while(start < count && !points[start].skip){
            start++;
        }
    }
    while(start < count && points[start].skip){
        start++;
    }
    start %= count;
    if (loop) {
        end += start;
    }
    while(end > start && points[end % count].skip){
        end--;
    }
    end %= count;
    return {
        start,
        end
    };
}
 function solidSegments(points, start, max, loop) {
    const count = points.length;
    const result = [];
    let last = start;
    let prev = points[start];
    let end;
    for(end = start + 1; end <= max; ++end){
        const cur = points[end % count];
        if (cur.skip || cur.stop) {
            if (!prev.skip) {
                loop = false;
                result.push({
                    start: start % count,
                    end: (end - 1) % count,
                    loop
                });
                start = last = cur.stop ? end : null;
            }
        } else {
            last = end;
            if (prev.skip) {
                start = end;
            }
        }
        prev = cur;
    }
    if (last !== null) {
        result.push({
            start: start % count,
            end: last % count,
            loop
        });
    }
    return result;
}
 function _computeSegments(line, segmentOptions) {
    const points = line.points;
    const spanGaps = line.options.spanGaps;
    const count = points.length;
    if (!count) {
        return [];
    }
    const loop = !!line._loop;
    const { start , end  } = findStartAndEnd(points, count, loop, spanGaps);
    if (spanGaps === true) {
        return splitByStyles(line, [
            {
                start,
                end,
                loop
            }
        ], points, segmentOptions);
    }
    const max = end < start ? end + count : end;
    const completeLoop = !!line._fullLoop && start === 0 && end === count - 1;
    return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions);
}
 function splitByStyles(line, segments, points, segmentOptions) {
    if (!segmentOptions || !segmentOptions.setContext || !points) {
        return segments;
    }
    return doSplitByStyles(line, segments, points, segmentOptions);
}
 function doSplitByStyles(line, segments, points, segmentOptions) {
    const chartContext = line._chart.getContext();
    const baseStyle = readStyle(line.options);
    const { _datasetIndex: datasetIndex , options: { spanGaps  }  } = line;
    const count = points.length;
    const result = [];
    let prevStyle = baseStyle;
    let start = segments[0].start;
    let i = start;
    function addStyle(s, e, l, st) {
        const dir = spanGaps ? -1 : 1;
        if (s === e) {
            return;
        }
        s += count;
        while(points[s % count].skip){
            s -= dir;
        }
        while(points[e % count].skip){
            e += dir;
        }
        if (s % count !== e % count) {
            result.push({
                start: s % count,
                end: e % count,
                loop: l,
                style: st
            });
            prevStyle = st;
            start = e % count;
        }
    }
    for (const segment of segments){
        start = spanGaps ? start : segment.start;
        let prev = points[start % count];
        let style;
        for(i = start + 1; i <= segment.end; i++){
            const pt = points[i % count];
            style = readStyle(segmentOptions.setContext(createContext(chartContext, {
                type: 'segment',
                p0: prev,
                p1: pt,
                p0DataIndex: (i - 1) % count,
                p1DataIndex: i % count,
                datasetIndex
            })));
            if (styleChanged(style, prevStyle)) {
                addStyle(start, i - 1, segment.loop, prevStyle);
            }
            prev = pt;
            prevStyle = style;
        }
        if (start < i - 1) {
            addStyle(start, i - 1, segment.loop, prevStyle);
        }
    }
    return result;
}
function readStyle(options) {
    return {
        backgroundColor: options.backgroundColor,
        borderCapStyle: options.borderCapStyle,
        borderDash: options.borderDash,
        borderDashOffset: options.borderDashOffset,
        borderJoinStyle: options.borderJoinStyle,
        borderWidth: options.borderWidth,
        borderColor: options.borderColor
    };
}
function styleChanged(style, prevStyle) {
    if (!prevStyle) {
        return false;
    }
    const cache = [];
    const replacer = function(key, value) {
        if (!isPatternOrGradient(value)) {
            return value;
        }
        if (!cache.includes(value)) {
            cache.push(value);
        }
        return cache.indexOf(value);
    };
    return JSON.stringify(style, replacer) !== JSON.stringify(prevStyle, replacer);
}

function getSizeForArea(scale, chartArea, field) {
    return scale.options.clip ? scale[field] : chartArea[field];
}
function getDatasetArea(meta, chartArea) {
    const { xScale , yScale  } = meta;
    if (xScale && yScale) {
        return {
            left: getSizeForArea(xScale, chartArea, 'left'),
            right: getSizeForArea(xScale, chartArea, 'right'),
            top: getSizeForArea(yScale, chartArea, 'top'),
            bottom: getSizeForArea(yScale, chartArea, 'bottom')
        };
    }
    return chartArea;
}
function getDatasetClipArea(chart, meta) {
    const clip = meta._clip;
    if (clip.disabled) {
        return false;
    }
    const area = getDatasetArea(meta, chart.chartArea);
    return {
        left: clip.left === false ? 0 : area.left - (clip.left === true ? 0 : clip.left),
        right: clip.right === false ? chart.width : area.right + (clip.right === true ? 0 : clip.right),
        top: clip.top === false ? 0 : area.top - (clip.top === true ? 0 : clip.top),
        bottom: clip.bottom === false ? chart.height : area.bottom + (clip.bottom === true ? 0 : clip.bottom)
    };
}

/*!
 * Chart.js v4.5.1
 * https://www.chartjs.org
 * (c) 2025 Chart.js Contributors
 * Released under the MIT License
 */

class Animator {
    constructor(){
        this._request = null;
        this._charts = new Map();
        this._running = false;
        this._lastDate = undefined;
    }
 _notify(chart, anims, date, type) {
        const callbacks = anims.listeners[type];
        const numSteps = anims.duration;
        callbacks.forEach((fn)=>fn({
                chart,
                initial: anims.initial,
                numSteps,
                currentStep: Math.min(date - anims.start, numSteps)
            }));
    }
 _refresh() {
        if (this._request) {
            return;
        }
        this._running = true;
        this._request = requestAnimFrame.call(window, ()=>{
            this._update();
            this._request = null;
            if (this._running) {
                this._refresh();
            }
        });
    }
 _update(date = Date.now()) {
        let remaining = 0;
        this._charts.forEach((anims, chart)=>{
            if (!anims.running || !anims.items.length) {
                return;
            }
            const items = anims.items;
            let i = items.length - 1;
            let draw = false;
            let item;
            for(; i >= 0; --i){
                item = items[i];
                if (item._active) {
                    if (item._total > anims.duration) {
                        anims.duration = item._total;
                    }
                    item.tick(date);
                    draw = true;
                } else {
                    items[i] = items[items.length - 1];
                    items.pop();
                }
            }
            if (draw) {
                chart.draw();
                this._notify(chart, anims, date, 'progress');
            }
            if (!items.length) {
                anims.running = false;
                this._notify(chart, anims, date, 'complete');
                anims.initial = false;
            }
            remaining += items.length;
        });
        this._lastDate = date;
        if (remaining === 0) {
            this._running = false;
        }
    }
 _getAnims(chart) {
        const charts = this._charts;
        let anims = charts.get(chart);
        if (!anims) {
            anims = {
                running: false,
                initial: true,
                items: [],
                listeners: {
                    complete: [],
                    progress: []
                }
            };
            charts.set(chart, anims);
        }
        return anims;
    }
 listen(chart, event, cb) {
        this._getAnims(chart).listeners[event].push(cb);
    }
 add(chart, items) {
        if (!items || !items.length) {
            return;
        }
        this._getAnims(chart).items.push(...items);
    }
 has(chart) {
        return this._getAnims(chart).items.length > 0;
    }
 start(chart) {
        const anims = this._charts.get(chart);
        if (!anims) {
            return;
        }
        anims.running = true;
        anims.start = Date.now();
        anims.duration = anims.items.reduce((acc, cur)=>Math.max(acc, cur._duration), 0);
        this._refresh();
    }
    running(chart) {
        if (!this._running) {
            return false;
        }
        const anims = this._charts.get(chart);
        if (!anims || !anims.running || !anims.items.length) {
            return false;
        }
        return true;
    }
 stop(chart) {
        const anims = this._charts.get(chart);
        if (!anims || !anims.items.length) {
            return;
        }
        const items = anims.items;
        let i = items.length - 1;
        for(; i >= 0; --i){
            items[i].cancel();
        }
        anims.items = [];
        this._notify(chart, anims, Date.now(), 'complete');
    }
 remove(chart) {
        return this._charts.delete(chart);
    }
}
var animator = /* #__PURE__ */ new Animator();

const transparent = 'transparent';
const interpolators = {
    boolean (from, to, factor) {
        return factor > 0.5 ? to : from;
    },
 color (from, to, factor) {
        const c0 = color(from || transparent);
        const c1 = c0.valid && color(to || transparent);
        return c1 && c1.valid ? c1.mix(c0, factor).hexString() : to;
    },
    number (from, to, factor) {
        return from + (to - from) * factor;
    }
};
class Animation {
    constructor(cfg, target, prop, to){
        const currentValue = target[prop];
        to = resolve([
            cfg.to,
            to,
            currentValue,
            cfg.from
        ]);
        const from = resolve([
            cfg.from,
            currentValue,
            to
        ]);
        this._active = true;
        this._fn = cfg.fn || interpolators[cfg.type || typeof from];
        this._easing = effects[cfg.easing] || effects.linear;
        this._start = Math.floor(Date.now() + (cfg.delay || 0));
        this._duration = this._total = Math.floor(cfg.duration);
        this._loop = !!cfg.loop;
        this._target = target;
        this._prop = prop;
        this._from = from;
        this._to = to;
        this._promises = undefined;
    }
    active() {
        return this._active;
    }
    update(cfg, to, date) {
        if (this._active) {
            this._notify(false);
            const currentValue = this._target[this._prop];
            const elapsed = date - this._start;
            const remain = this._duration - elapsed;
            this._start = date;
            this._duration = Math.floor(Math.max(remain, cfg.duration));
            this._total += elapsed;
            this._loop = !!cfg.loop;
            this._to = resolve([
                cfg.to,
                to,
                currentValue,
                cfg.from
            ]);
            this._from = resolve([
                cfg.from,
                currentValue,
                to
            ]);
        }
    }
    cancel() {
        if (this._active) {
            this.tick(Date.now());
            this._active = false;
            this._notify(false);
        }
    }
    tick(date) {
        const elapsed = date - this._start;
        const duration = this._duration;
        const prop = this._prop;
        const from = this._from;
        const loop = this._loop;
        const to = this._to;
        let factor;
        this._active = from !== to && (loop || elapsed < duration);
        if (!this._active) {
            this._target[prop] = to;
            this._notify(true);
            return;
        }
        if (elapsed < 0) {
            this._target[prop] = from;
            return;
        }
        factor = elapsed / duration % 2;
        factor = loop && factor > 1 ? 2 - factor : factor;
        factor = this._easing(Math.min(1, Math.max(0, factor)));
        this._target[prop] = this._fn(from, to, factor);
    }
    wait() {
        const promises = this._promises || (this._promises = []);
        return new Promise((res, rej)=>{
            promises.push({
                res,
                rej
            });
        });
    }
    _notify(resolved) {
        const method = resolved ? 'res' : 'rej';
        const promises = this._promises || [];
        for(let i = 0; i < promises.length; i++){
            promises[i][method]();
        }
    }
}

class Animations {
    constructor(chart, config){
        this._chart = chart;
        this._properties = new Map();
        this.configure(config);
    }
    configure(config) {
        if (!isObject(config)) {
            return;
        }
        const animationOptions = Object.keys(defaults.animation);
        const animatedProps = this._properties;
        Object.getOwnPropertyNames(config).forEach((key)=>{
            const cfg = config[key];
            if (!isObject(cfg)) {
                return;
            }
            const resolved = {};
            for (const option of animationOptions){
                resolved[option] = cfg[option];
            }
            (isArray(cfg.properties) && cfg.properties || [
                key
            ]).forEach((prop)=>{
                if (prop === key || !animatedProps.has(prop)) {
                    animatedProps.set(prop, resolved);
                }
            });
        });
    }
 _animateOptions(target, values) {
        const newOptions = values.options;
        const options = resolveTargetOptions(target, newOptions);
        if (!options) {
            return [];
        }
        const animations = this._createAnimations(options, newOptions);
        if (newOptions.$shared) {
            awaitAll(target.options.$animations, newOptions).then(()=>{
                target.options = newOptions;
            }, ()=>{
            });
        }
        return animations;
    }
 _createAnimations(target, values) {
        const animatedProps = this._properties;
        const animations = [];
        const running = target.$animations || (target.$animations = {});
        const props = Object.keys(values);
        const date = Date.now();
        let i;
        for(i = props.length - 1; i >= 0; --i){
            const prop = props[i];
            if (prop.charAt(0) === '$') {
                continue;
            }
            if (prop === 'options') {
                animations.push(...this._animateOptions(target, values));
                continue;
            }
            const value = values[prop];
            let animation = running[prop];
            const cfg = animatedProps.get(prop);
            if (animation) {
                if (cfg && animation.active()) {
                    animation.update(cfg, value, date);
                    continue;
                } else {
                    animation.cancel();
                }
            }
            if (!cfg || !cfg.duration) {
                target[prop] = value;
                continue;
            }
            running[prop] = animation = new Animation(cfg, target, prop, value);
            animations.push(animation);
        }
        return animations;
    }
 update(target, values) {
        if (this._properties.size === 0) {
            Object.assign(target, values);
            return;
        }
        const animations = this._createAnimations(target, values);
        if (animations.length) {
            animator.add(this._chart, animations);
            return true;
        }
    }
}
function awaitAll(animations, properties) {
    const running = [];
    const keys = Object.keys(properties);
    for(let i = 0; i < keys.length; i++){
        const anim = animations[keys[i]];
        if (anim && anim.active()) {
            running.push(anim.wait());
        }
    }
    return Promise.all(running);
}
function resolveTargetOptions(target, newOptions) {
    if (!newOptions) {
        return;
    }
    let options = target.options;
    if (!options) {
        target.options = newOptions;
        return;
    }
    if (options.$shared) {
        target.options = options = Object.assign({}, options, {
            $shared: false,
            $animations: {}
        });
    }
    return options;
}

function scaleClip(scale, allowedOverflow) {
    const opts = scale && scale.options || {};
    const reverse = opts.reverse;
    const min = opts.min === undefined ? allowedOverflow : 0;
    const max = opts.max === undefined ? allowedOverflow : 0;
    return {
        start: reverse ? max : min,
        end: reverse ? min : max
    };
}
function defaultClip(xScale, yScale, allowedOverflow) {
    if (allowedOverflow === false) {
        return false;
    }
    const x = scaleClip(xScale, allowedOverflow);
    const y = scaleClip(yScale, allowedOverflow);
    return {
        top: y.end,
        right: x.end,
        bottom: y.start,
        left: x.start
    };
}
function toClip(value) {
    let t, r, b, l;
    if (isObject(value)) {
        t = value.top;
        r = value.right;
        b = value.bottom;
        l = value.left;
    } else {
        t = r = b = l = value;
    }
    return {
        top: t,
        right: r,
        bottom: b,
        left: l,
        disabled: value === false
    };
}
function getSortedDatasetIndices(chart, filterVisible) {
    const keys = [];
    const metasets = chart._getSortedDatasetMetas(filterVisible);
    let i, ilen;
    for(i = 0, ilen = metasets.length; i < ilen; ++i){
        keys.push(metasets[i].index);
    }
    return keys;
}
function applyStack(stack, value, dsIndex, options = {}) {
    const keys = stack.keys;
    const singleMode = options.mode === 'single';
    let i, ilen, datasetIndex, otherValue;
    if (value === null) {
        return;
    }
    let found = false;
    for(i = 0, ilen = keys.length; i < ilen; ++i){
        datasetIndex = +keys[i];
        if (datasetIndex === dsIndex) {
            found = true;
            if (options.all) {
                continue;
            }
            break;
        }
        otherValue = stack.values[datasetIndex];
        if (isNumberFinite(otherValue) && (singleMode || value === 0 || sign(value) === sign(otherValue))) {
            value += otherValue;
        }
    }
    if (!found && !options.all) {
        return 0;
    }
    return value;
}
function convertObjectDataToArray(data, meta) {
    const { iScale , vScale  } = meta;
    const iAxisKey = iScale.axis === 'x' ? 'x' : 'y';
    const vAxisKey = vScale.axis === 'x' ? 'x' : 'y';
    const keys = Object.keys(data);
    const adata = new Array(keys.length);
    let i, ilen, key;
    for(i = 0, ilen = keys.length; i < ilen; ++i){
        key = keys[i];
        adata[i] = {
            [iAxisKey]: key,
            [vAxisKey]: data[key]
        };
    }
    return adata;
}
function isStacked(scale, meta) {
    const stacked = scale && scale.options.stacked;
    return stacked || stacked === undefined && meta.stack !== undefined;
}
function getStackKey(indexScale, valueScale, meta) {
    return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;
}
function getUserBounds(scale) {
    const { min , max , minDefined , maxDefined  } = scale.getUserBounds();
    return {
        min: minDefined ? min : Number.NEGATIVE_INFINITY,
        max: maxDefined ? max : Number.POSITIVE_INFINITY
    };
}
function getOrCreateStack(stacks, stackKey, indexValue) {
    const subStack = stacks[stackKey] || (stacks[stackKey] = {});
    return subStack[indexValue] || (subStack[indexValue] = {});
}
function getLastIndexInStack(stack, vScale, positive, type) {
    for (const meta of vScale.getMatchingVisibleMetas(type).reverse()){
        const value = stack[meta.index];
        if (positive && value > 0 || !positive && value < 0) {
            return meta.index;
        }
    }
    return null;
}
function updateStacks(controller, parsed) {
    const { chart , _cachedMeta: meta  } = controller;
    const stacks = chart._stacks || (chart._stacks = {});
    const { iScale , vScale , index: datasetIndex  } = meta;
    const iAxis = iScale.axis;
    const vAxis = vScale.axis;
    const key = getStackKey(iScale, vScale, meta);
    const ilen = parsed.length;
    let stack;
    for(let i = 0; i < ilen; ++i){
        const item = parsed[i];
        const { [iAxis]: index , [vAxis]: value  } = item;
        const itemStacks = item._stacks || (item._stacks = {});
        stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);
        stack[datasetIndex] = value;
        stack._top = getLastIndexInStack(stack, vScale, true, meta.type);
        stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);
        const visualValues = stack._visualValues || (stack._visualValues = {});
        visualValues[datasetIndex] = value;
    }
}
function getFirstScaleId(chart, axis) {
    const scales = chart.scales;
    return Object.keys(scales).filter((key)=>scales[key].axis === axis).shift();
}
function createDatasetContext(parent, index) {
    return createContext(parent, {
        active: false,
        dataset: undefined,
        datasetIndex: index,
        index,
        mode: 'default',
        type: 'dataset'
    });
}
function createDataContext(parent, index, element) {
    return createContext(parent, {
        active: false,
        dataIndex: index,
        parsed: undefined,
        raw: undefined,
        element,
        index,
        mode: 'default',
        type: 'data'
    });
}
function clearStacks(meta, items) {
    const datasetIndex = meta.controller.index;
    const axis = meta.vScale && meta.vScale.axis;
    if (!axis) {
        return;
    }
    items = items || meta._parsed;
    for (const parsed of items){
        const stacks = parsed._stacks;
        if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {
            return;
        }
        delete stacks[axis][datasetIndex];
        if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) {
            delete stacks[axis]._visualValues[datasetIndex];
        }
    }
}
const isDirectUpdateMode = (mode)=>mode === 'reset' || mode === 'none';
const cloneIfNotShared = (cached, shared)=>shared ? cached : Object.assign({}, cached);
const createStack = (canStack, meta, chart)=>canStack && !meta.hidden && meta._stacked && {
        keys: getSortedDatasetIndices(chart, true),
        values: null
    };
class DatasetController {
 static defaults = {};
 static datasetElementType = null;
 static dataElementType = null;
 constructor(chart, datasetIndex){
        this.chart = chart;
        this._ctx = chart.ctx;
        this.index = datasetIndex;
        this._cachedDataOpts = {};
        this._cachedMeta = this.getMeta();
        this._type = this._cachedMeta.type;
        this.options = undefined;
         this._parsing = false;
        this._data = undefined;
        this._objectData = undefined;
        this._sharedOptions = undefined;
        this._drawStart = undefined;
        this._drawCount = undefined;
        this.enableOptionSharing = false;
        this.supportsDecimation = false;
        this.$context = undefined;
        this._syncList = [];
        this.datasetElementType = new.target.datasetElementType;
        this.dataElementType = new.target.dataElementType;
        this.initialize();
    }
    initialize() {
        const meta = this._cachedMeta;
        this.configure();
        this.linkScales();
        meta._stacked = isStacked(meta.vScale, meta);
        this.addElements();
        if (this.options.fill && !this.chart.isPluginEnabled('filler')) {
            console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options");
        }
    }
    updateIndex(datasetIndex) {
        if (this.index !== datasetIndex) {
            clearStacks(this._cachedMeta);
        }
        this.index = datasetIndex;
    }
    linkScales() {
        const chart = this.chart;
        const meta = this._cachedMeta;
        const dataset = this.getDataset();
        const chooseId = (axis, x, y, r)=>axis === 'x' ? x : axis === 'r' ? r : y;
        const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));
        const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));
        const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));
        const indexAxis = meta.indexAxis;
        const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);
        const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);
        meta.xScale = this.getScaleForId(xid);
        meta.yScale = this.getScaleForId(yid);
        meta.rScale = this.getScaleForId(rid);
        meta.iScale = this.getScaleForId(iid);
        meta.vScale = this.getScaleForId(vid);
    }
    getDataset() {
        return this.chart.data.datasets[this.index];
    }
    getMeta() {
        return this.chart.getDatasetMeta(this.index);
    }
 getScaleForId(scaleID) {
        return this.chart.scales[scaleID];
    }
 _getOtherScale(scale) {
        const meta = this._cachedMeta;
        return scale === meta.iScale ? meta.vScale : meta.iScale;
    }
    reset() {
        this._update('reset');
    }
 _destroy() {
        const meta = this._cachedMeta;
        if (this._data) {
            unlistenArrayEvents(this._data, this);
        }
        if (meta._stacked) {
            clearStacks(meta);
        }
    }
 _dataCheck() {
        const dataset = this.getDataset();
        const data = dataset.data || (dataset.data = []);
        const _data = this._data;
        if (isObject(data)) {
            const meta = this._cachedMeta;
            this._data = convertObjectDataToArray(data, meta);
        } else if (_data !== data) {
            if (_data) {
                unlistenArrayEvents(_data, this);
                const meta = this._cachedMeta;
                clearStacks(meta);
                meta._parsed = [];
            }
            if (data && Object.isExtensible(data)) {
                listenArrayEvents(data, this);
            }
            this._syncList = [];
            this._data = data;
        }
    }
    addElements() {
        const meta = this._cachedMeta;
        this._dataCheck();
        if (this.datasetElementType) {
            meta.dataset = new this.datasetElementType();
        }
    }
    buildOrUpdateElements(resetNewElements) {
        const meta = this._cachedMeta;
        const dataset = this.getDataset();
        let stackChanged = false;
        this._dataCheck();
        const oldStacked = meta._stacked;
        meta._stacked = isStacked(meta.vScale, meta);
        if (meta.stack !== dataset.stack) {
            stackChanged = true;
            clearStacks(meta);
            meta.stack = dataset.stack;
        }
        this._resyncElements(resetNewElements);
        if (stackChanged || oldStacked !== meta._stacked) {
            updateStacks(this, meta._parsed);
            meta._stacked = isStacked(meta.vScale, meta);
        }
    }
 configure() {
        const config = this.chart.config;
        const scopeKeys = config.datasetScopeKeys(this._type);
        const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);
        this.options = config.createResolver(scopes, this.getContext());
        this._parsing = this.options.parsing;
        this._cachedDataOpts = {};
    }
 parse(start, count) {
        const { _cachedMeta: meta , _data: data  } = this;
        const { iScale , _stacked  } = meta;
        const iAxis = iScale.axis;
        let sorted = start === 0 && count === data.length ? true : meta._sorted;
        let prev = start > 0 && meta._parsed[start - 1];
        let i, cur, parsed;
        if (this._parsing === false) {
            meta._parsed = data;
            meta._sorted = true;
            parsed = data;
        } else {
            if (isArray(data[start])) {
                parsed = this.parseArrayData(meta, data, start, count);
            } else if (isObject(data[start])) {
                parsed = this.parseObjectData(meta, data, start, count);
            } else {
                parsed = this.parsePrimitiveData(meta, data, start, count);
            }
            const isNotInOrderComparedToPrev = ()=>cur[iAxis] === null || prev && cur[iAxis] < prev[iAxis];
            for(i = 0; i < count; ++i){
                meta._parsed[i + start] = cur = parsed[i];
                if (sorted) {
                    if (isNotInOrderComparedToPrev()) {
                        sorted = false;
                    }
                    prev = cur;
                }
            }
            meta._sorted = sorted;
        }
        if (_stacked) {
            updateStacks(this, parsed);
        }
    }
 parsePrimitiveData(meta, data, start, count) {
        const { iScale , vScale  } = meta;
        const iAxis = iScale.axis;
        const vAxis = vScale.axis;
        const labels = iScale.getLabels();
        const singleScale = iScale === vScale;
        const parsed = new Array(count);
        let i, ilen, index;
        for(i = 0, ilen = count; i < ilen; ++i){
            index = i + start;
            parsed[i] = {
                [iAxis]: singleScale || iScale.parse(labels[index], index),
                [vAxis]: vScale.parse(data[index], index)
            };
        }
        return parsed;
    }
 parseArrayData(meta, data, start, count) {
        const { xScale , yScale  } = meta;
        const parsed = new Array(count);
        let i, ilen, index, item;
        for(i = 0, ilen = count; i < ilen; ++i){
            index = i + start;
            item = data[index];
            parsed[i] = {
                x: xScale.parse(item[0], index),
                y: yScale.parse(item[1], index)
            };
        }
        return parsed;
    }
 parseObjectData(meta, data, start, count) {
        const { xScale , yScale  } = meta;
        const { xAxisKey ='x' , yAxisKey ='y'  } = this._parsing;
        const parsed = new Array(count);
        let i, ilen, index, item;
        for(i = 0, ilen = count; i < ilen; ++i){
            index = i + start;
            item = data[index];
            parsed[i] = {
                x: xScale.parse(resolveObjectKey(item, xAxisKey), index),
                y: yScale.parse(resolveObjectKey(item, yAxisKey), index)
            };
        }
        return parsed;
    }
 getParsed(index) {
        return this._cachedMeta._parsed[index];
    }
 getDataElement(index) {
        return this._cachedMeta.data[index];
    }
 applyStack(scale, parsed, mode) {
        const chart = this.chart;
        const meta = this._cachedMeta;
        const value = parsed[scale.axis];
        const stack = {
            keys: getSortedDatasetIndices(chart, true),
            values: parsed._stacks[scale.axis]._visualValues
        };
        return applyStack(stack, value, meta.index, {
            mode
        });
    }
 updateRangeFromParsed(range, scale, parsed, stack) {
        const parsedValue = parsed[scale.axis];
        let value = parsedValue === null ? NaN : parsedValue;
        const values = stack && parsed._stacks[scale.axis];
        if (stack && values) {
            stack.values = values;
            value = applyStack(stack, parsedValue, this._cachedMeta.index);
        }
        range.min = Math.min(range.min, value);
        range.max = Math.max(range.max, value);
    }
 getMinMax(scale, canStack) {
        const meta = this._cachedMeta;
        const _parsed = meta._parsed;
        const sorted = meta._sorted && scale === meta.iScale;
        const ilen = _parsed.length;
        const otherScale = this._getOtherScale(scale);
        const stack = createStack(canStack, meta, this.chart);
        const range = {
            min: Number.POSITIVE_INFINITY,
            max: Number.NEGATIVE_INFINITY
        };
        const { min: otherMin , max: otherMax  } = getUserBounds(otherScale);
        let i, parsed;
        function _skip() {
            parsed = _parsed[i];
            const otherValue = parsed[otherScale.axis];
            return !isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;
        }
        for(i = 0; i < ilen; ++i){
            if (_skip()) {
                continue;
            }
            this.updateRangeFromParsed(range, scale, parsed, stack);
            if (sorted) {
                break;
            }
        }
        if (sorted) {
            for(i = ilen - 1; i >= 0; --i){
                if (_skip()) {
                    continue;
                }
                this.updateRangeFromParsed(range, scale, parsed, stack);
                break;
            }
        }
        return range;
    }
    getAllParsedValues(scale) {
        const parsed = this._cachedMeta._parsed;
        const values = [];
        let i, ilen, value;
        for(i = 0, ilen = parsed.length; i < ilen; ++i){
            value = parsed[i][scale.axis];
            if (isNumberFinite(value)) {
                values.push(value);
            }
        }
        return values;
    }
 getMaxOverflow() {
        return false;
    }
 getLabelAndValue(index) {
        const meta = this._cachedMeta;
        const iScale = meta.iScale;
        const vScale = meta.vScale;
        const parsed = this.getParsed(index);
        return {
            label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',
            value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''
        };
    }
 _update(mode) {
        const meta = this._cachedMeta;
        this.update(mode || 'default');
        meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));
    }
 update(mode) {}
    draw() {
        const ctx = this._ctx;
        const chart = this.chart;
        const meta = this._cachedMeta;
        const elements = meta.data || [];
        const area = chart.chartArea;
        const active = [];
        const start = this._drawStart || 0;
        const count = this._drawCount || elements.length - start;
        const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;
        let i;
        if (meta.dataset) {
            meta.dataset.draw(ctx, area, start, count);
        }
        for(i = start; i < start + count; ++i){
            const element = elements[i];
            if (element.hidden) {
                continue;
            }
            if (element.active && drawActiveElementsOnTop) {
                active.push(element);
            } else {
                element.draw(ctx, area);
            }
        }
        for(i = 0; i < active.length; ++i){
            active[i].draw(ctx, area);
        }
    }
 getStyle(index, active) {
        const mode = active ? 'active' : 'default';
        return index === undefined && this._cachedMeta.dataset ? this.resolveDatasetElementOptions(mode) : this.resolveDataElementOptions(index || 0, mode);
    }
 getContext(index, active, mode) {
        const dataset = this.getDataset();
        let context;
        if (index >= 0 && index < this._cachedMeta.data.length) {
            const element = this._cachedMeta.data[index];
            context = element.$context || (element.$context = createDataContext(this.getContext(), index, element));
            context.parsed = this.getParsed(index);
            context.raw = dataset.data[index];
            context.index = context.dataIndex = index;
        } else {
            context = this.$context || (this.$context = createDatasetContext(this.chart.getContext(), this.index));
            context.dataset = dataset;
            context.index = context.datasetIndex = this.index;
        }
        context.active = !!active;
        context.mode = mode;
        return context;
    }
 resolveDatasetElementOptions(mode) {
        return this._resolveElementOptions(this.datasetElementType.id, mode);
    }
 resolveDataElementOptions(index, mode) {
        return this._resolveElementOptions(this.dataElementType.id, mode, index);
    }
 _resolveElementOptions(elementType, mode = 'default', index) {
        const active = mode === 'active';
        const cache = this._cachedDataOpts;
        const cacheKey = elementType + '-' + mode;
        const cached = cache[cacheKey];
        const sharing = this.enableOptionSharing && defined(index);
        if (cached) {
            return cloneIfNotShared(cached, sharing);
        }
        const config = this.chart.config;
        const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);
        const prefixes = active ? [
            `${elementType}Hover`,
            'hover',
            elementType,
            ''
        ] : [
            elementType,
            ''
        ];
        const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
        const names = Object.keys(defaults.elements[elementType]);
        const context = ()=>this.getContext(index, active, mode);
        const values = config.resolveNamedOptions(scopes, names, context, prefixes);
        if (values.$shared) {
            values.$shared = sharing;
            cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));
        }
        return values;
    }
 _resolveAnimations(index, transition, active) {
        const chart = this.chart;
        const cache = this._cachedDataOpts;
        const cacheKey = `animation-${transition}`;
        const cached = cache[cacheKey];
        if (cached) {
            return cached;
        }
        let options;
        if (chart.options.animation !== false) {
            const config = this.chart.config;
            const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);
            const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
            options = config.createResolver(scopes, this.getContext(index, active, transition));
        }
        const animations = new Animations(chart, options && options.animations);
        if (options && options._cacheable) {
            cache[cacheKey] = Object.freeze(animations);
        }
        return animations;
    }
 getSharedOptions(options) {
        if (!options.$shared) {
            return;
        }
        return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));
    }
 includeOptions(mode, sharedOptions) {
        return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;
    }
 _getSharedOptions(start, mode) {
        const firstOpts = this.resolveDataElementOptions(start, mode);
        const previouslySharedOptions = this._sharedOptions;
        const sharedOptions = this.getSharedOptions(firstOpts);
        const includeOptions = this.includeOptions(mode, sharedOptions) || sharedOptions !== previouslySharedOptions;
        this.updateSharedOptions(sharedOptions, mode, firstOpts);
        return {
            sharedOptions,
            includeOptions
        };
    }
 updateElement(element, index, properties, mode) {
        if (isDirectUpdateMode(mode)) {
            Object.assign(element, properties);
        } else {
            this._resolveAnimations(index, mode).update(element, properties);
        }
    }
 updateSharedOptions(sharedOptions, mode, newOptions) {
        if (sharedOptions && !isDirectUpdateMode(mode)) {
            this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);
        }
    }
 _setStyle(element, index, mode, active) {
        element.active = active;
        const options = this.getStyle(index, active);
        this._resolveAnimations(index, mode, active).update(element, {
            options: !active && this.getSharedOptions(options) || options
        });
    }
    removeHoverStyle(element, datasetIndex, index) {
        this._setStyle(element, index, 'active', false);
    }
    setHoverStyle(element, datasetIndex, index) {
        this._setStyle(element, index, 'active', true);
    }
 _removeDatasetHoverStyle() {
        const element = this._cachedMeta.dataset;
        if (element) {
            this._setStyle(element, undefined, 'active', false);
        }
    }
 _setDatasetHoverStyle() {
        const element = this._cachedMeta.dataset;
        if (element) {
            this._setStyle(element, undefined, 'active', true);
        }
    }
 _resyncElements(resetNewElements) {
        const data = this._data;
        const elements = this._cachedMeta.data;
        for (const [method, arg1, arg2] of this._syncList){
            this[method](arg1, arg2);
        }
        this._syncList = [];
        const numMeta = elements.length;
        const numData = data.length;
        const count = Math.min(numData, numMeta);
        if (count) {
            this.parse(0, count);
        }
        if (numData > numMeta) {
            this._insertElements(numMeta, numData - numMeta, resetNewElements);
        } else if (numData < numMeta) {
            this._removeElements(numData, numMeta - numData);
        }
    }
 _insertElements(start, count, resetNewElements = true) {
        const meta = this._cachedMeta;
        const data = meta.data;
        const end = start + count;
        let i;
        const move = (arr)=>{
            arr.length += count;
            for(i = arr.length - 1; i >= end; i--){
                arr[i] = arr[i - count];
            }
        };
        move(data);
        for(i = start; i < end; ++i){
            data[i] = new this.dataElementType();
        }
        if (this._parsing) {
            move(meta._parsed);
        }
        this.parse(start, count);
        if (resetNewElements) {
            this.updateElements(data, start, count, 'reset');
        }
    }
    updateElements(element, start, count, mode) {}
 _removeElements(start, count) {
        const meta = this._cachedMeta;
        if (this._parsing) {
            const removed = meta._parsed.splice(start, count);
            if (meta._stacked) {
                clearStacks(meta, removed);
            }
        }
        meta.data.splice(start, count);
    }
 _sync(args) {
        if (this._parsing) {
            this._syncList.push(args);
        } else {
            const [method, arg1, arg2] = args;
            this[method](arg1, arg2);
        }
        this.chart._dataChanges.push([
            this.index,
            ...args
        ]);
    }
    _onDataPush() {
        const count = arguments.length;
        this._sync([
            '_insertElements',
            this.getDataset().data.length - count,
            count
        ]);
    }
    _onDataPop() {
        this._sync([
            '_removeElements',
            this._cachedMeta.data.length - 1,
            1
        ]);
    }
    _onDataShift() {
        this._sync([
            '_removeElements',
            0,
            1
        ]);
    }
    _onDataSplice(start, count) {
        if (count) {
            this._sync([
                '_removeElements',
                start,
                count
            ]);
        }
        const newCount = arguments.length - 2;
        if (newCount) {
            this._sync([
                '_insertElements',
                start,
                newCount
            ]);
        }
    }
    _onDataUnshift() {
        this._sync([
            '_insertElements',
            0,
            arguments.length
        ]);
    }
}

function getAllScaleValues(scale, type) {
    if (!scale._cache.$bar) {
        const visibleMetas = scale.getMatchingVisibleMetas(type);
        let values = [];
        for(let i = 0, ilen = visibleMetas.length; i < ilen; i++){
            values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));
        }
        scale._cache.$bar = _arrayUnique(values.sort((a, b)=>a - b));
    }
    return scale._cache.$bar;
}
 function computeMinSampleSize(meta) {
    const scale = meta.iScale;
    const values = getAllScaleValues(scale, meta.type);
    let min = scale._length;
    let i, ilen, curr, prev;
    const updateMinAndPrev = ()=>{
        if (curr === 32767 || curr === -32768) {
            return;
        }
        if (defined(prev)) {
            min = Math.min(min, Math.abs(curr - prev) || min);
        }
        prev = curr;
    };
    for(i = 0, ilen = values.length; i < ilen; ++i){
        curr = scale.getPixelForValue(values[i]);
        updateMinAndPrev();
    }
    prev = undefined;
    for(i = 0, ilen = scale.ticks.length; i < ilen; ++i){
        curr = scale.getPixelForTick(i);
        updateMinAndPrev();
    }
    return min;
}
 function computeFitCategoryTraits(index, ruler, options, stackCount) {
    const thickness = options.barThickness;
    let size, ratio;
    if (isNullOrUndef(thickness)) {
        size = ruler.min * options.categoryPercentage;
        ratio = options.barPercentage;
    } else {
        size = thickness * stackCount;
        ratio = 1;
    }
    return {
        chunk: size / stackCount,
        ratio,
        start: ruler.pixels[index] - size / 2
    };
}
 function computeFlexCategoryTraits(index, ruler, options, stackCount) {
    const pixels = ruler.pixels;
    const curr = pixels[index];
    let prev = index > 0 ? pixels[index - 1] : null;
    let next = index < pixels.length - 1 ? pixels[index + 1] : null;
    const percent = options.categoryPercentage;
    if (prev === null) {
        prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
    }
    if (next === null) {
        next = curr + curr - prev;
    }
    const start = curr - (curr - Math.min(prev, next)) / 2 * percent;
    const size = Math.abs(next - prev) / 2 * percent;
    return {
        chunk: size / stackCount,
        ratio: options.barPercentage,
        start
    };
}
function parseFloatBar(entry, item, vScale, i) {
    const startValue = vScale.parse(entry[0], i);
    const endValue = vScale.parse(entry[1], i);
    const min = Math.min(startValue, endValue);
    const max = Math.max(startValue, endValue);
    let barStart = min;
    let barEnd = max;
    if (Math.abs(min) > Math.abs(max)) {
        barStart = max;
        barEnd = min;
    }
    item[vScale.axis] = barEnd;
    item._custom = {
        barStart,
        barEnd,
        start: startValue,
        end: endValue,
        min,
        max
    };
}
function parseValue(entry, item, vScale, i) {
    if (isArray(entry)) {
        parseFloatBar(entry, item, vScale, i);
    } else {
        item[vScale.axis] = vScale.parse(entry, i);
    }
    return item;
}
function parseArrayOrPrimitive(meta, data, start, count) {
    const iScale = meta.iScale;
    const vScale = meta.vScale;
    const labels = iScale.getLabels();
    const singleScale = iScale === vScale;
    const parsed = [];
    let i, ilen, item, entry;
    for(i = start, ilen = start + count; i < ilen; ++i){
        entry = data[i];
        item = {};
        item[iScale.axis] = singleScale || iScale.parse(labels[i], i);
        parsed.push(parseValue(entry, item, vScale, i));
    }
    return parsed;
}
function isFloatBar(custom) {
    return custom && custom.barStart !== undefined && custom.barEnd !== undefined;
}
function barSign(size, vScale, actualBase) {
    if (size !== 0) {
        return sign(size);
    }
    return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);
}
function borderProps(properties) {
    let reverse, start, end, top, bottom;
    if (properties.horizontal) {
        reverse = properties.base > properties.x;
        start = 'left';
        end = 'right';
    } else {
        reverse = properties.base < properties.y;
        start = 'bottom';
        end = 'top';
    }
    if (reverse) {
        top = 'end';
        bottom = 'start';
    } else {
        top = 'start';
        bottom = 'end';
    }
    return {
        start,
        end,
        reverse,
        top,
        bottom
    };
}
function setBorderSkipped(properties, options, stack, index) {
    let edge = options.borderSkipped;
    const res = {};
    if (!edge) {
        properties.borderSkipped = res;
        return;
    }
    if (edge === true) {
        properties.borderSkipped = {
            top: true,
            right: true,
            bottom: true,
            left: true
        };
        return;
    }
    const { start , end , reverse , top , bottom  } = borderProps(properties);
    if (edge === 'middle' && stack) {
        properties.enableBorderRadius = true;
        if ((stack._top || 0) === index) {
            edge = top;
        } else if ((stack._bottom || 0) === index) {
            edge = bottom;
        } else {
            res[parseEdge(bottom, start, end, reverse)] = true;
            edge = top;
        }
    }
    res[parseEdge(edge, start, end, reverse)] = true;
    properties.borderSkipped = res;
}
function parseEdge(edge, a, b, reverse) {
    if (reverse) {
        edge = swap(edge, a, b);
        edge = startEnd(edge, b, a);
    } else {
        edge = startEnd(edge, a, b);
    }
    return edge;
}
function swap(orig, v1, v2) {
    return orig === v1 ? v2 : orig === v2 ? v1 : orig;
}
function startEnd(v, start, end) {
    return v === 'start' ? start : v === 'end' ? end : v;
}
function setInflateAmount(properties, { inflateAmount  }, ratio) {
    properties.inflateAmount = inflateAmount === 'auto' ? ratio === 1 ? 0.33 : 0 : inflateAmount;
}
class BarController extends DatasetController {
    static id = 'bar';
 static defaults = {
        datasetElementType: false,
        dataElementType: 'bar',
        categoryPercentage: 0.8,
        barPercentage: 0.9,
        grouped: true,
        animations: {
            numbers: {
                type: 'number',
                properties: [
                    'x',
                    'y',
                    'base',
                    'width',
                    'height'
                ]
            }
        }
    };
 static overrides = {
        scales: {
            _index_: {
                type: 'category',
                offset: true,
                grid: {
                    offset: true
                }
            },
            _value_: {
                type: 'linear',
                beginAtZero: true
            }
        }
    };
 parsePrimitiveData(meta, data, start, count) {
        return parseArrayOrPrimitive(meta, data, start, count);
    }
 parseArrayData(meta, data, start, count) {
        return parseArrayOrPrimitive(meta, data, start, count);
    }
 parseObjectData(meta, data, start, count) {
        const { iScale , vScale  } = meta;
        const { xAxisKey ='x' , yAxisKey ='y'  } = this._parsing;
        const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;
        const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;
        const parsed = [];
        let i, ilen, item, obj;
        for(i = start, ilen = start + count; i < ilen; ++i){
            obj = data[i];
            item = {};
            item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);
            parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));
        }
        return parsed;
    }
 updateRangeFromParsed(range, scale, parsed, stack) {
        super.updateRangeFromParsed(range, scale, parsed, stack);
        const custom = parsed._custom;
        if (custom && scale === this._cachedMeta.vScale) {
            range.min = Math.min(range.min, custom.min);
            range.max = Math.max(range.max, custom.max);
        }
    }
 getMaxOverflow() {
        return 0;
    }
 getLabelAndValue(index) {
        const meta = this._cachedMeta;
        const { iScale , vScale  } = meta;
        const parsed = this.getParsed(index);
        const custom = parsed._custom;
        const value = isFloatBar(custom) ? '[' + custom.start + ', ' + custom.end + ']' : '' + vScale.getLabelForValue(parsed[vScale.axis]);
        return {
            label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
            value
        };
    }
    initialize() {
        this.enableOptionSharing = true;
        super.initialize();
        const meta = this._cachedMeta;
        meta.stack = this.getDataset().stack;
    }
    update(mode) {
        const meta = this._cachedMeta;
        this.updateElements(meta.data, 0, meta.data.length, mode);
    }
    updateElements(bars, start, count, mode) {
        const reset = mode === 'reset';
        const { index , _cachedMeta: { vScale  }  } = this;
        const base = vScale.getBasePixel();
        const horizontal = vScale.isHorizontal();
        const ruler = this._getRuler();
        const { sharedOptions , includeOptions  } = this._getSharedOptions(start, mode);
        for(let i = start; i < start + count; i++){
            const parsed = this.getParsed(i);
            const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {
                base,
                head: base
            } : this._calculateBarValuePixels(i);
            const ipixels = this._calculateBarIndexPixels(i, ruler);
            const stack = (parsed._stacks || {})[vScale.axis];
            const properties = {
                horizontal,
                base: vpixels.base,
                enableBorderRadius: !stack || isFloatBar(parsed._custom) || index === stack._top || index === stack._bottom,
                x: horizontal ? vpixels.head : ipixels.center,
                y: horizontal ? ipixels.center : vpixels.head,
                height: horizontal ? ipixels.size : Math.abs(vpixels.size),
                width: horizontal ? Math.abs(vpixels.size) : ipixels.size
            };
            if (includeOptions) {
                properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);
            }
            const options = properties.options || bars[i].options;
            setBorderSkipped(properties, options, stack, index);
            setInflateAmount(properties, options, ruler.ratio);
            this.updateElement(bars[i], i, properties, mode);
        }
    }
 _getStacks(last, dataIndex) {
        const { iScale  } = this._cachedMeta;
        const metasets = iScale.getMatchingVisibleMetas(this._type).filter((meta)=>meta.controller.options.grouped);
        const stacked = iScale.options.stacked;
        const stacks = [];
        const currentParsed = this._cachedMeta.controller.getParsed(dataIndex);
        const iScaleValue = currentParsed && currentParsed[iScale.axis];
        const skipNull = (meta)=>{
            const parsed = meta._parsed.find((item)=>item[iScale.axis] === iScaleValue);
            const val = parsed && parsed[meta.vScale.axis];
            if (isNullOrUndef(val) || isNaN(val)) {
                return true;
            }
        };
        for (const meta of metasets){
            if (dataIndex !== undefined && skipNull(meta)) {
                continue;
            }
            if (stacked === false || stacks.indexOf(meta.stack) === -1 || stacked === undefined && meta.stack === undefined) {
                stacks.push(meta.stack);
            }
            if (meta.index === last) {
                break;
            }
        }
        if (!stacks.length) {
            stacks.push(undefined);
        }
        return stacks;
    }
 _getStackCount(index) {
        return this._getStacks(undefined, index).length;
    }
    _getAxisCount() {
        return this._getAxis().length;
    }
    getFirstScaleIdForIndexAxis() {
        const scales = this.chart.scales;
        const indexScaleId = this.chart.options.indexAxis;
        return Object.keys(scales).filter((key)=>scales[key].axis === indexScaleId).shift();
    }
    _getAxis() {
        const axis = {};
        const firstScaleAxisId = this.getFirstScaleIdForIndexAxis();
        for (const dataset of this.chart.data.datasets){
            axis[valueOrDefault(this.chart.options.indexAxis === 'x' ? dataset.xAxisID : dataset.yAxisID, firstScaleAxisId)] = true;
        }
        return Object.keys(axis);
    }
 _getStackIndex(datasetIndex, name, dataIndex) {
        const stacks = this._getStacks(datasetIndex, dataIndex);
        const index = name !== undefined ? stacks.indexOf(name) : -1;
        return index === -1 ? stacks.length - 1 : index;
    }
 _getRuler() {
        const opts = this.options;
        const meta = this._cachedMeta;
        const iScale = meta.iScale;
        const pixels = [];
        let i, ilen;
        for(i = 0, ilen = meta.data.length; i < ilen; ++i){
            pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));
        }
        const barThickness = opts.barThickness;
        const min = barThickness || computeMinSampleSize(meta);
        return {
            min,
            pixels,
            start: iScale._startPixel,
            end: iScale._endPixel,
            stackCount: this._getStackCount(),
            scale: iScale,
            grouped: opts.grouped,
            ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
        };
    }
 _calculateBarValuePixels(index) {
        const { _cachedMeta: { vScale , _stacked , index: datasetIndex  } , options: { base: baseValue , minBarLength  }  } = this;
        const actualBase = baseValue || 0;
        const parsed = this.getParsed(index);
        const custom = parsed._custom;
        const floating = isFloatBar(custom);
        let value = parsed[vScale.axis];
        let start = 0;
        let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;
        let head, size;
        if (length !== value) {
            start = length - value;
            length = value;
        }
        if (floating) {
            value = custom.barStart;
            length = custom.barEnd - custom.barStart;
            if (value !== 0 && sign(value) !== sign(custom.barEnd)) {
                start = 0;
            }
            start += value;
        }
        const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;
        let base = vScale.getPixelForValue(startValue);
        if (this.chart.getDataVisibility(index)) {
            head = vScale.getPixelForValue(start + length);
        } else {
            head = base;
        }
        size = head - base;
        if (Math.abs(size) < minBarLength) {
            size = barSign(size, vScale, actualBase) * minBarLength;
            if (value === actualBase) {
                base -= size / 2;
            }
            const startPixel = vScale.getPixelForDecimal(0);
            const endPixel = vScale.getPixelForDecimal(1);
            const min = Math.min(startPixel, endPixel);
            const max = Math.max(startPixel, endPixel);
            base = Math.max(Math.min(base, max), min);
            head = base + size;
            if (_stacked && !floating) {
                parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base);
            }
        }
        if (base === vScale.getPixelForValue(actualBase)) {
            const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;
            base += halfGrid;
            size -= halfGrid;
        }
        return {
            size,
            base,
            head,
            center: head + size / 2
        };
    }
 _calculateBarIndexPixels(index, ruler) {
        const scale = ruler.scale;
        const options = this.options;
        const skipNull = options.skipNull;
        const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);
        let center, size;
        const axisCount = this._getAxisCount();
        if (ruler.grouped) {
            const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;
            const range = options.barThickness === 'flex' ? computeFlexCategoryTraits(index, ruler, options, stackCount * axisCount) : computeFitCategoryTraits(index, ruler, options, stackCount * axisCount);
            const axisID = this.chart.options.indexAxis === 'x' ? this.getDataset().xAxisID : this.getDataset().yAxisID;
            const axisNumber = this._getAxis().indexOf(valueOrDefault(axisID, this.getFirstScaleIdForIndexAxis()));
            const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined) + axisNumber;
            center = range.start + range.chunk * stackIndex + range.chunk / 2;
            size = Math.min(maxBarThickness, range.chunk * range.ratio);
        } else {
            center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);
            size = Math.min(maxBarThickness, ruler.min * ruler.ratio);
        }
        return {
            base: center - size / 2,
            head: center + size / 2,
            center,
            size
        };
    }
    draw() {
        const meta = this._cachedMeta;
        const vScale = meta.vScale;
        const rects = meta.data;
        const ilen = rects.length;
        let i = 0;
        for(; i < ilen; ++i){
            if (this.getParsed(i)[vScale.axis] !== null && !rects[i].hidden) {
                rects[i].draw(this._ctx);
            }
        }
    }
}

class BubbleController extends DatasetController {
    static id = 'bubble';
 static defaults = {
        datasetElementType: false,
        dataElementType: 'point',
        animations: {
            numbers: {
                type: 'number',
                properties: [
                    'x',
                    'y',
                    'borderWidth',
                    'radius'
                ]
            }
        }
    };
 static overrides = {
        scales: {
            x: {
                type: 'linear'
            },
            y: {
                type: 'linear'
            }
        }
    };
    initialize() {
        this.enableOptionSharing = true;
        super.initialize();
    }
 parsePrimitiveData(meta, data, start, count) {
        const parsed = super.parsePrimitiveData(meta, data, start, count);
        for(let i = 0; i < parsed.length; i++){
            parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;
        }
        return parsed;
    }
 parseArrayData(meta, data, start, count) {
        const parsed = super.parseArrayData(meta, data, start, count);
        for(let i = 0; i < parsed.length; i++){
            const item = data[start + i];
            parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);
        }
        return parsed;
    }
 parseObjectData(meta, data, start, count) {
        const parsed = super.parseObjectData(meta, data, start, count);
        for(let i = 0; i < parsed.length; i++){
            const item = data[start + i];
            parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);
        }
        return parsed;
    }
 getMaxOverflow() {
        const data = this._cachedMeta.data;
        let max = 0;
        for(let i = data.length - 1; i >= 0; --i){
            max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);
        }
        return max > 0 && max;
    }
 getLabelAndValue(index) {
        const meta = this._cachedMeta;
        const labels = this.chart.data.labels || [];
        const { xScale , yScale  } = meta;
        const parsed = this.getParsed(index);
        const x = xScale.getLabelForValue(parsed.x);
        const y = yScale.getLabelForValue(parsed.y);
        const r = parsed._custom;
        return {
            label: labels[index] || '',
            value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'
        };
    }
    update(mode) {
        const points = this._cachedMeta.data;
        this.updateElements(points, 0, points.length, mode);
    }
    updateElements(points, start, count, mode) {
        const reset = mode === 'reset';
        const { iScale , vScale  } = this._cachedMeta;
        const { sharedOptions , includeOptions  } = this._getSharedOptions(start, mode);
        const iAxis = iScale.axis;
        const vAxis = vScale.axis;
        for(let i = start; i < start + count; i++){
            const point = points[i];
            const parsed = !reset && this.getParsed(i);
            const properties = {};
            const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);
            const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);
            properties.skip = isNaN(iPixel) || isNaN(vPixel);
            if (includeOptions) {
                properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
                if (reset) {
                    properties.options.radius = 0;
                }
            }
            this.updateElement(point, i, properties, mode);
        }
    }
 resolveDataElementOptions(index, mode) {
        const parsed = this.getParsed(index);
        let values = super.resolveDataElementOptions(index, mode);
        if (values.$shared) {
            values = Object.assign({}, values, {
                $shared: false
            });
        }
        const radius = values.radius;
        if (mode !== 'active') {
            values.radius = 0;
        }
        values.radius += valueOrDefault(parsed && parsed._custom, radius);
        return values;
    }
}

function getRatioAndOffset(rotation, circumference, cutout) {
    let ratioX = 1;
    let ratioY = 1;
    let offsetX = 0;
    let offsetY = 0;
    if (circumference < TAU) {
        const startAngle = rotation;
        const endAngle = startAngle + circumference;
        const startX = Math.cos(startAngle);
        const startY = Math.sin(startAngle);
        const endX = Math.cos(endAngle);
        const endY = Math.sin(endAngle);
        const calcMax = (angle, a, b)=>_angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);
        const calcMin = (angle, a, b)=>_angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);
        const maxX = calcMax(0, startX, endX);
        const maxY = calcMax(HALF_PI, startY, endY);
        const minX = calcMin(PI, startX, endX);
        const minY = calcMin(PI + HALF_PI, startY, endY);
        ratioX = (maxX - minX) / 2;
        ratioY = (maxY - minY) / 2;
        offsetX = -(maxX + minX) / 2;
        offsetY = -(maxY + minY) / 2;
    }
    return {
        ratioX,
        ratioY,
        offsetX,
        offsetY
    };
}
class DoughnutController extends DatasetController {
    static id = 'doughnut';
 static defaults = {
        datasetElementType: false,
        dataElementType: 'arc',
        animation: {
            animateRotate: true,
            animateScale: false
        },
        animations: {
            numbers: {
                type: 'number',
                properties: [
                    'circumference',
                    'endAngle',
                    'innerRadius',
                    'outerRadius',
                    'startAngle',
                    'x',
                    'y',
                    'offset',
                    'borderWidth',
                    'spacing'
                ]
            }
        },
        cutout: '50%',
        rotation: 0,
        circumference: 360,
        radius: '100%',
        spacing: 0,
        indexAxis: 'r'
    };
    static descriptors = {
        _scriptable: (name)=>name !== 'spacing',
        _indexable: (name)=>name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash')
    };
 static overrides = {
        aspectRatio: 1,
        plugins: {
            legend: {
                labels: {
                    generateLabels (chart) {
                        const data = chart.data;
                        const { labels: { pointStyle , textAlign , color , useBorderRadius , borderRadius  }  } = chart.legend.options;
                        if (data.labels.length && data.datasets.length) {
                            return data.labels.map((label, i)=>{
                                const meta = chart.getDatasetMeta(0);
                                const style = meta.controller.getStyle(i);
                                return {
                                    text: label,
                                    fillStyle: style.backgroundColor,
                                    fontColor: color,
                                    hidden: !chart.getDataVisibility(i),
                                    lineDash: style.borderDash,
                                    lineDashOffset: style.borderDashOffset,
                                    lineJoin: style.borderJoinStyle,
                                    lineWidth: style.borderWidth,
                                    strokeStyle: style.borderColor,
                                    textAlign: textAlign,
                                    pointStyle: pointStyle,
                                    borderRadius: useBorderRadius && (borderRadius || style.borderRadius),
                                    index: i
                                };
                            });
                        }
                        return [];
                    }
                },
                onClick (e, legendItem, legend) {
                    legend.chart.toggleDataVisibility(legendItem.index);
                    legend.chart.update();
                }
            }
        }
    };
    constructor(chart, datasetIndex){
        super(chart, datasetIndex);
        this.enableOptionSharing = true;
        this.innerRadius = undefined;
        this.outerRadius = undefined;
        this.offsetX = undefined;
        this.offsetY = undefined;
    }
    linkScales() {}
 parse(start, count) {
        const data = this.getDataset().data;
        const meta = this._cachedMeta;
        if (this._parsing === false) {
            meta._parsed = data;
        } else {
            let getter = (i)=>+data[i];
            if (isObject(data[start])) {
                const { key ='value'  } = this._parsing;
                getter = (i)=>+resolveObjectKey(data[i], key);
            }
            let i, ilen;
            for(i = start, ilen = start + count; i < ilen; ++i){
                meta._parsed[i] = getter(i);
            }
        }
    }
 _getRotation() {
        return toRadians(this.options.rotation - 90);
    }
 _getCircumference() {
        return toRadians(this.options.circumference);
    }
 _getRotationExtents() {
        let min = TAU;
        let max = -TAU;
        for(let i = 0; i < this.chart.data.datasets.length; ++i){
            if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) {
                const controller = this.chart.getDatasetMeta(i).controller;
                const rotation = controller._getRotation();
                const circumference = controller._getCircumference();
                min = Math.min(min, rotation);
                max = Math.max(max, rotation + circumference);
            }
        }
        return {
            rotation: min,
            circumference: max - min
        };
    }
 update(mode) {
        const chart = this.chart;
        const { chartArea  } = chart;
        const meta = this._cachedMeta;
        const arcs = meta.data;
        const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;
        const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
        const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1);
        const chartWeight = this._getRingWeight(this.index);
        const { circumference , rotation  } = this._getRotationExtents();
        const { ratioX , ratioY , offsetX , offsetY  } = getRatioAndOffset(rotation, circumference, cutout);
        const maxWidth = (chartArea.width - spacing) / ratioX;
        const maxHeight = (chartArea.height - spacing) / ratioY;
        const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
        const outerRadius = toDimension(this.options.radius, maxRadius);
        const innerRadius = Math.max(outerRadius * cutout, 0);
        const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();
        this.offsetX = offsetX * outerRadius;
        this.offsetY = offsetY * outerRadius;
        meta.total = this.calculateTotal();
        this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);
        this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);
        this.updateElements(arcs, 0, arcs.length, mode);
    }
 _circumference(i, reset) {
        const opts = this.options;
        const meta = this._cachedMeta;
        const circumference = this._getCircumference();
        if (reset && opts.animation.animateRotate || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {
            return 0;
        }
        return this.calculateCircumference(meta._parsed[i] * circumference / TAU);
    }
    updateElements(arcs, start, count, mode) {
        const reset = mode === 'reset';
        const chart = this.chart;
        const chartArea = chart.chartArea;
        const opts = chart.options;
        const animationOpts = opts.animation;
        const centerX = (chartArea.left + chartArea.right) / 2;
        const centerY = (chartArea.top + chartArea.bottom) / 2;
        const animateScale = reset && animationOpts.animateScale;
        const innerRadius = animateScale ? 0 : this.innerRadius;
        const outerRadius = animateScale ? 0 : this.outerRadius;
        const { sharedOptions , includeOptions  } = this._getSharedOptions(start, mode);
        let startAngle = this._getRotation();
        let i;
        for(i = 0; i < start; ++i){
            startAngle += this._circumference(i, reset);
        }
        for(i = start; i < start + count; ++i){
            const circumference = this._circumference(i, reset);
            const arc = arcs[i];
            const properties = {
                x: centerX + this.offsetX,
                y: centerY + this.offsetY,
                startAngle,
                endAngle: startAngle + circumference,
                circumference,
                outerRadius,
                innerRadius
            };
            if (includeOptions) {
                properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);
            }
            startAngle += circumference;
            this.updateElement(arc, i, properties, mode);
        }
    }
    calculateTotal() {
        const meta = this._cachedMeta;
        const metaData = meta.data;
        let total = 0;
        let i;
        for(i = 0; i < metaData.length; i++){
            const value = meta._parsed[i];
            if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {
                total += Math.abs(value);
            }
        }
        return total;
    }
    calculateCircumference(value) {
        const total = this._cachedMeta.total;
        if (total > 0 && !isNaN(value)) {
            return TAU * (Math.abs(value) / total);
        }
        return 0;
    }
    getLabelAndValue(index) {
        const meta = this._cachedMeta;
        const chart = this.chart;
        const labels = chart.data.labels || [];
        const value = formatNumber(meta._parsed[index], chart.options.locale);
        return {
            label: labels[index] || '',
            value
        };
    }
    getMaxBorderWidth(arcs) {
        let max = 0;
        const chart = this.chart;
        let i, ilen, meta, controller, options;
        if (!arcs) {
            for(i = 0, ilen = chart.data.datasets.length; i < ilen; ++i){
                if (chart.isDatasetVisible(i)) {
                    meta = chart.getDatasetMeta(i);
                    arcs = meta.data;
                    controller = meta.controller;
                    break;
                }
            }
        }
        if (!arcs) {
            return 0;
        }
        for(i = 0, ilen = arcs.length; i < ilen; ++i){
            options = controller.resolveDataElementOptions(i);
            if (options.borderAlign !== 'inner') {
                max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);
            }
        }
        return max;
    }
    getMaxOffset(arcs) {
        let max = 0;
        for(let i = 0, ilen = arcs.length; i < ilen; ++i){
            const options = this.resolveDataElementOptions(i);
            max = Math.max(max, options.offset || 0, options.hoverOffset || 0);
        }
        return max;
    }
 _getRingWeightOffset(datasetIndex) {
        let ringWeightOffset = 0;
        for(let i = 0; i < datasetIndex; ++i){
            if (this.chart.isDatasetVisible(i)) {
                ringWeightOffset += this._getRingWeight(i);
            }
        }
        return ringWeightOffset;
    }
 _getRingWeight(datasetIndex) {
        return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
    }
 _getVisibleDatasetWeightTotal() {
        return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
    }
}

class LineController extends DatasetController {
    static id = 'line';
 static defaults = {
        datasetElementType: 'line',
        dataElementType: 'point',
        showLine: true,
        spanGaps: false
    };
 static overrides = {
        scales: {
            _index_: {
                type: 'category'
            },
            _value_: {
                type: 'linear'
            }
        }
    };
    initialize() {
        this.enableOptionSharing = true;
        this.supportsDecimation = true;
        super.initialize();
    }
    update(mode) {
        const meta = this._cachedMeta;
        const { dataset: line , data: points = [] , _dataset  } = meta;
        const animationsDisabled = this.chart._animationsDisabled;
        let { start , count  } = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
        this._drawStart = start;
        this._drawCount = count;
        if (_scaleRangesChanged(meta)) {
            start = 0;
            count = points.length;
        }
        line._chart = this.chart;
        line._datasetIndex = this.index;
        line._decimated = !!_dataset._decimated;
        line.points = points;
        const options = this.resolveDatasetElementOptions(mode);
        if (!this.options.showLine) {
            options.borderWidth = 0;
        }
        options.segment = this.options.segment;
        this.updateElement(line, undefined, {
            animated: !animationsDisabled,
            options
        }, mode);
        this.updateElements(points, start, count, mode);
    }
    updateElements(points, start, count, mode) {
        const reset = mode === 'reset';
        const { iScale , vScale , _stacked , _dataset  } = this._cachedMeta;
        const { sharedOptions , includeOptions  } = this._getSharedOptions(start, mode);
        const iAxis = iScale.axis;
        const vAxis = vScale.axis;
        const { spanGaps , segment  } = this.options;
        const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
        const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';
        const end = start + count;
        const pointsCount = points.length;
        let prevParsed = start > 0 && this.getParsed(start - 1);
        for(let i = 0; i < pointsCount; ++i){
            const point = points[i];
            const properties = directUpdate ? point : {};
            if (i < start || i >= end) {
                properties.skip = true;
                continue;
            }
            const parsed = this.getParsed(i);
            const nullData = isNullOrUndef(parsed[vAxis]);
            const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
            const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
            properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
            properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
            if (segment) {
                properties.parsed = parsed;
                properties.raw = _dataset.data[i];
            }
            if (includeOptions) {
                properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
            }
            if (!directUpdate) {
                this.updateElement(point, i, properties, mode);
            }
            prevParsed = parsed;
        }
    }
 getMaxOverflow() {
        const meta = this._cachedMeta;
        const dataset = meta.dataset;
        const border = dataset.options && dataset.options.borderWidth || 0;
        const data = meta.data || [];
        if (!data.length) {
            return border;
        }
        const firstPoint = data[0].size(this.resolveDataElementOptions(0));
        const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));
        return Math.max(border, firstPoint, lastPoint) / 2;
    }
    draw() {
        const meta = this._cachedMeta;
        meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);
        super.draw();
    }
}

class PolarAreaController extends DatasetController {
    static id = 'polarArea';
 static defaults = {
        dataElementType: 'arc',
        animation: {
            animateRotate: true,
            animateScale: true
        },
        animations: {
            numbers: {
                type: 'number',
                properties: [
                    'x',
                    'y',
                    'startAngle',
                    'endAngle',
                    'innerRadius',
                    'outerRadius'
                ]
            }
        },
        indexAxis: 'r',
        startAngle: 0
    };
 static overrides = {
        aspectRatio: 1,
        plugins: {
            legend: {
                labels: {
                    generateLabels (chart) {
                        const data = chart.data;
                        if (data.labels.length && data.datasets.length) {
                            const { labels: { pointStyle , color  }  } = chart.legend.options;
                            return data.labels.map((label, i)=>{
                                const meta = chart.getDatasetMeta(0);
                                const style = meta.controller.getStyle(i);
                                return {
                                    text: label,
                                    fillStyle: style.backgroundColor,
                                    strokeStyle: style.borderColor,
                                    fontColor: color,
                                    lineWidth: style.borderWidth,
                                    pointStyle: pointStyle,
                                    hidden: !chart.getDataVisibility(i),
                                    index: i
                                };
                            });
                        }
                        return [];
                    }
                },
                onClick (e, legendItem, legend) {
                    legend.chart.toggleDataVisibility(legendItem.index);
                    legend.chart.update();
                }
            }
        },
        scales: {
            r: {
                type: 'radialLinear',
                angleLines: {
                    display: false
                },
                beginAtZero: true,
                grid: {
                    circular: true
                },
                pointLabels: {
                    display: false
                },
                startAngle: 0
            }
        }
    };
    constructor(chart, datasetIndex){
        super(chart, datasetIndex);
        this.innerRadius = undefined;
        this.outerRadius = undefined;
    }
    getLabelAndValue(index) {
        const meta = this._cachedMeta;
        const chart = this.chart;
        const labels = chart.data.labels || [];
        const value = formatNumber(meta._parsed[index].r, chart.options.locale);
        return {
            label: labels[index] || '',
            value
        };
    }
    parseObjectData(meta, data, start, count) {
        return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);
    }
    update(mode) {
        const arcs = this._cachedMeta.data;
        this._updateRadius();
        this.updateElements(arcs, 0, arcs.length, mode);
    }
 getMinMax() {
        const meta = this._cachedMeta;
        const range = {
            min: Number.POSITIVE_INFINITY,
            max: Number.NEGATIVE_INFINITY
        };
        meta.data.forEach((element, index)=>{
            const parsed = this.getParsed(index).r;
            if (!isNaN(parsed) && this.chart.getDataVisibility(index)) {
                if (parsed < range.min) {
                    range.min = parsed;
                }
                if (parsed > range.max) {
                    range.max = parsed;
                }
            }
        });
        return range;
    }
 _updateRadius() {
        const chart = this.chart;
        const chartArea = chart.chartArea;
        const opts = chart.options;
        const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
        const outerRadius = Math.max(minSize / 2, 0);
        const innerRadius = Math.max(opts.cutoutPercentage ? outerRadius / 100 * opts.cutoutPercentage : 1, 0);
        const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();
        this.outerRadius = outerRadius - radiusLength * this.index;
        this.innerRadius = this.outerRadius - radiusLength;
    }
    updateElements(arcs, start, count, mode) {
        const reset = mode === 'reset';
        const chart = this.chart;
        const opts = chart.options;
        const animationOpts = opts.animation;
        const scale = this._cachedMeta.rScale;
        const centerX = scale.xCenter;
        const centerY = scale.yCenter;
        const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;
        let angle = datasetStartAngle;
        let i;
        const defaultAngle = 360 / this.countVisibleElements();
        for(i = 0; i < start; ++i){
            angle += this._computeAngle(i, mode, defaultAngle);
        }
        for(i = start; i < start + count; i++){
            const arc = arcs[i];
            let startAngle = angle;
            let endAngle = angle + this._computeAngle(i, mode, defaultAngle);
            let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0;
            angle = endAngle;
            if (reset) {
                if (animationOpts.animateScale) {
                    outerRadius = 0;
                }
                if (animationOpts.animateRotate) {
                    startAngle = endAngle = datasetStartAngle;
                }
            }
            const properties = {
                x: centerX,
                y: centerY,
                innerRadius: 0,
                outerRadius,
                startAngle,
                endAngle,
                options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)
            };
            this.updateElement(arc, i, properties, mode);
        }
    }
    countVisibleElements() {
        const meta = this._cachedMeta;
        let count = 0;
        meta.data.forEach((element, index)=>{
            if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) {
                count++;
            }
        });
        return count;
    }
 _computeAngle(index, mode, defaultAngle) {
        return this.chart.getDataVisibility(index) ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) : 0;
    }
}

class PieController extends DoughnutController {
    static id = 'pie';
 static defaults = {
        cutout: 0,
        rotation: 0,
        circumference: 360,
        radius: '100%'
    };
}

class RadarController extends DatasetController {
    static id = 'radar';
 static defaults = {
        datasetElementType: 'line',
        dataElementType: 'point',
        indexAxis: 'r',
        showLine: true,
        elements: {
            line: {
                fill: 'start'
            }
        }
    };
 static overrides = {
        aspectRatio: 1,
        scales: {
            r: {
                type: 'radialLinear'
            }
        }
    };
 getLabelAndValue(index) {
        const vScale = this._cachedMeta.vScale;
        const parsed = this.getParsed(index);
        return {
            label: vScale.getLabels()[index],
            value: '' + vScale.getLabelForValue(parsed[vScale.axis])
        };
    }
    parseObjectData(meta, data, start, count) {
        return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);
    }
    update(mode) {
        const meta = this._cachedMeta;
        const line = meta.dataset;
        const points = meta.data || [];
        const labels = meta.iScale.getLabels();
        line.points = points;
        if (mode !== 'resize') {
            const options = this.resolveDatasetElementOptions(mode);
            if (!this.options.showLine) {
                options.borderWidth = 0;
            }
            const properties = {
                _loop: true,
                _fullLoop: labels.length === points.length,
                options
            };
            this.updateElement(line, undefined, properties, mode);
        }
        this.updateElements(points, 0, points.length, mode);
    }
    updateElements(points, start, count, mode) {
        const scale = this._cachedMeta.rScale;
        const reset = mode === 'reset';
        for(let i = start; i < start + count; i++){
            const point = points[i];
            const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);
            const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r);
            const x = reset ? scale.xCenter : pointPosition.x;
            const y = reset ? scale.yCenter : pointPosition.y;
            const properties = {
                x,
                y,
                angle: pointPosition.angle,
                skip: isNaN(x) || isNaN(y),
                options
            };
            this.updateElement(point, i, properties, mode);
        }
    }
}

class ScatterController extends DatasetController {
    static id = 'scatter';
 static defaults = {
        datasetElementType: false,
        dataElementType: 'point',
        showLine: false,
        fill: false
    };
 static overrides = {
        interaction: {
            mode: 'point'
        },
        scales: {
            x: {
                type: 'linear'
            },
            y: {
                type: 'linear'
            }
        }
    };
 getLabelAndValue(index) {
        const meta = this._cachedMeta;
        const labels = this.chart.data.labels || [];
        const { xScale , yScale  } = meta;
        const parsed = this.getParsed(index);
        const x = xScale.getLabelForValue(parsed.x);
        const y = yScale.getLabelForValue(parsed.y);
        return {
            label: labels[index] || '',
            value: '(' + x + ', ' + y + ')'
        };
    }
    update(mode) {
        const meta = this._cachedMeta;
        const { data: points = []  } = meta;
        const animationsDisabled = this.chart._animationsDisabled;
        let { start , count  } = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
        this._drawStart = start;
        this._drawCount = count;
        if (_scaleRangesChanged(meta)) {
            start = 0;
            count = points.length;
        }
        if (this.options.showLine) {
            if (!this.datasetElementType) {
                this.addElements();
            }
            const { dataset: line , _dataset  } = meta;
            line._chart = this.chart;
            line._datasetIndex = this.index;
            line._decimated = !!_dataset._decimated;
            line.points = points;
            const options = this.resolveDatasetElementOptions(mode);
            options.segment = this.options.segment;
            this.updateElement(line, undefined, {
                animated: !animationsDisabled,
                options
            }, mode);
        } else if (this.datasetElementType) {
            delete meta.dataset;
            this.datasetElementType = false;
        }
        this.updateElements(points, start, count, mode);
    }
    addElements() {
        const { showLine  } = this.options;
        if (!this.datasetElementType && showLine) {
            this.datasetElementType = this.chart.registry.getElement('line');
        }
        super.addElements();
    }
    updateElements(points, start, count, mode) {
        const reset = mode === 'reset';
        const { iScale , vScale , _stacked , _dataset  } = this._cachedMeta;
        const firstOpts = this.resolveDataElementOptions(start, mode);
        const sharedOptions = this.getSharedOptions(firstOpts);
        const includeOptions = this.includeOptions(mode, sharedOptions);
        const iAxis = iScale.axis;
        const vAxis = vScale.axis;
        const { spanGaps , segment  } = this.options;
        const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
        const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';
        let prevParsed = start > 0 && this.getParsed(start - 1);
        for(let i = start; i < start + count; ++i){
            const point = points[i];
            const parsed = this.getParsed(i);
            const properties = directUpdate ? point : {};
            const nullData = isNullOrUndef(parsed[vAxis]);
            const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
            const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
            properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
            properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
            if (segment) {
                properties.parsed = parsed;
                properties.raw = _dataset.data[i];
            }
            if (includeOptions) {
                properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
            }
            if (!directUpdate) {
                this.updateElement(point, i, properties, mode);
            }
            prevParsed = parsed;
        }
        this.updateSharedOptions(sharedOptions, mode, firstOpts);
    }
 getMaxOverflow() {
        const meta = this._cachedMeta;
        const data = meta.data || [];
        if (!this.options.showLine) {
            let max = 0;
            for(let i = data.length - 1; i >= 0; --i){
                max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);
            }
            return max > 0 && max;
        }
        const dataset = meta.dataset;
        const border = dataset.options && dataset.options.borderWidth || 0;
        if (!data.length) {
            return border;
        }
        const firstPoint = data[0].size(this.resolveDataElementOptions(0));
        const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));
        return Math.max(border, firstPoint, lastPoint) / 2;
    }
}

var controllers = /*#__PURE__*/Object.freeze({
__proto__: null,
BarController: BarController,
BubbleController: BubbleController,
DoughnutController: DoughnutController,
LineController: LineController,
PieController: PieController,
PolarAreaController: PolarAreaController,
RadarController: RadarController,
ScatterController: ScatterController
});

/**
 * @namespace Chart._adapters
 * @since 2.8.0
 * @private
 */ function abstract() {
    throw new Error('This method is not implemented: Check that a complete date adapter is provided.');
}
/**
 * Date adapter (current used by the time scale)
 * @namespace Chart._adapters._date
 * @memberof Chart._adapters
 * @private
 */ class DateAdapterBase {
    /**
   * Override default date adapter methods.
   * Accepts type parameter to define options type.
   * @example
   * Chart._adapters._date.override<{myAdapterOption: string}>({
   *   init() {
   *     console.log(this.options.myAdapterOption);
   *   }
   * })
   */ static override(members) {
        Object.assign(DateAdapterBase.prototype, members);
    }
    options;
    constructor(options){
        this.options = options || {};
    }
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    init() {}
    formats() {
        return abstract();
    }
    parse() {
        return abstract();
    }
    format() {
        return abstract();
    }
    add() {
        return abstract();
    }
    diff() {
        return abstract();
    }
    startOf() {
        return abstract();
    }
    endOf() {
        return abstract();
    }
}
var adapters = {
    _date: DateAdapterBase
};

function binarySearch(metaset, axis, value, intersect) {
    const { controller , data , _sorted  } = metaset;
    const iScale = controller._cachedMeta.iScale;
    const spanGaps = metaset.dataset ? metaset.dataset.options ? metaset.dataset.options.spanGaps : null : null;
    if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {
        const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;
        if (!intersect) {
            const result = lookupMethod(data, axis, value);
            if (spanGaps) {
                const { vScale  } = controller._cachedMeta;
                const { _parsed  } = metaset;
                const distanceToDefinedLo = _parsed.slice(0, result.lo + 1).reverse().findIndex((point)=>!isNullOrUndef(point[vScale.axis]));
                result.lo -= Math.max(0, distanceToDefinedLo);
                const distanceToDefinedHi = _parsed.slice(result.hi).findIndex((point)=>!isNullOrUndef(point[vScale.axis]));
                result.hi += Math.max(0, distanceToDefinedHi);
            }
            return result;
        } else if (controller._sharedOptions) {
            const el = data[0];
            const range = typeof el.getRange === 'function' && el.getRange(axis);
            if (range) {
                const start = lookupMethod(data, axis, value - range);
                const end = lookupMethod(data, axis, value + range);
                return {
                    lo: start.lo,
                    hi: end.hi
                };
            }
        }
    }
    return {
        lo: 0,
        hi: data.length - 1
    };
}
 function evaluateInteractionItems(chart, axis, position, handler, intersect) {
    const metasets = chart.getSortedVisibleDatasetMetas();
    const value = position[axis];
    for(let i = 0, ilen = metasets.length; i < ilen; ++i){
        const { index , data  } = metasets[i];
        const { lo , hi  } = binarySearch(metasets[i], axis, value, intersect);
        for(let j = lo; j <= hi; ++j){
            const element = data[j];
            if (!element.skip) {
                handler(element, index, j);
            }
        }
    }
}
 function getDistanceMetricForAxis(axis) {
    const useX = axis.indexOf('x') !== -1;
    const useY = axis.indexOf('y') !== -1;
    return function(pt1, pt2) {
        const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
        const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
        return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
    };
}
 function getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) {
    const items = [];
    if (!includeInvisible && !chart.isPointInArea(position)) {
        return items;
    }
    const evaluationFunc = function(element, datasetIndex, index) {
        if (!includeInvisible && !_isPointInArea(element, chart.chartArea, 0)) {
            return;
        }
        if (element.inRange(position.x, position.y, useFinalPosition)) {
            items.push({
                element,
                datasetIndex,
                index
            });
        }
    };
    evaluateInteractionItems(chart, axis, position, evaluationFunc, true);
    return items;
}
 function getNearestRadialItems(chart, position, axis, useFinalPosition) {
    let items = [];
    function evaluationFunc(element, datasetIndex, index) {
        const { startAngle , endAngle  } = element.getProps([
            'startAngle',
            'endAngle'
        ], useFinalPosition);
        const { angle  } = getAngleFromPoint(element, {
            x: position.x,
            y: position.y
        });
        if (_angleBetween(angle, startAngle, endAngle)) {
            items.push({
                element,
                datasetIndex,
                index
            });
        }
    }
    evaluateInteractionItems(chart, axis, position, evaluationFunc);
    return items;
}
 function getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {
    let items = [];
    const distanceMetric = getDistanceMetricForAxis(axis);
    let minDistance = Number.POSITIVE_INFINITY;
    function evaluationFunc(element, datasetIndex, index) {
        const inRange = element.inRange(position.x, position.y, useFinalPosition);
        if (intersect && !inRange) {
            return;
        }
        const center = element.getCenterPoint(useFinalPosition);
        const pointInArea = !!includeInvisible || chart.isPointInArea(center);
        if (!pointInArea && !inRange) {
            return;
        }
        const distance = distanceMetric(position, center);
        if (distance < minDistance) {
            items = [
                {
                    element,
                    datasetIndex,
                    index
                }
            ];
            minDistance = distance;
        } else if (distance === minDistance) {
            items.push({
                element,
                datasetIndex,
                index
            });
        }
    }
    evaluateInteractionItems(chart, axis, position, evaluationFunc);
    return items;
}
 function getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {
    if (!includeInvisible && !chart.isPointInArea(position)) {
        return [];
    }
    return axis === 'r' && !intersect ? getNearestRadialItems(chart, position, axis, useFinalPosition) : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible);
}
 function getAxisItems(chart, position, axis, intersect, useFinalPosition) {
    const items = [];
    const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';
    let intersectsItem = false;
    evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index)=>{
        if (element[rangeMethod] && element[rangeMethod](position[axis], useFinalPosition)) {
            items.push({
                element,
                datasetIndex,
                index
            });
            intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition);
        }
    });
    if (intersect && !intersectsItem) {
        return [];
    }
    return items;
}
 var Interaction = {
    evaluateInteractionItems,
    modes: {
 index (chart, e, options, useFinalPosition) {
            const position = getRelativePosition(e, chart);
            const axis = options.axis || 'x';
            const includeInvisible = options.includeInvisible || false;
            const items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);
            const elements = [];
            if (!items.length) {
                return [];
            }
            chart.getSortedVisibleDatasetMetas().forEach((meta)=>{
                const index = items[0].index;
                const element = meta.data[index];
                if (element && !element.skip) {
                    elements.push({
                        element,
                        datasetIndex: meta.index,
                        index
                    });
                }
            });
            return elements;
        },
 dataset (chart, e, options, useFinalPosition) {
            const position = getRelativePosition(e, chart);
            const axis = options.axis || 'xy';
            const includeInvisible = options.includeInvisible || false;
            let items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);
            if (items.length > 0) {
                const datasetIndex = items[0].datasetIndex;
                const data = chart.getDatasetMeta(datasetIndex).data;
                items = [];
                for(let i = 0; i < data.length; ++i){
                    items.push({
                        element: data[i],
                        datasetIndex,
                        index: i
                    });
                }
            }
            return items;
        },
 point (chart, e, options, useFinalPosition) {
            const position = getRelativePosition(e, chart);
            const axis = options.axis || 'xy';
            const includeInvisible = options.includeInvisible || false;
            return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible);
        },
 nearest (chart, e, options, useFinalPosition) {
            const position = getRelativePosition(e, chart);
            const axis = options.axis || 'xy';
            const includeInvisible = options.includeInvisible || false;
            return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible);
        },
 x (chart, e, options, useFinalPosition) {
            const position = getRelativePosition(e, chart);
            return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition);
        },
 y (chart, e, options, useFinalPosition) {
            const position = getRelativePosition(e, chart);
            return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition);
        }
    }
};

const STATIC_POSITIONS = [
    'left',
    'top',
    'right',
    'bottom'
];
function filterByPosition(array, position) {
    return array.filter((v)=>v.pos === position);
}
function filterDynamicPositionByAxis(array, axis) {
    return array.filter((v)=>STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);
}
function sortByWeight(array, reverse) {
    return array.sort((a, b)=>{
        const v0 = reverse ? b : a;
        const v1 = reverse ? a : b;
        return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight;
    });
}
function wrapBoxes(boxes) {
    const layoutBoxes = [];
    let i, ilen, box, pos, stack, stackWeight;
    for(i = 0, ilen = (boxes || []).length; i < ilen; ++i){
        box = boxes[i];
        ({ position: pos , options: { stack , stackWeight =1  }  } = box);
        layoutBoxes.push({
            index: i,
            box,
            pos,
            horizontal: box.isHorizontal(),
            weight: box.weight,
            stack: stack && pos + stack,
            stackWeight
        });
    }
    return layoutBoxes;
}
function buildStacks(layouts) {
    const stacks = {};
    for (const wrap of layouts){
        const { stack , pos , stackWeight  } = wrap;
        if (!stack || !STATIC_POSITIONS.includes(pos)) {
            continue;
        }
        const _stack = stacks[stack] || (stacks[stack] = {
            count: 0,
            placed: 0,
            weight: 0,
            size: 0
        });
        _stack.count++;
        _stack.weight += stackWeight;
    }
    return stacks;
}
 function setLayoutDims(layouts, params) {
    const stacks = buildStacks(layouts);
    const { vBoxMaxWidth , hBoxMaxHeight  } = params;
    let i, ilen, layout;
    for(i = 0, ilen = layouts.length; i < ilen; ++i){
        layout = layouts[i];
        const { fullSize  } = layout.box;
        const stack = stacks[layout.stack];
        const factor = stack && layout.stackWeight / stack.weight;
        if (layout.horizontal) {
            layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;
            layout.height = hBoxMaxHeight;
        } else {
            layout.width = vBoxMaxWidth;
            layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;
        }
    }
    return stacks;
}
function buildLayoutBoxes(boxes) {
    const layoutBoxes = wrapBoxes(boxes);
    const fullSize = sortByWeight(layoutBoxes.filter((wrap)=>wrap.box.fullSize), true);
    const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
    const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
    const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
    const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
    const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');
    const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');
    return {
        fullSize,
        leftAndTop: left.concat(top),
        rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),
        chartArea: filterByPosition(layoutBoxes, 'chartArea'),
        vertical: left.concat(right).concat(centerVertical),
        horizontal: top.concat(bottom).concat(centerHorizontal)
    };
}
function getCombinedMax(maxPadding, chartArea, a, b) {
    return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
}
function updateMaxPadding(maxPadding, boxPadding) {
    maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
    maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
    maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
    maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
}
function updateDims(chartArea, params, layout, stacks) {
    const { pos , box  } = layout;
    const maxPadding = chartArea.maxPadding;
    if (!isObject(pos)) {
        if (layout.size) {
            chartArea[pos] -= layout.size;
        }
        const stack = stacks[layout.stack] || {
            size: 0,
            count: 1
        };
        stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);
        layout.size = stack.size / stack.count;
        chartArea[pos] += layout.size;
    }
    if (box.getPadding) {
        updateMaxPadding(maxPadding, box.getPadding());
    }
    const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));
    const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));
    const widthChanged = newWidth !== chartArea.w;
    const heightChanged = newHeight !== chartArea.h;
    chartArea.w = newWidth;
    chartArea.h = newHeight;
    return layout.horizontal ? {
        same: widthChanged,
        other: heightChanged
    } : {
        same: heightChanged,
        other: widthChanged
    };
}
function handleMaxPadding(chartArea) {
    const maxPadding = chartArea.maxPadding;
    function updatePos(pos) {
        const change = Math.max(maxPadding[pos] - chartArea[pos], 0);
        chartArea[pos] += change;
        return change;
    }
    chartArea.y += updatePos('top');
    chartArea.x += updatePos('left');
    updatePos('right');
    updatePos('bottom');
}
function getMargins(horizontal, chartArea) {
    const maxPadding = chartArea.maxPadding;
    function marginForPositions(positions) {
        const margin = {
            left: 0,
            top: 0,
            right: 0,
            bottom: 0
        };
        positions.forEach((pos)=>{
            margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
        });
        return margin;
    }
    return horizontal ? marginForPositions([
        'left',
        'right'
    ]) : marginForPositions([
        'top',
        'bottom'
    ]);
}
function fitBoxes(boxes, chartArea, params, stacks) {
    const refitBoxes = [];
    let i, ilen, layout, box, refit, changed;
    for(i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i){
        layout = boxes[i];
        box = layout.box;
        box.update(layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea));
        const { same , other  } = updateDims(chartArea, params, layout, stacks);
        refit |= same && refitBoxes.length;
        changed = changed || other;
        if (!box.fullSize) {
            refitBoxes.push(layout);
        }
    }
    return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;
}
function setBoxDims(box, left, top, width, height) {
    box.top = top;
    box.left = left;
    box.right = left + width;
    box.bottom = top + height;
    box.width = width;
    box.height = height;
}
function placeBoxes(boxes, chartArea, params, stacks) {
    const userPadding = params.padding;
    let { x , y  } = chartArea;
    for (const layout of boxes){
        const box = layout.box;
        const stack = stacks[layout.stack] || {
            count: 1,
            placed: 0,
            weight: 1
        };
        const weight = layout.stackWeight / stack.weight || 1;
        if (layout.horizontal) {
            const width = chartArea.w * weight;
            const height = stack.size || box.height;
            if (defined(stack.start)) {
                y = stack.start;
            }
            if (box.fullSize) {
                setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);
            } else {
                setBoxDims(box, chartArea.left + stack.placed, y, width, height);
            }
            stack.start = y;
            stack.placed += width;
            y = box.bottom;
        } else {
            const height = chartArea.h * weight;
            const width = stack.size || box.width;
            if (defined(stack.start)) {
                x = stack.start;
            }
            if (box.fullSize) {
                setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);
            } else {
                setBoxDims(box, x, chartArea.top + stack.placed, width, height);
            }
            stack.start = x;
            stack.placed += height;
            x = box.right;
        }
    }
    chartArea.x = x;
    chartArea.y = y;
}
var layouts = {
 addBox (chart, item) {
        if (!chart.boxes) {
            chart.boxes = [];
        }
        item.fullSize = item.fullSize || false;
        item.position = item.position || 'top';
        item.weight = item.weight || 0;
        item._layers = item._layers || function() {
            return [
                {
                    z: 0,
                    draw (chartArea) {
                        item.draw(chartArea);
                    }
                }
            ];
        };
        chart.boxes.push(item);
    },
 removeBox (chart, layoutItem) {
        const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
        if (index !== -1) {
            chart.boxes.splice(index, 1);
        }
    },
 configure (chart, item, options) {
        item.fullSize = options.fullSize;
        item.position = options.position;
        item.weight = options.weight;
    },
 update (chart, width, height, minPadding) {
        if (!chart) {
            return;
        }
        const padding = toPadding(chart.options.layout.padding);
        const availableWidth = Math.max(width - padding.width, 0);
        const availableHeight = Math.max(height - padding.height, 0);
        const boxes = buildLayoutBoxes(chart.boxes);
        const verticalBoxes = boxes.vertical;
        const horizontalBoxes = boxes.horizontal;
        each(chart.boxes, (box)=>{
            if (typeof box.beforeLayout === 'function') {
                box.beforeLayout();
            }
        });
        const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap)=>wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;
        const params = Object.freeze({
            outerWidth: width,
            outerHeight: height,
            padding,
            availableWidth,
            availableHeight,
            vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,
            hBoxMaxHeight: availableHeight / 2
        });
        const maxPadding = Object.assign({}, padding);
        updateMaxPadding(maxPadding, toPadding(minPadding));
        const chartArea = Object.assign({
            maxPadding,
            w: availableWidth,
            h: availableHeight,
            x: padding.left,
            y: padding.top
        }, padding);
        const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
        fitBoxes(boxes.fullSize, chartArea, params, stacks);
        fitBoxes(verticalBoxes, chartArea, params, stacks);
        if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {
            fitBoxes(verticalBoxes, chartArea, params, stacks);
        }
        handleMaxPadding(chartArea);
        placeBoxes(boxes.leftAndTop, chartArea, params, stacks);
        chartArea.x += chartArea.w;
        chartArea.y += chartArea.h;
        placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);
        chart.chartArea = {
            left: chartArea.left,
            top: chartArea.top,
            right: chartArea.left + chartArea.w,
            bottom: chartArea.top + chartArea.h,
            height: chartArea.h,
            width: chartArea.w
        };
        each(boxes.chartArea, (layout)=>{
            const box = layout.box;
            Object.assign(box, chart.chartArea);
            box.update(chartArea.w, chartArea.h, {
                left: 0,
                top: 0,
                right: 0,
                bottom: 0
            });
        });
    }
};

class BasePlatform {
 acquireContext(canvas, aspectRatio) {}
 releaseContext(context) {
        return false;
    }
 addEventListener(chart, type, listener) {}
 removeEventListener(chart, type, listener) {}
 getDevicePixelRatio() {
        return 1;
    }
 getMaximumSize(element, width, height, aspectRatio) {
        width = Math.max(0, width || element.width);
        height = height || element.height;
        return {
            width,
            height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)
        };
    }
 isAttached(canvas) {
        return true;
    }
 updateConfig(config) {
    }
}

class BasicPlatform extends BasePlatform {
    acquireContext(item) {
        return item && item.getContext && item.getContext('2d') || null;
    }
    updateConfig(config) {
        config.options.animation = false;
    }
}

const EXPANDO_KEY = '$chartjs';
 const EVENT_TYPES = {
    touchstart: 'mousedown',
    touchmove: 'mousemove',
    touchend: 'mouseup',
    pointerenter: 'mouseenter',
    pointerdown: 'mousedown',
    pointermove: 'mousemove',
    pointerup: 'mouseup',
    pointerleave: 'mouseout',
    pointerout: 'mouseout'
};
const isNullOrEmpty = (value)=>value === null || value === '';
 function initCanvas(canvas, aspectRatio) {
    const style = canvas.style;
    const renderHeight = canvas.getAttribute('height');
    const renderWidth = canvas.getAttribute('width');
    canvas[EXPANDO_KEY] = {
        initial: {
            height: renderHeight,
            width: renderWidth,
            style: {
                display: style.display,
                height: style.height,
                width: style.width
            }
        }
    };
    style.display = style.display || 'block';
    style.boxSizing = style.boxSizing || 'border-box';
    if (isNullOrEmpty(renderWidth)) {
        const displayWidth = readUsedSize(canvas, 'width');
        if (displayWidth !== undefined) {
            canvas.width = displayWidth;
        }
    }
    if (isNullOrEmpty(renderHeight)) {
        if (canvas.style.height === '') {
            canvas.height = canvas.width / (aspectRatio || 2);
        } else {
            const displayHeight = readUsedSize(canvas, 'height');
            if (displayHeight !== undefined) {
                canvas.height = displayHeight;
            }
        }
    }
    return canvas;
}
const eventListenerOptions = supportsEventListenerOptions ? {
    passive: true
} : false;
function addListener(node, type, listener) {
    if (node) {
        node.addEventListener(type, listener, eventListenerOptions);
    }
}
function removeListener(chart, type, listener) {
    if (chart && chart.canvas) {
        chart.canvas.removeEventListener(type, listener, eventListenerOptions);
    }
}
function fromNativeEvent(event, chart) {
    const type = EVENT_TYPES[event.type] || event.type;
    const { x , y  } = getRelativePosition(event, chart);
    return {
        type,
        chart,
        native: event,
        x: x !== undefined ? x : null,
        y: y !== undefined ? y : null
    };
}
function nodeListContains(nodeList, canvas) {
    for (const node of nodeList){
        if (node === canvas || node.contains(canvas)) {
            return true;
        }
    }
}
function createAttachObserver(chart, type, listener) {
    const canvas = chart.canvas;
    const observer = new MutationObserver((entries)=>{
        let trigger = false;
        for (const entry of entries){
            trigger = trigger || nodeListContains(entry.addedNodes, canvas);
            trigger = trigger && !nodeListContains(entry.removedNodes, canvas);
        }
        if (trigger) {
            listener();
        }
    });
    observer.observe(document, {
        childList: true,
        subtree: true
    });
    return observer;
}
function createDetachObserver(chart, type, listener) {
    const canvas = chart.canvas;
    const observer = new MutationObserver((entries)=>{
        let trigger = false;
        for (const entry of entries){
            trigger = trigger || nodeListContains(entry.removedNodes, canvas);
            trigger = trigger && !nodeListContains(entry.addedNodes, canvas);
        }
        if (trigger) {
            listener();
        }
    });
    observer.observe(document, {
        childList: true,
        subtree: true
    });
    return observer;
}
const drpListeningCharts = new Map();
let oldDevicePixelRatio = 0;
function onWindowResize() {
    const dpr = window.devicePixelRatio;
    if (dpr === oldDevicePixelRatio) {
        return;
    }
    oldDevicePixelRatio = dpr;
    drpListeningCharts.forEach((resize, chart)=>{
        if (chart.currentDevicePixelRatio !== dpr) {
            resize();
        }
    });
}
function listenDevicePixelRatioChanges(chart, resize) {
    if (!drpListeningCharts.size) {
        window.addEventListener('resize', onWindowResize);
    }
    drpListeningCharts.set(chart, resize);
}
function unlistenDevicePixelRatioChanges(chart) {
    drpListeningCharts.delete(chart);
    if (!drpListeningCharts.size) {
        window.removeEventListener('resize', onWindowResize);
    }
}
function createResizeObserver(chart, type, listener) {
    const canvas = chart.canvas;
    const container = canvas && _getParentNode(canvas);
    if (!container) {
        return;
    }
    const resize = throttled((width, height)=>{
        const w = container.clientWidth;
        listener(width, height);
        if (w < container.clientWidth) {
            listener();
        }
    }, window);
    const observer = new ResizeObserver((entries)=>{
        const entry = entries[0];
        const width = entry.contentRect.width;
        const height = entry.contentRect.height;
        if (width === 0 && height === 0) {
            return;
        }
        resize(width, height);
    });
    observer.observe(container);
    listenDevicePixelRatioChanges(chart, resize);
    return observer;
}
function releaseObserver(chart, type, observer) {
    if (observer) {
        observer.disconnect();
    }
    if (type === 'resize') {
        unlistenDevicePixelRatioChanges(chart);
    }
}
function createProxyAndListen(chart, type, listener) {
    const canvas = chart.canvas;
    const proxy = throttled((event)=>{
        if (chart.ctx !== null) {
            listener(fromNativeEvent(event, chart));
        }
    }, chart);
    addListener(canvas, type, proxy);
    return proxy;
}
 class DomPlatform extends BasePlatform {
 acquireContext(canvas, aspectRatio) {
        const context = canvas && canvas.getContext && canvas.getContext('2d');
        if (context && context.canvas === canvas) {
            initCanvas(canvas, aspectRatio);
            return context;
        }
        return null;
    }
 releaseContext(context) {
        const canvas = context.canvas;
        if (!canvas[EXPANDO_KEY]) {
            return false;
        }
        const initial = canvas[EXPANDO_KEY].initial;
        [
            'height',
            'width'
        ].forEach((prop)=>{
            const value = initial[prop];
            if (isNullOrUndef(value)) {
                canvas.removeAttribute(prop);
            } else {
                canvas.setAttribute(prop, value);
            }
        });
        const style = initial.style || {};
        Object.keys(style).forEach((key)=>{
            canvas.style[key] = style[key];
        });
        canvas.width = canvas.width;
        delete canvas[EXPANDO_KEY];
        return true;
    }
 addEventListener(chart, type, listener) {
        this.removeEventListener(chart, type);
        const proxies = chart.$proxies || (chart.$proxies = {});
        const handlers = {
            attach: createAttachObserver,
            detach: createDetachObserver,
            resize: createResizeObserver
        };
        const handler = handlers[type] || createProxyAndListen;
        proxies[type] = handler(chart, type, listener);
    }
 removeEventListener(chart, type) {
        const proxies = chart.$proxies || (chart.$proxies = {});
        const proxy = proxies[type];
        if (!proxy) {
            return;
        }
        const handlers = {
            attach: releaseObserver,
            detach: releaseObserver,
            resize: releaseObserver
        };
        const handler = handlers[type] || removeListener;
        handler(chart, type, proxy);
        proxies[type] = undefined;
    }
    getDevicePixelRatio() {
        return window.devicePixelRatio;
    }
 getMaximumSize(canvas, width, height, aspectRatio) {
        return getMaximumSize(canvas, width, height, aspectRatio);
    }
 isAttached(canvas) {
        const container = canvas && _getParentNode(canvas);
        return !!(container && container.isConnected);
    }
}

function _detectPlatform(canvas) {
    if (!_isDomSupported() || typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {
        return BasicPlatform;
    }
    return DomPlatform;
}

let Element$1 = class Element {
    static defaults = {};
    static defaultRoutes = undefined;
    x;
    y;
    active = false;
    options;
    $animations;
    tooltipPosition(useFinalPosition) {
        const { x , y  } = this.getProps([
            'x',
            'y'
        ], useFinalPosition);
        return {
            x,
            y
        };
    }
    hasValue() {
        return isNumber(this.x) && isNumber(this.y);
    }
    getProps(props, final) {
        const anims = this.$animations;
        if (!final || !anims) {
            // let's not create an object, if not needed
            return this;
        }
        const ret = {};
        props.forEach((prop)=>{
            ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop];
        });
        return ret;
    }
};

function autoSkip(scale, ticks) {
    const tickOpts = scale.options.ticks;
    const determinedMaxTicks = determineMaxTicks(scale);
    const ticksLimit = Math.min(tickOpts.maxTicksLimit || determinedMaxTicks, determinedMaxTicks);
    const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
    const numMajorIndices = majorIndices.length;
    const first = majorIndices[0];
    const last = majorIndices[numMajorIndices - 1];
    const newTicks = [];
    if (numMajorIndices > ticksLimit) {
        skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
        return newTicks;
    }
    const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
    if (numMajorIndices > 0) {
        let i, ilen;
        const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
        skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
        for(i = 0, ilen = numMajorIndices - 1; i < ilen; i++){
            skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
        }
        skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
        return newTicks;
    }
    skip(ticks, newTicks, spacing);
    return newTicks;
}
function determineMaxTicks(scale) {
    const offset = scale.options.offset;
    const tickLength = scale._tickSize();
    const maxScale = scale._length / tickLength + (offset ? 0 : 1);
    const maxChart = scale._maxLength / tickLength;
    return Math.floor(Math.min(maxScale, maxChart));
}
 function calculateSpacing(majorIndices, ticks, ticksLimit) {
    const evenMajorSpacing = getEvenSpacing(majorIndices);
    const spacing = ticks.length / ticksLimit;
    if (!evenMajorSpacing) {
        return Math.max(spacing, 1);
    }
    const factors = _factorize(evenMajorSpacing);
    for(let i = 0, ilen = factors.length - 1; i < ilen; i++){
        const factor = factors[i];
        if (factor > spacing) {
            return factor;
        }
    }
    return Math.max(spacing, 1);
}
 function getMajorIndices(ticks) {
    const result = [];
    let i, ilen;
    for(i = 0, ilen = ticks.length; i < ilen; i++){
        if (ticks[i].major) {
            result.push(i);
        }
    }
    return result;
}
 function skipMajors(ticks, newTicks, majorIndices, spacing) {
    let count = 0;
    let next = majorIndices[0];
    let i;
    spacing = Math.ceil(spacing);
    for(i = 0; i < ticks.length; i++){
        if (i === next) {
            newTicks.push(ticks[i]);
            count++;
            next = majorIndices[count * spacing];
        }
    }
}
 function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
    const start = valueOrDefault(majorStart, 0);
    const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);
    let count = 0;
    let length, i, next;
    spacing = Math.ceil(spacing);
    if (majorEnd) {
        length = majorEnd - majorStart;
        spacing = length / Math.floor(length / spacing);
    }
    next = start;
    while(next < 0){
        count++;
        next = Math.round(start + count * spacing);
    }
    for(i = Math.max(start, 0); i < end; i++){
        if (i === next) {
            newTicks.push(ticks[i]);
            count++;
            next = Math.round(start + count * spacing);
        }
    }
}
 function getEvenSpacing(arr) {
    const len = arr.length;
    let i, diff;
    if (len < 2) {
        return false;
    }
    for(diff = arr[0], i = 1; i < len; ++i){
        if (arr[i] - arr[i - 1] !== diff) {
            return false;
        }
    }
    return diff;
}

const reverseAlign = (align)=>align === 'left' ? 'right' : align === 'right' ? 'left' : align;
const offsetFromEdge = (scale, edge, offset)=>edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;
const getTicksLimit = (ticksLength, maxTicksLimit)=>Math.min(maxTicksLimit || ticksLength, ticksLength);
 function sample(arr, numItems) {
    const result = [];
    const increment = arr.length / numItems;
    const len = arr.length;
    let i = 0;
    for(; i < len; i += increment){
        result.push(arr[Math.floor(i)]);
    }
    return result;
}
 function getPixelForGridLine(scale, index, offsetGridLines) {
    const length = scale.ticks.length;
    const validIndex = Math.min(index, length - 1);
    const start = scale._startPixel;
    const end = scale._endPixel;
    const epsilon = 1e-6;
    let lineValue = scale.getPixelForTick(validIndex);
    let offset;
    if (offsetGridLines) {
        if (length === 1) {
            offset = Math.max(lineValue - start, end - lineValue);
        } else if (index === 0) {
            offset = (scale.getPixelForTick(1) - lineValue) / 2;
        } else {
            offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
        }
        lineValue += validIndex < index ? offset : -offset;
        if (lineValue < start - epsilon || lineValue > end + epsilon) {
            return;
        }
    }
    return lineValue;
}
 function garbageCollect(caches, length) {
    each(caches, (cache)=>{
        const gc = cache.gc;
        const gcLen = gc.length / 2;
        let i;
        if (gcLen > length) {
            for(i = 0; i < gcLen; ++i){
                delete cache.data[gc[i]];
            }
            gc.splice(0, gcLen);
        }
    });
}
 function getTickMarkLength(options) {
    return options.drawTicks ? options.tickLength : 0;
}
 function getTitleHeight(options, fallback) {
    if (!options.display) {
        return 0;
    }
    const font = toFont(options.font, fallback);
    const padding = toPadding(options.padding);
    const lines = isArray(options.text) ? options.text.length : 1;
    return lines * font.lineHeight + padding.height;
}
function createScaleContext(parent, scale) {
    return createContext(parent, {
        scale,
        type: 'scale'
    });
}
function createTickContext(parent, index, tick) {
    return createContext(parent, {
        tick,
        index,
        type: 'tick'
    });
}
function titleAlign(align, position, reverse) {
     let ret = _toLeftRightCenter(align);
    if (reverse && position !== 'right' || !reverse && position === 'right') {
        ret = reverseAlign(ret);
    }
    return ret;
}
function titleArgs(scale, offset, position, align) {
    const { top , left , bottom , right , chart  } = scale;
    const { chartArea , scales  } = chart;
    let rotation = 0;
    let maxWidth, titleX, titleY;
    const height = bottom - top;
    const width = right - left;
    if (scale.isHorizontal()) {
        titleX = _alignStartEnd(align, left, right);
        if (isObject(position)) {
            const positionAxisID = Object.keys(position)[0];
            const value = position[positionAxisID];
            titleY = scales[positionAxisID].getPixelForValue(value) + height - offset;
        } else if (position === 'center') {
            titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset;
        } else {
            titleY = offsetFromEdge(scale, position, offset);
        }
        maxWidth = right - left;
    } else {
        if (isObject(position)) {
            const positionAxisID = Object.keys(position)[0];
            const value = position[positionAxisID];
            titleX = scales[positionAxisID].getPixelForValue(value) - width + offset;
        } else if (position === 'center') {
            titleX = (chartArea.left + chartArea.right) / 2 - width + offset;
        } else {
            titleX = offsetFromEdge(scale, position, offset);
        }
        titleY = _alignStartEnd(align, bottom, top);
        rotation = position === 'left' ? -HALF_PI : HALF_PI;
    }
    return {
        titleX,
        titleY,
        maxWidth,
        rotation
    };
}
class Scale extends Element$1 {
    constructor(cfg){
        super();
         this.id = cfg.id;
         this.type = cfg.type;
         this.options = undefined;
         this.ctx = cfg.ctx;
         this.chart = cfg.chart;
         this.top = undefined;
         this.bottom = undefined;
         this.left = undefined;
         this.right = undefined;
         this.width = undefined;
         this.height = undefined;
        this._margins = {
            left: 0,
            right: 0,
            top: 0,
            bottom: 0
        };
         this.maxWidth = undefined;
         this.maxHeight = undefined;
         this.paddingTop = undefined;
         this.paddingBottom = undefined;
         this.paddingLeft = undefined;
         this.paddingRight = undefined;
         this.axis = undefined;
         this.labelRotation = undefined;
        this.min = undefined;
        this.max = undefined;
        this._range = undefined;
         this.ticks = [];
         this._gridLineItems = null;
         this._labelItems = null;
         this._labelSizes = null;
        this._length = 0;
        this._maxLength = 0;
        this._longestTextCache = {};
         this._startPixel = undefined;
         this._endPixel = undefined;
        this._reversePixels = false;
        this._userMax = undefined;
        this._userMin = undefined;
        this._suggestedMax = undefined;
        this._suggestedMin = undefined;
        this._ticksLength = 0;
        this._borderValue = 0;
        this._cache = {};
        this._dataLimitsCached = false;
        this.$context = undefined;
    }
 init(options) {
        this.options = options.setContext(this.getContext());
        this.axis = options.axis;
        this._userMin = this.parse(options.min);
        this._userMax = this.parse(options.max);
        this._suggestedMin = this.parse(options.suggestedMin);
        this._suggestedMax = this.parse(options.suggestedMax);
    }
 parse(raw, index) {
        return raw;
    }
 getUserBounds() {
        let { _userMin , _userMax , _suggestedMin , _suggestedMax  } = this;
        _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
        _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
        _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
        _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
        return {
            min: finiteOrDefault(_userMin, _suggestedMin),
            max: finiteOrDefault(_userMax, _suggestedMax),
            minDefined: isNumberFinite(_userMin),
            maxDefined: isNumberFinite(_userMax)
        };
    }
 getMinMax(canStack) {
        let { min , max , minDefined , maxDefined  } = this.getUserBounds();
        let range;
        if (minDefined && maxDefined) {
            return {
                min,
                max
            };
        }
        const metas = this.getMatchingVisibleMetas();
        for(let i = 0, ilen = metas.length; i < ilen; ++i){
            range = metas[i].controller.getMinMax(this, canStack);
            if (!minDefined) {
                min = Math.min(min, range.min);
            }
            if (!maxDefined) {
                max = Math.max(max, range.max);
            }
        }
        min = maxDefined && min > max ? max : min;
        max = minDefined && min > max ? min : max;
        return {
            min: finiteOrDefault(min, finiteOrDefault(max, min)),
            max: finiteOrDefault(max, finiteOrDefault(min, max))
        };
    }
 getPadding() {
        return {
            left: this.paddingLeft || 0,
            top: this.paddingTop || 0,
            right: this.paddingRight || 0,
            bottom: this.paddingBottom || 0
        };
    }
 getTicks() {
        return this.ticks;
    }
 getLabels() {
        const data = this.chart.data;
        return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
    }
 getLabelItems(chartArea = this.chart.chartArea) {
        const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea));
        return items;
    }
    beforeLayout() {
        this._cache = {};
        this._dataLimitsCached = false;
    }
    beforeUpdate() {
        callback(this.options.beforeUpdate, [
            this
        ]);
    }
 update(maxWidth, maxHeight, margins) {
        const { beginAtZero , grace , ticks: tickOpts  } = this.options;
        const sampleSize = tickOpts.sampleSize;
        this.beforeUpdate();
        this.maxWidth = maxWidth;
        this.maxHeight = maxHeight;
        this._margins = margins = Object.assign({
            left: 0,
            right: 0,
            top: 0,
            bottom: 0
        }, margins);
        this.ticks = null;
        this._labelSizes = null;
        this._gridLineItems = null;
        this._labelItems = null;
        this.beforeSetDimensions();
        this.setDimensions();
        this.afterSetDimensions();
        this._maxLength = this.isHorizontal() ? this.width + margins.left + margins.right : this.height + margins.top + margins.bottom;
        if (!this._dataLimitsCached) {
            this.beforeDataLimits();
            this.determineDataLimits();
            this.afterDataLimits();
            this._range = _addGrace(this, grace, beginAtZero);
            this._dataLimitsCached = true;
        }
        this.beforeBuildTicks();
        this.ticks = this.buildTicks() || [];
        this.afterBuildTicks();
        const samplingEnabled = sampleSize < this.ticks.length;
        this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks);
        this.configure();
        this.beforeCalculateLabelRotation();
        this.calculateLabelRotation();
        this.afterCalculateLabelRotation();
        if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {
            this.ticks = autoSkip(this, this.ticks);
            this._labelSizes = null;
            this.afterAutoSkip();
        }
        if (samplingEnabled) {
            this._convertTicksToLabels(this.ticks);
        }
        this.beforeFit();
        this.fit();
        this.afterFit();
        this.afterUpdate();
    }
 configure() {
        let reversePixels = this.options.reverse;
        let startPixel, endPixel;
        if (this.isHorizontal()) {
            startPixel = this.left;
            endPixel = this.right;
        } else {
            startPixel = this.top;
            endPixel = this.bottom;
            reversePixels = !reversePixels;
        }
        this._startPixel = startPixel;
        this._endPixel = endPixel;
        this._reversePixels = reversePixels;
        this._length = endPixel - startPixel;
        this._alignToPixels = this.options.alignToPixels;
    }
    afterUpdate() {
        callback(this.options.afterUpdate, [
            this
        ]);
    }
    beforeSetDimensions() {
        callback(this.options.beforeSetDimensions, [
            this
        ]);
    }
    setDimensions() {
        if (this.isHorizontal()) {
            this.width = this.maxWidth;
            this.left = 0;
            this.right = this.width;
        } else {
            this.height = this.maxHeight;
            this.top = 0;
            this.bottom = this.height;
        }
        this.paddingLeft = 0;
        this.paddingTop = 0;
        this.paddingRight = 0;
        this.paddingBottom = 0;
    }
    afterSetDimensions() {
        callback(this.options.afterSetDimensions, [
            this
        ]);
    }
    _callHooks(name) {
        this.chart.notifyPlugins(name, this.getContext());
        callback(this.options[name], [
            this
        ]);
    }
    beforeDataLimits() {
        this._callHooks('beforeDataLimits');
    }
    determineDataLimits() {}
    afterDataLimits() {
        this._callHooks('afterDataLimits');
    }
    beforeBuildTicks() {
        this._callHooks('beforeBuildTicks');
    }
 buildTicks() {
        return [];
    }
    afterBuildTicks() {
        this._callHooks('afterBuildTicks');
    }
    beforeTickToLabelConversion() {
        callback(this.options.beforeTickToLabelConversion, [
            this
        ]);
    }
 generateTickLabels(ticks) {
        const tickOpts = this.options.ticks;
        let i, ilen, tick;
        for(i = 0, ilen = ticks.length; i < ilen; i++){
            tick = ticks[i];
            tick.label = callback(tickOpts.callback, [
                tick.value,
                i,
                ticks
            ], this);
        }
    }
    afterTickToLabelConversion() {
        callback(this.options.afterTickToLabelConversion, [
            this
        ]);
    }
    beforeCalculateLabelRotation() {
        callback(this.options.beforeCalculateLabelRotation, [
            this
        ]);
    }
    calculateLabelRotation() {
        const options = this.options;
        const tickOpts = options.ticks;
        const numTicks = getTicksLimit(this.ticks.length, options.ticks.maxTicksLimit);
        const minRotation = tickOpts.minRotation || 0;
        const maxRotation = tickOpts.maxRotation;
        let labelRotation = minRotation;
        let tickWidth, maxHeight, maxLabelDiagonal;
        if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) {
            this.labelRotation = minRotation;
            return;
        }
        const labelSizes = this._getLabelSizes();
        const maxLabelWidth = labelSizes.widest.width;
        const maxLabelHeight = labelSizes.highest.height;
        const maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth);
        tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1);
        if (maxLabelWidth + 6 > tickWidth) {
            tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
            maxHeight = this.maxHeight - getTickMarkLength(options.grid) - tickOpts.padding - getTitleHeight(options.title, this.chart.options.font);
            maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
            labelRotation = toDegrees(Math.min(Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)), Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))));
            labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
        }
        this.labelRotation = labelRotation;
    }
    afterCalculateLabelRotation() {
        callback(this.options.afterCalculateLabelRotation, [
            this
        ]);
    }
    afterAutoSkip() {}
    beforeFit() {
        callback(this.options.beforeFit, [
            this
        ]);
    }
    fit() {
        const minSize = {
            width: 0,
            height: 0
        };
        const { chart , options: { ticks: tickOpts , title: titleOpts , grid: gridOpts  }  } = this;
        const display = this._isVisible();
        const isHorizontal = this.isHorizontal();
        if (display) {
            const titleHeight = getTitleHeight(titleOpts, chart.options.font);
            if (isHorizontal) {
                minSize.width = this.maxWidth;
                minSize.height = getTickMarkLength(gridOpts) + titleHeight;
            } else {
                minSize.height = this.maxHeight;
                minSize.width = getTickMarkLength(gridOpts) + titleHeight;
            }
            if (tickOpts.display && this.ticks.length) {
                const { first , last , widest , highest  } = this._getLabelSizes();
                const tickPadding = tickOpts.padding * 2;
                const angleRadians = toRadians(this.labelRotation);
                const cos = Math.cos(angleRadians);
                const sin = Math.sin(angleRadians);
                if (isHorizontal) {
                    const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
                    minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding);
                } else {
                    const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
                    minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding);
                }
                this._calculatePadding(first, last, sin, cos);
            }
        }
        this._handleMargins();
        if (isHorizontal) {
            this.width = this._length = chart.width - this._margins.left - this._margins.right;
            this.height = minSize.height;
        } else {
            this.width = minSize.width;
            this.height = this._length = chart.height - this._margins.top - this._margins.bottom;
        }
    }
    _calculatePadding(first, last, sin, cos) {
        const { ticks: { align , padding  } , position  } = this.options;
        const isRotated = this.labelRotation !== 0;
        const labelsBelowTicks = position !== 'top' && this.axis === 'x';
        if (this.isHorizontal()) {
            const offsetLeft = this.getPixelForTick(0) - this.left;
            const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1);
            let paddingLeft = 0;
            let paddingRight = 0;
            if (isRotated) {
                if (labelsBelowTicks) {
                    paddingLeft = cos * first.width;
                    paddingRight = sin * last.height;
                } else {
                    paddingLeft = sin * first.height;
                    paddingRight = cos * last.width;
                }
            } else if (align === 'start') {
                paddingRight = last.width;
            } else if (align === 'end') {
                paddingLeft = first.width;
            } else if (align !== 'inner') {
                paddingLeft = first.width / 2;
                paddingRight = last.width / 2;
            }
            this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0);
            this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0);
        } else {
            let paddingTop = last.height / 2;
            let paddingBottom = first.height / 2;
            if (align === 'start') {
                paddingTop = 0;
                paddingBottom = first.height;
            } else if (align === 'end') {
                paddingTop = last.height;
                paddingBottom = 0;
            }
            this.paddingTop = paddingTop + padding;
            this.paddingBottom = paddingBottom + padding;
        }
    }
 _handleMargins() {
        if (this._margins) {
            this._margins.left = Math.max(this.paddingLeft, this._margins.left);
            this._margins.top = Math.max(this.paddingTop, this._margins.top);
            this._margins.right = Math.max(this.paddingRight, this._margins.right);
            this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom);
        }
    }
    afterFit() {
        callback(this.options.afterFit, [
            this
        ]);
    }
 isHorizontal() {
        const { axis , position  } = this.options;
        return position === 'top' || position === 'bottom' || axis === 'x';
    }
 isFullSize() {
        return this.options.fullSize;
    }
 _convertTicksToLabels(ticks) {
        this.beforeTickToLabelConversion();
        this.generateTickLabels(ticks);
        let i, ilen;
        for(i = 0, ilen = ticks.length; i < ilen; i++){
            if (isNullOrUndef(ticks[i].label)) {
                ticks.splice(i, 1);
                ilen--;
                i--;
            }
        }
        this.afterTickToLabelConversion();
    }
 _getLabelSizes() {
        let labelSizes = this._labelSizes;
        if (!labelSizes) {
            const sampleSize = this.options.ticks.sampleSize;
            let ticks = this.ticks;
            if (sampleSize < ticks.length) {
                ticks = sample(ticks, sampleSize);
            }
            this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length, this.options.ticks.maxTicksLimit);
        }
        return labelSizes;
    }
 _computeLabelSizes(ticks, length, maxTicksLimit) {
        const { ctx , _longestTextCache: caches  } = this;
        const widths = [];
        const heights = [];
        const increment = Math.floor(length / getTicksLimit(length, maxTicksLimit));
        let widestLabelSize = 0;
        let highestLabelSize = 0;
        let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
        for(i = 0; i < length; i += increment){
            label = ticks[i].label;
            tickFont = this._resolveTickFontOptions(i);
            ctx.font = fontString = tickFont.string;
            cache = caches[fontString] = caches[fontString] || {
                data: {},
                gc: []
            };
            lineHeight = tickFont.lineHeight;
            width = height = 0;
            if (!isNullOrUndef(label) && !isArray(label)) {
                width = _measureText(ctx, cache.data, cache.gc, width, label);
                height = lineHeight;
            } else if (isArray(label)) {
                for(j = 0, jlen = label.length; j < jlen; ++j){
                    nestedLabel =  label[j];
                    if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
                        width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);
                        height += lineHeight;
                    }
                }
            }
            widths.push(width);
            heights.push(height);
            widestLabelSize = Math.max(width, widestLabelSize);
            highestLabelSize = Math.max(height, highestLabelSize);
        }
        garbageCollect(caches, length);
        const widest = widths.indexOf(widestLabelSize);
        const highest = heights.indexOf(highestLabelSize);
        const valueAt = (idx)=>({
                width: widths[idx] || 0,
                height: heights[idx] || 0
            });
        return {
            first: valueAt(0),
            last: valueAt(length - 1),
            widest: valueAt(widest),
            highest: valueAt(highest),
            widths,
            heights
        };
    }
 getLabelForValue(value) {
        return value;
    }
 getPixelForValue(value, index) {
        return NaN;
    }
 getValueForPixel(pixel) {}
 getPixelForTick(index) {
        const ticks = this.ticks;
        if (index < 0 || index > ticks.length - 1) {
            return null;
        }
        return this.getPixelForValue(ticks[index].value);
    }
 getPixelForDecimal(decimal) {
        if (this._reversePixels) {
            decimal = 1 - decimal;
        }
        const pixel = this._startPixel + decimal * this._length;
        return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel);
    }
 getDecimalForPixel(pixel) {
        const decimal = (pixel - this._startPixel) / this._length;
        return this._reversePixels ? 1 - decimal : decimal;
    }
 getBasePixel() {
        return this.getPixelForValue(this.getBaseValue());
    }
 getBaseValue() {
        const { min , max  } = this;
        return min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0;
    }
 getContext(index) {
        const ticks = this.ticks || [];
        if (index >= 0 && index < ticks.length) {
            const tick = ticks[index];
            return tick.$context || (tick.$context = createTickContext(this.getContext(), index, tick));
        }
        return this.$context || (this.$context = createScaleContext(this.chart.getContext(), this));
    }
 _tickSize() {
        const optionTicks = this.options.ticks;
        const rot = toRadians(this.labelRotation);
        const cos = Math.abs(Math.cos(rot));
        const sin = Math.abs(Math.sin(rot));
        const labelSizes = this._getLabelSizes();
        const padding = optionTicks.autoSkipPadding || 0;
        const w = labelSizes ? labelSizes.widest.width + padding : 0;
        const h = labelSizes ? labelSizes.highest.height + padding : 0;
        return this.isHorizontal() ? h * cos > w * sin ? w / cos : h / sin : h * sin < w * cos ? h / cos : w / sin;
    }
 _isVisible() {
        const display = this.options.display;
        if (display !== 'auto') {
            return !!display;
        }
        return this.getMatchingVisibleMetas().length > 0;
    }
 _computeGridLineItems(chartArea) {
        const axis = this.axis;
        const chart = this.chart;
        const options = this.options;
        const { grid , position , border  } = options;
        const offset = grid.offset;
        const isHorizontal = this.isHorizontal();
        const ticks = this.ticks;
        const ticksLength = ticks.length + (offset ? 1 : 0);
        const tl = getTickMarkLength(grid);
        const items = [];
        const borderOpts = border.setContext(this.getContext());
        const axisWidth = borderOpts.display ? borderOpts.width : 0;
        const axisHalfWidth = axisWidth / 2;
        const alignBorderValue = function(pixel) {
            return _alignPixel(chart, pixel, axisWidth);
        };
        let borderValue, i, lineValue, alignedLineValue;
        let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
        if (position === 'top') {
            borderValue = alignBorderValue(this.bottom);
            ty1 = this.bottom - tl;
            ty2 = borderValue - axisHalfWidth;
            y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
            y2 = chartArea.bottom;
        } else if (position === 'bottom') {
            borderValue = alignBorderValue(this.top);
            y1 = chartArea.top;
            y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
            ty1 = borderValue + axisHalfWidth;
            ty2 = this.top + tl;
        } else if (position === 'left') {
            borderValue = alignBorderValue(this.right);
            tx1 = this.right - tl;
            tx2 = borderValue - axisHalfWidth;
            x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
            x2 = chartArea.right;
        } else if (position === 'right') {
            borderValue = alignBorderValue(this.left);
            x1 = chartArea.left;
            x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
            tx1 = borderValue + axisHalfWidth;
            tx2 = this.left + tl;
        } else if (axis === 'x') {
            if (position === 'center') {
                borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);
            } else if (isObject(position)) {
                const positionAxisID = Object.keys(position)[0];
                const value = position[positionAxisID];
                borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
            }
            y1 = chartArea.top;
            y2 = chartArea.bottom;
            ty1 = borderValue + axisHalfWidth;
            ty2 = ty1 + tl;
        } else if (axis === 'y') {
            if (position === 'center') {
                borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
            } else if (isObject(position)) {
                const positionAxisID = Object.keys(position)[0];
                const value = position[positionAxisID];
                borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
            }
            tx1 = borderValue - axisHalfWidth;
            tx2 = tx1 - tl;
            x1 = chartArea.left;
            x2 = chartArea.right;
        }
        const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength);
        const step = Math.max(1, Math.ceil(ticksLength / limit));
        for(i = 0; i < ticksLength; i += step){
            const context = this.getContext(i);
            const optsAtIndex = grid.setContext(context);
            const optsAtIndexBorder = border.setContext(context);
            const lineWidth = optsAtIndex.lineWidth;
            const lineColor = optsAtIndex.color;
            const borderDash = optsAtIndexBorder.dash || [];
            const borderDashOffset = optsAtIndexBorder.dashOffset;
            const tickWidth = optsAtIndex.tickWidth;
            const tickColor = optsAtIndex.tickColor;
            const tickBorderDash = optsAtIndex.tickBorderDash || [];
            const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;
            lineValue = getPixelForGridLine(this, i, offset);
            if (lineValue === undefined) {
                continue;
            }
            alignedLineValue = _alignPixel(chart, lineValue, lineWidth);
            if (isHorizontal) {
                tx1 = tx2 = x1 = x2 = alignedLineValue;
            } else {
                ty1 = ty2 = y1 = y2 = alignedLineValue;
            }
            items.push({
                tx1,
                ty1,
                tx2,
                ty2,
                x1,
                y1,
                x2,
                y2,
                width: lineWidth,
                color: lineColor,
                borderDash,
                borderDashOffset,
                tickWidth,
                tickColor,
                tickBorderDash,
                tickBorderDashOffset
            });
        }
        this._ticksLength = ticksLength;
        this._borderValue = borderValue;
        return items;
    }
 _computeLabelItems(chartArea) {
        const axis = this.axis;
        const options = this.options;
        const { position , ticks: optionTicks  } = options;
        const isHorizontal = this.isHorizontal();
        const ticks = this.ticks;
        const { align , crossAlign , padding , mirror  } = optionTicks;
        const tl = getTickMarkLength(options.grid);
        const tickAndPadding = tl + padding;
        const hTickAndPadding = mirror ? -padding : tickAndPadding;
        const rotation = -toRadians(this.labelRotation);
        const items = [];
        let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
        let textBaseline = 'middle';
        if (position === 'top') {
            y = this.bottom - hTickAndPadding;
            textAlign = this._getXAxisLabelAlignment();
        } else if (position === 'bottom') {
            y = this.top + hTickAndPadding;
            textAlign = this._getXAxisLabelAlignment();
        } else if (position === 'left') {
            const ret = this._getYAxisLabelAlignment(tl);
            textAlign = ret.textAlign;
            x = ret.x;
        } else if (position === 'right') {
            const ret = this._getYAxisLabelAlignment(tl);
            textAlign = ret.textAlign;
            x = ret.x;
        } else if (axis === 'x') {
            if (position === 'center') {
                y = (chartArea.top + chartArea.bottom) / 2 + tickAndPadding;
            } else if (isObject(position)) {
                const positionAxisID = Object.keys(position)[0];
                const value = position[positionAxisID];
                y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;
            }
            textAlign = this._getXAxisLabelAlignment();
        } else if (axis === 'y') {
            if (position === 'center') {
                x = (chartArea.left + chartArea.right) / 2 - tickAndPadding;
            } else if (isObject(position)) {
                const positionAxisID = Object.keys(position)[0];
                const value = position[positionAxisID];
                x = this.chart.scales[positionAxisID].getPixelForValue(value);
            }
            textAlign = this._getYAxisLabelAlignment(tl).textAlign;
        }
        if (axis === 'y') {
            if (align === 'start') {
                textBaseline = 'top';
            } else if (align === 'end') {
                textBaseline = 'bottom';
            }
        }
        const labelSizes = this._getLabelSizes();
        for(i = 0, ilen = ticks.length; i < ilen; ++i){
            tick = ticks[i];
            label = tick.label;
            const optsAtIndex = optionTicks.setContext(this.getContext(i));
            pixel = this.getPixelForTick(i) + optionTicks.labelOffset;
            font = this._resolveTickFontOptions(i);
            lineHeight = font.lineHeight;
            lineCount = isArray(label) ? label.length : 1;
            const halfCount = lineCount / 2;
            const color = optsAtIndex.color;
            const strokeColor = optsAtIndex.textStrokeColor;
            const strokeWidth = optsAtIndex.textStrokeWidth;
            let tickTextAlign = textAlign;
            if (isHorizontal) {
                x = pixel;
                if (textAlign === 'inner') {
                    if (i === ilen - 1) {
                        tickTextAlign = !this.options.reverse ? 'right' : 'left';
                    } else if (i === 0) {
                        tickTextAlign = !this.options.reverse ? 'left' : 'right';
                    } else {
                        tickTextAlign = 'center';
                    }
                }
                if (position === 'top') {
                    if (crossAlign === 'near' || rotation !== 0) {
                        textOffset = -lineCount * lineHeight + lineHeight / 2;
                    } else if (crossAlign === 'center') {
                        textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;
                    } else {
                        textOffset = -labelSizes.highest.height + lineHeight / 2;
                    }
                } else {
                    if (crossAlign === 'near' || rotation !== 0) {
                        textOffset = lineHeight / 2;
                    } else if (crossAlign === 'center') {
                        textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;
                    } else {
                        textOffset = labelSizes.highest.height - lineCount * lineHeight;
                    }
                }
                if (mirror) {
                    textOffset *= -1;
                }
                if (rotation !== 0 && !optsAtIndex.showLabelBackdrop) {
                    x += lineHeight / 2 * Math.sin(rotation);
                }
            } else {
                y = pixel;
                textOffset = (1 - lineCount) * lineHeight / 2;
            }
            let backdrop;
            if (optsAtIndex.showLabelBackdrop) {
                const labelPadding = toPadding(optsAtIndex.backdropPadding);
                const height = labelSizes.heights[i];
                const width = labelSizes.widths[i];
                let top = textOffset - labelPadding.top;
                let left = 0 - labelPadding.left;
                switch(textBaseline){
                    case 'middle':
                        top -= height / 2;
                        break;
                    case 'bottom':
                        top -= height;
                        break;
                }
                switch(textAlign){
                    case 'center':
                        left -= width / 2;
                        break;
                    case 'right':
                        left -= width;
                        break;
                    case 'inner':
                        if (i === ilen - 1) {
                            left -= width;
                        } else if (i > 0) {
                            left -= width / 2;
                        }
                        break;
                }
                backdrop = {
                    left,
                    top,
                    width: width + labelPadding.width,
                    height: height + labelPadding.height,
                    color: optsAtIndex.backdropColor
                };
            }
            items.push({
                label,
                font,
                textOffset,
                options: {
                    rotation,
                    color,
                    strokeColor,
                    strokeWidth,
                    textAlign: tickTextAlign,
                    textBaseline,
                    translation: [
                        x,
                        y
                    ],
                    backdrop
                }
            });
        }
        return items;
    }
    _getXAxisLabelAlignment() {
        const { position , ticks  } = this.options;
        const rotation = -toRadians(this.labelRotation);
        if (rotation) {
            return position === 'top' ? 'left' : 'right';
        }
        let align = 'center';
        if (ticks.align === 'start') {
            align = 'left';
        } else if (ticks.align === 'end') {
            align = 'right';
        } else if (ticks.align === 'inner') {
            align = 'inner';
        }
        return align;
    }
    _getYAxisLabelAlignment(tl) {
        const { position , ticks: { crossAlign , mirror , padding  }  } = this.options;
        const labelSizes = this._getLabelSizes();
        const tickAndPadding = tl + padding;
        const widest = labelSizes.widest.width;
        let textAlign;
        let x;
        if (position === 'left') {
            if (mirror) {
                x = this.right + padding;
                if (crossAlign === 'near') {
                    textAlign = 'left';
                } else if (crossAlign === 'center') {
                    textAlign = 'center';
                    x += widest / 2;
                } else {
                    textAlign = 'right';
                    x += widest;
                }
            } else {
                x = this.right - tickAndPadding;
                if (crossAlign === 'near') {
                    textAlign = 'right';
                } else if (crossAlign === 'center') {
                    textAlign = 'center';
                    x -= widest / 2;
                } else {
                    textAlign = 'left';
                    x = this.left;
                }
            }
        } else if (position === 'right') {
            if (mirror) {
                x = this.left + padding;
                if (crossAlign === 'near') {
                    textAlign = 'right';
                } else if (crossAlign === 'center') {
                    textAlign = 'center';
                    x -= widest / 2;
                } else {
                    textAlign = 'left';
                    x -= widest;
                }
            } else {
                x = this.left + tickAndPadding;
                if (crossAlign === 'near') {
                    textAlign = 'left';
                } else if (crossAlign === 'center') {
                    textAlign = 'center';
                    x += widest / 2;
                } else {
                    textAlign = 'right';
                    x = this.right;
                }
            }
        } else {
            textAlign = 'right';
        }
        return {
            textAlign,
            x
        };
    }
 _computeLabelArea() {
        if (this.options.ticks.mirror) {
            return;
        }
        const chart = this.chart;
        const position = this.options.position;
        if (position === 'left' || position === 'right') {
            return {
                top: 0,
                left: this.left,
                bottom: chart.height,
                right: this.right
            };
        }
        if (position === 'top' || position === 'bottom') {
            return {
                top: this.top,
                left: 0,
                bottom: this.bottom,
                right: chart.width
            };
        }
    }
 drawBackground() {
        const { ctx , options: { backgroundColor  } , left , top , width , height  } = this;
        if (backgroundColor) {
            ctx.save();
            ctx.fillStyle = backgroundColor;
            ctx.fillRect(left, top, width, height);
            ctx.restore();
        }
    }
    getLineWidthForValue(value) {
        const grid = this.options.grid;
        if (!this._isVisible() || !grid.display) {
            return 0;
        }
        const ticks = this.ticks;
        const index = ticks.findIndex((t)=>t.value === value);
        if (index >= 0) {
            const opts = grid.setContext(this.getContext(index));
            return opts.lineWidth;
        }
        return 0;
    }
 drawGrid(chartArea) {
        const grid = this.options.grid;
        const ctx = this.ctx;
        const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea));
        let i, ilen;
        const drawLine = (p1, p2, style)=>{
            if (!style.width || !style.color) {
                return;
            }
            ctx.save();
            ctx.lineWidth = style.width;
            ctx.strokeStyle = style.color;
            ctx.setLineDash(style.borderDash || []);
            ctx.lineDashOffset = style.borderDashOffset;
            ctx.beginPath();
            ctx.moveTo(p1.x, p1.y);
            ctx.lineTo(p2.x, p2.y);
            ctx.stroke();
            ctx.restore();
        };
        if (grid.display) {
            for(i = 0, ilen = items.length; i < ilen; ++i){
                const item = items[i];
                if (grid.drawOnChartArea) {
                    drawLine({
                        x: item.x1,
                        y: item.y1
                    }, {
                        x: item.x2,
                        y: item.y2
                    }, item);
                }
                if (grid.drawTicks) {
                    drawLine({
                        x: item.tx1,
                        y: item.ty1
                    }, {
                        x: item.tx2,
                        y: item.ty2
                    }, {
                        color: item.tickColor,
                        width: item.tickWidth,
                        borderDash: item.tickBorderDash,
                        borderDashOffset: item.tickBorderDashOffset
                    });
                }
            }
        }
    }
 drawBorder() {
        const { chart , ctx , options: { border , grid  }  } = this;
        const borderOpts = border.setContext(this.getContext());
        const axisWidth = border.display ? borderOpts.width : 0;
        if (!axisWidth) {
            return;
        }
        const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth;
        const borderValue = this._borderValue;
        let x1, x2, y1, y2;
        if (this.isHorizontal()) {
            x1 = _alignPixel(chart, this.left, axisWidth) - axisWidth / 2;
            x2 = _alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2;
            y1 = y2 = borderValue;
        } else {
            y1 = _alignPixel(chart, this.top, axisWidth) - axisWidth / 2;
            y2 = _alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2;
            x1 = x2 = borderValue;
        }
        ctx.save();
        ctx.lineWidth = borderOpts.width;
        ctx.strokeStyle = borderOpts.color;
        ctx.beginPath();
        ctx.moveTo(x1, y1);
        ctx.lineTo(x2, y2);
        ctx.stroke();
        ctx.restore();
    }
 drawLabels(chartArea) {
        const optionTicks = this.options.ticks;
        if (!optionTicks.display) {
            return;
        }
        const ctx = this.ctx;
        const area = this._computeLabelArea();
        if (area) {
            clipArea(ctx, area);
        }
        const items = this.getLabelItems(chartArea);
        for (const item of items){
            const renderTextOptions = item.options;
            const tickFont = item.font;
            const label = item.label;
            const y = item.textOffset;
            renderText(ctx, label, 0, y, tickFont, renderTextOptions);
        }
        if (area) {
            unclipArea(ctx);
        }
    }
 drawTitle() {
        const { ctx , options: { position , title , reverse  }  } = this;
        if (!title.display) {
            return;
        }
        const font = toFont(title.font);
        const padding = toPadding(title.padding);
        const align = title.align;
        let offset = font.lineHeight / 2;
        if (position === 'bottom' || position === 'center' || isObject(position)) {
            offset += padding.bottom;
            if (isArray(title.text)) {
                offset += font.lineHeight * (title.text.length - 1);
            }
        } else {
            offset += padding.top;
        }
        const { titleX , titleY , maxWidth , rotation  } = titleArgs(this, offset, position, align);
        renderText(ctx, title.text, 0, 0, font, {
            color: title.color,
            maxWidth,
            rotation,
            textAlign: titleAlign(align, position, reverse),
            textBaseline: 'middle',
            translation: [
                titleX,
                titleY
            ]
        });
    }
    draw(chartArea) {
        if (!this._isVisible()) {
            return;
        }
        this.drawBackground();
        this.drawGrid(chartArea);
        this.drawBorder();
        this.drawTitle();
        this.drawLabels(chartArea);
    }
 _layers() {
        const opts = this.options;
        const tz = opts.ticks && opts.ticks.z || 0;
        const gz = valueOrDefault(opts.grid && opts.grid.z, -1);
        const bz = valueOrDefault(opts.border && opts.border.z, 0);
        if (!this._isVisible() || this.draw !== Scale.prototype.draw) {
            return [
                {
                    z: tz,
                    draw: (chartArea)=>{
                        this.draw(chartArea);
                    }
                }
            ];
        }
        return [
            {
                z: gz,
                draw: (chartArea)=>{
                    this.drawBackground();
                    this.drawGrid(chartArea);
                    this.drawTitle();
                }
            },
            {
                z: bz,
                draw: ()=>{
                    this.drawBorder();
                }
            },
            {
                z: tz,
                draw: (chartArea)=>{
                    this.drawLabels(chartArea);
                }
            }
        ];
    }
 getMatchingVisibleMetas(type) {
        const metas = this.chart.getSortedVisibleDatasetMetas();
        const axisID = this.axis + 'AxisID';
        const result = [];
        let i, ilen;
        for(i = 0, ilen = metas.length; i < ilen; ++i){
            const meta = metas[i];
            if (meta[axisID] === this.id && (!type || meta.type === type)) {
                result.push(meta);
            }
        }
        return result;
    }
 _resolveTickFontOptions(index) {
        const opts = this.options.ticks.setContext(this.getContext(index));
        return toFont(opts.font);
    }
 _maxDigits() {
        const fontSize = this._resolveTickFontOptions(0).lineHeight;
        return (this.isHorizontal() ? this.width : this.height) / fontSize;
    }
}

class TypedRegistry {
    constructor(type, scope, override){
        this.type = type;
        this.scope = scope;
        this.override = override;
        this.items = Object.create(null);
    }
    isForType(type) {
        return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);
    }
 register(item) {
        const proto = Object.getPrototypeOf(item);
        let parentScope;
        if (isIChartComponent(proto)) {
            parentScope = this.register(proto);
        }
        const items = this.items;
        const id = item.id;
        const scope = this.scope + '.' + id;
        if (!id) {
            throw new Error('class does not have id: ' + item);
        }
        if (id in items) {
            return scope;
        }
        items[id] = item;
        registerDefaults(item, scope, parentScope);
        if (this.override) {
            defaults.override(item.id, item.overrides);
        }
        return scope;
    }
 get(id) {
        return this.items[id];
    }
 unregister(item) {
        const items = this.items;
        const id = item.id;
        const scope = this.scope;
        if (id in items) {
            delete items[id];
        }
        if (scope && id in defaults[scope]) {
            delete defaults[scope][id];
            if (this.override) {
                delete overrides[id];
            }
        }
    }
}
function registerDefaults(item, scope, parentScope) {
    const itemDefaults = merge(Object.create(null), [
        parentScope ? defaults.get(parentScope) : {},
        defaults.get(scope),
        item.defaults
    ]);
    defaults.set(scope, itemDefaults);
    if (item.defaultRoutes) {
        routeDefaults(scope, item.defaultRoutes);
    }
    if (item.descriptors) {
        defaults.describe(scope, item.descriptors);
    }
}
function routeDefaults(scope, routes) {
    Object.keys(routes).forEach((property)=>{
        const propertyParts = property.split('.');
        const sourceName = propertyParts.pop();
        const sourceScope = [
            scope
        ].concat(propertyParts).join('.');
        const parts = routes[property].split('.');
        const targetName = parts.pop();
        const targetScope = parts.join('.');
        defaults.route(sourceScope, sourceName, targetScope, targetName);
    });
}
function isIChartComponent(proto) {
    return 'id' in proto && 'defaults' in proto;
}

class Registry {
    constructor(){
        this.controllers = new TypedRegistry(DatasetController, 'datasets', true);
        this.elements = new TypedRegistry(Element$1, 'elements');
        this.plugins = new TypedRegistry(Object, 'plugins');
        this.scales = new TypedRegistry(Scale, 'scales');
        this._typedRegistries = [
            this.controllers,
            this.scales,
            this.elements
        ];
    }
 add(...args) {
        this._each('register', args);
    }
    remove(...args) {
        this._each('unregister', args);
    }
 addControllers(...args) {
        this._each('register', args, this.controllers);
    }
 addElements(...args) {
        this._each('register', args, this.elements);
    }
 addPlugins(...args) {
        this._each('register', args, this.plugins);
    }
 addScales(...args) {
        this._each('register', args, this.scales);
    }
 getController(id) {
        return this._get(id, this.controllers, 'controller');
    }
 getElement(id) {
        return this._get(id, this.elements, 'element');
    }
 getPlugin(id) {
        return this._get(id, this.plugins, 'plugin');
    }
 getScale(id) {
        return this._get(id, this.scales, 'scale');
    }
 removeControllers(...args) {
        this._each('unregister', args, this.controllers);
    }
 removeElements(...args) {
        this._each('unregister', args, this.elements);
    }
 removePlugins(...args) {
        this._each('unregister', args, this.plugins);
    }
 removeScales(...args) {
        this._each('unregister', args, this.scales);
    }
 _each(method, args, typedRegistry) {
        [
            ...args
        ].forEach((arg)=>{
            const reg = typedRegistry || this._getRegistryForType(arg);
            if (typedRegistry || reg.isForType(arg) || reg === this.plugins && arg.id) {
                this._exec(method, reg, arg);
            } else {
                each(arg, (item)=>{
                    const itemReg = typedRegistry || this._getRegistryForType(item);
                    this._exec(method, itemReg, item);
                });
            }
        });
    }
 _exec(method, registry, component) {
        const camelMethod = _capitalize(method);
        callback(component['before' + camelMethod], [], component);
        registry[method](component);
        callback(component['after' + camelMethod], [], component);
    }
 _getRegistryForType(type) {
        for(let i = 0; i < this._typedRegistries.length; i++){
            const reg = this._typedRegistries[i];
            if (reg.isForType(type)) {
                return reg;
            }
        }
        return this.plugins;
    }
 _get(id, typedRegistry, type) {
        const item = typedRegistry.get(id);
        if (item === undefined) {
            throw new Error('"' + id + '" is not a registered ' + type + '.');
        }
        return item;
    }
}
var registry = /* #__PURE__ */ new Registry();

class PluginService {
    constructor(){
        this._init = undefined;
    }
 notify(chart, hook, args, filter) {
        if (hook === 'beforeInit') {
            this._init = this._createDescriptors(chart, true);
            this._notify(this._init, chart, 'install');
        }
        if (this._init === undefined) {
            return;
        }
        const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart);
        const result = this._notify(descriptors, chart, hook, args);
        if (hook === 'afterDestroy') {
            this._notify(descriptors, chart, 'stop');
            this._notify(this._init, chart, 'uninstall');
            this._init = undefined;
        }
        return result;
    }
 _notify(descriptors, chart, hook, args) {
        args = args || {};
        for (const descriptor of descriptors){
            const plugin = descriptor.plugin;
            const method = plugin[hook];
            const params = [
                chart,
                args,
                descriptor.options
            ];
            if (callback(method, params, plugin) === false && args.cancelable) {
                return false;
            }
        }
        return true;
    }
    invalidate() {
        if (!isNullOrUndef(this._cache)) {
            this._oldCache = this._cache;
            this._cache = undefined;
        }
    }
 _descriptors(chart) {
        if (this._cache) {
            return this._cache;
        }
        const descriptors = this._cache = this._createDescriptors(chart);
        this._notifyStateChanges(chart);
        return descriptors;
    }
    _createDescriptors(chart, all) {
        const config = chart && chart.config;
        const options = valueOrDefault(config.options && config.options.plugins, {});
        const plugins = allPlugins(config);
        return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);
    }
 _notifyStateChanges(chart) {
        const previousDescriptors = this._oldCache || [];
        const descriptors = this._cache;
        const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.plugin.id === y.plugin.id));
        this._notify(diff(previousDescriptors, descriptors), chart, 'stop');
        this._notify(diff(descriptors, previousDescriptors), chart, 'start');
    }
}
 function allPlugins(config) {
    const localIds = {};
    const plugins = [];
    const keys = Object.keys(registry.plugins.items);
    for(let i = 0; i < keys.length; i++){
        plugins.push(registry.getPlugin(keys[i]));
    }
    const local = config.plugins || [];
    for(let i = 0; i < local.length; i++){
        const plugin = local[i];
        if (plugins.indexOf(plugin) === -1) {
            plugins.push(plugin);
            localIds[plugin.id] = true;
        }
    }
    return {
        plugins,
        localIds
    };
}
function getOpts(options, all) {
    if (!all && options === false) {
        return null;
    }
    if (options === true) {
        return {};
    }
    return options;
}
function createDescriptors(chart, { plugins , localIds  }, options, all) {
    const result = [];
    const context = chart.getContext();
    for (const plugin of plugins){
        const id = plugin.id;
        const opts = getOpts(options[id], all);
        if (opts === null) {
            continue;
        }
        result.push({
            plugin,
            options: pluginOpts(chart.config, {
                plugin,
                local: localIds[id]
            }, opts, context)
        });
    }
    return result;
}
function pluginOpts(config, { plugin , local  }, opts, context) {
    const keys = config.pluginScopeKeys(plugin);
    const scopes = config.getOptionScopes(opts, keys);
    if (local && plugin.defaults) {
        scopes.push(plugin.defaults);
    }
    return config.createResolver(scopes, context, [
        ''
    ], {
        scriptable: false,
        indexable: false,
        allKeys: true
    });
}

function getIndexAxis(type, options) {
    const datasetDefaults = defaults.datasets[type] || {};
    const datasetOptions = (options.datasets || {})[type] || {};
    return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
}
function getAxisFromDefaultScaleID(id, indexAxis) {
    let axis = id;
    if (id === '_index_') {
        axis = indexAxis;
    } else if (id === '_value_') {
        axis = indexAxis === 'x' ? 'y' : 'x';
    }
    return axis;
}
function getDefaultScaleIDFromAxis(axis, indexAxis) {
    return axis === indexAxis ? '_index_' : '_value_';
}
function idMatchesAxis(id) {
    if (id === 'x' || id === 'y' || id === 'r') {
        return id;
    }
}
function axisFromPosition(position) {
    if (position === 'top' || position === 'bottom') {
        return 'x';
    }
    if (position === 'left' || position === 'right') {
        return 'y';
    }
}
function determineAxis(id, ...scaleOptions) {
    if (idMatchesAxis(id)) {
        return id;
    }
    for (const opts of scaleOptions){
        const axis = opts.axis || axisFromPosition(opts.position) || id.length > 1 && idMatchesAxis(id[0].toLowerCase());
        if (axis) {
            return axis;
        }
    }
    throw new Error(`Cannot determine type of '${id}' axis. Please provide 'axis' or 'position' option.`);
}
function getAxisFromDataset(id, axis, dataset) {
    if (dataset[axis + 'AxisID'] === id) {
        return {
            axis
        };
    }
}
function retrieveAxisFromDatasets(id, config) {
    if (config.data && config.data.datasets) {
        const boundDs = config.data.datasets.filter((d)=>d.xAxisID === id || d.yAxisID === id);
        if (boundDs.length) {
            return getAxisFromDataset(id, 'x', boundDs[0]) || getAxisFromDataset(id, 'y', boundDs[0]);
        }
    }
    return {};
}
function mergeScaleConfig(config, options) {
    const chartDefaults = overrides[config.type] || {
        scales: {}
    };
    const configScales = options.scales || {};
    const chartIndexAxis = getIndexAxis(config.type, options);
    const scales = Object.create(null);
    Object.keys(configScales).forEach((id)=>{
        const scaleConf = configScales[id];
        if (!isObject(scaleConf)) {
            return console.error(`Invalid scale configuration for scale: ${id}`);
        }
        if (scaleConf._proxy) {
            return console.warn(`Ignoring resolver passed as options for scale: ${id}`);
        }
        const axis = determineAxis(id, scaleConf, retrieveAxisFromDatasets(id, config), defaults.scales[scaleConf.type]);
        const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
        const defaultScaleOptions = chartDefaults.scales || {};
        scales[id] = mergeIf(Object.create(null), [
            {
                axis
            },
            scaleConf,
            defaultScaleOptions[axis],
            defaultScaleOptions[defaultId]
        ]);
    });
    config.data.datasets.forEach((dataset)=>{
        const type = dataset.type || config.type;
        const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
        const datasetDefaults = overrides[type] || {};
        const defaultScaleOptions = datasetDefaults.scales || {};
        Object.keys(defaultScaleOptions).forEach((defaultID)=>{
            const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
            const id = dataset[axis + 'AxisID'] || axis;
            scales[id] = scales[id] || Object.create(null);
            mergeIf(scales[id], [
                {
                    axis
                },
                configScales[id],
                defaultScaleOptions[defaultID]
            ]);
        });
    });
    Object.keys(scales).forEach((key)=>{
        const scale = scales[key];
        mergeIf(scale, [
            defaults.scales[scale.type],
            defaults.scale
        ]);
    });
    return scales;
}
function initOptions(config) {
    const options = config.options || (config.options = {});
    options.plugins = valueOrDefault(options.plugins, {});
    options.scales = mergeScaleConfig(config, options);
}
function initData(data) {
    data = data || {};
    data.datasets = data.datasets || [];
    data.labels = data.labels || [];
    return data;
}
function initConfig(config) {
    config = config || {};
    config.data = initData(config.data);
    initOptions(config);
    return config;
}
const keyCache = new Map();
const keysCached = new Set();
function cachedKeys(cacheKey, generate) {
    let keys = keyCache.get(cacheKey);
    if (!keys) {
        keys = generate();
        keyCache.set(cacheKey, keys);
        keysCached.add(keys);
    }
    return keys;
}
const addIfFound = (set, obj, key)=>{
    const opts = resolveObjectKey(obj, key);
    if (opts !== undefined) {
        set.add(opts);
    }
};
class Config {
    constructor(config){
        this._config = initConfig(config);
        this._scopeCache = new Map();
        this._resolverCache = new Map();
    }
    get platform() {
        return this._config.platform;
    }
    get type() {
        return this._config.type;
    }
    set type(type) {
        this._config.type = type;
    }
    get data() {
        return this._config.data;
    }
    set data(data) {
        this._config.data = initData(data);
    }
    get options() {
        return this._config.options;
    }
    set options(options) {
        this._config.options = options;
    }
    get plugins() {
        return this._config.plugins;
    }
    update() {
        const config = this._config;
        this.clearCache();
        initOptions(config);
    }
    clearCache() {
        this._scopeCache.clear();
        this._resolverCache.clear();
    }
 datasetScopeKeys(datasetType) {
        return cachedKeys(datasetType, ()=>[
                [
                    `datasets.${datasetType}`,
                    ''
                ]
            ]);
    }
 datasetAnimationScopeKeys(datasetType, transition) {
        return cachedKeys(`${datasetType}.transition.${transition}`, ()=>[
                [
                    `datasets.${datasetType}.transitions.${transition}`,
                    `transitions.${transition}`
                ],
                [
                    `datasets.${datasetType}`,
                    ''
                ]
            ]);
    }
 datasetElementScopeKeys(datasetType, elementType) {
        return cachedKeys(`${datasetType}-${elementType}`, ()=>[
                [
                    `datasets.${datasetType}.elements.${elementType}`,
                    `datasets.${datasetType}`,
                    `elements.${elementType}`,
                    ''
                ]
            ]);
    }
 pluginScopeKeys(plugin) {
        const id = plugin.id;
        const type = this.type;
        return cachedKeys(`${type}-plugin-${id}`, ()=>[
                [
                    `plugins.${id}`,
                    ...plugin.additionalOptionScopes || []
                ]
            ]);
    }
 _cachedScopes(mainScope, resetCache) {
        const _scopeCache = this._scopeCache;
        let cache = _scopeCache.get(mainScope);
        if (!cache || resetCache) {
            cache = new Map();
            _scopeCache.set(mainScope, cache);
        }
        return cache;
    }
 getOptionScopes(mainScope, keyLists, resetCache) {
        const { options , type  } = this;
        const cache = this._cachedScopes(mainScope, resetCache);
        const cached = cache.get(keyLists);
        if (cached) {
            return cached;
        }
        const scopes = new Set();
        keyLists.forEach((keys)=>{
            if (mainScope) {
                scopes.add(mainScope);
                keys.forEach((key)=>addIfFound(scopes, mainScope, key));
            }
            keys.forEach((key)=>addIfFound(scopes, options, key));
            keys.forEach((key)=>addIfFound(scopes, overrides[type] || {}, key));
            keys.forEach((key)=>addIfFound(scopes, defaults, key));
            keys.forEach((key)=>addIfFound(scopes, descriptors, key));
        });
        const array = Array.from(scopes);
        if (array.length === 0) {
            array.push(Object.create(null));
        }
        if (keysCached.has(keyLists)) {
            cache.set(keyLists, array);
        }
        return array;
    }
 chartOptionScopes() {
        const { options , type  } = this;
        return [
            options,
            overrides[type] || {},
            defaults.datasets[type] || {},
            {
                type
            },
            defaults,
            descriptors
        ];
    }
 resolveNamedOptions(scopes, names, context, prefixes = [
        ''
    ]) {
        const result = {
            $shared: true
        };
        const { resolver , subPrefixes  } = getResolver(this._resolverCache, scopes, prefixes);
        let options = resolver;
        if (needContext(resolver, names)) {
            result.$shared = false;
            context = isFunction(context) ? context() : context;
            const subResolver = this.createResolver(scopes, context, subPrefixes);
            options = _attachContext(resolver, context, subResolver);
        }
        for (const prop of names){
            result[prop] = options[prop];
        }
        return result;
    }
 createResolver(scopes, context, prefixes = [
        ''
    ], descriptorDefaults) {
        const { resolver  } = getResolver(this._resolverCache, scopes, prefixes);
        return isObject(context) ? _attachContext(resolver, context, undefined, descriptorDefaults) : resolver;
    }
}
function getResolver(resolverCache, scopes, prefixes) {
    let cache = resolverCache.get(scopes);
    if (!cache) {
        cache = new Map();
        resolverCache.set(scopes, cache);
    }
    const cacheKey = prefixes.join();
    let cached = cache.get(cacheKey);
    if (!cached) {
        const resolver = _createResolver(scopes, prefixes);
        cached = {
            resolver,
            subPrefixes: prefixes.filter((p)=>!p.toLowerCase().includes('hover'))
        };
        cache.set(cacheKey, cached);
    }
    return cached;
}
const hasFunction = (value)=>isObject(value) && Object.getOwnPropertyNames(value).some((key)=>isFunction(value[key]));
function needContext(proxy, names) {
    const { isScriptable , isIndexable  } = _descriptors(proxy);
    for (const prop of names){
        const scriptable = isScriptable(prop);
        const indexable = isIndexable(prop);
        const value = (indexable || scriptable) && proxy[prop];
        if (scriptable && (isFunction(value) || hasFunction(value)) || indexable && isArray(value)) {
            return true;
        }
    }
    return false;
}

var version = "4.5.1";

const KNOWN_POSITIONS = [
    'top',
    'bottom',
    'left',
    'right',
    'chartArea'
];
function positionIsHorizontal(position, axis) {
    return position === 'top' || position === 'bottom' || KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x';
}
function compare2Level(l1, l2) {
    return function(a, b) {
        return a[l1] === b[l1] ? a[l2] - b[l2] : a[l1] - b[l1];
    };
}
function onAnimationsComplete(context) {
    const chart = context.chart;
    const animationOptions = chart.options.animation;
    chart.notifyPlugins('afterRender');
    callback(animationOptions && animationOptions.onComplete, [
        context
    ], chart);
}
function onAnimationProgress(context) {
    const chart = context.chart;
    const animationOptions = chart.options.animation;
    callback(animationOptions && animationOptions.onProgress, [
        context
    ], chart);
}
 function getCanvas(item) {
    if (_isDomSupported() && typeof item === 'string') {
        item = document.getElementById(item);
    } else if (item && item.length) {
        item = item[0];
    }
    if (item && item.canvas) {
        item = item.canvas;
    }
    return item;
}
const instances = {};
const getChart = (key)=>{
    const canvas = getCanvas(key);
    return Object.values(instances).filter((c)=>c.canvas === canvas).pop();
};
function moveNumericKeys(obj, start, move) {
    const keys = Object.keys(obj);
    for (const key of keys){
        const intKey = +key;
        if (intKey >= start) {
            const value = obj[key];
            delete obj[key];
            if (move > 0 || intKey > start) {
                obj[intKey + move] = value;
            }
        }
    }
}
 function determineLastEvent(e, lastEvent, inChartArea, isClick) {
    if (!inChartArea || e.type === 'mouseout') {
        return null;
    }
    if (isClick) {
        return lastEvent;
    }
    return e;
}
let Chart$1 = class Chart {
    static defaults = defaults;
    static instances = instances;
    static overrides = overrides;
    static registry = registry;
    static version = version;
    static getChart = getChart;
    static register(...items) {
        registry.add(...items);
        invalidatePlugins();
    }
    static unregister(...items) {
        registry.remove(...items);
        invalidatePlugins();
    }
    constructor(item, userConfig){
        const config = this.config = new Config(userConfig);
        const initialCanvas = getCanvas(item);
        const existingChart = getChart(initialCanvas);
        if (existingChart) {
            throw new Error('Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' + ' must be destroyed before the canvas with ID \'' + existingChart.canvas.id + '\' can be reused.');
        }
        const options = config.createResolver(config.chartOptionScopes(), this.getContext());
        this.platform = new (config.platform || _detectPlatform(initialCanvas))();
        this.platform.updateConfig(config);
        const context = this.platform.acquireContext(initialCanvas, options.aspectRatio);
        const canvas = context && context.canvas;
        const height = canvas && canvas.height;
        const width = canvas && canvas.width;
        this.id = uid();
        this.ctx = context;
        this.canvas = canvas;
        this.width = width;
        this.height = height;
        this._options = options;
        this._aspectRatio = this.aspectRatio;
        this._layers = [];
        this._metasets = [];
        this._stacks = undefined;
        this.boxes = [];
        this.currentDevicePixelRatio = undefined;
        this.chartArea = undefined;
        this._active = [];
        this._lastEvent = undefined;
        this._listeners = {};
         this._responsiveListeners = undefined;
        this._sortedMetasets = [];
        this.scales = {};
        this._plugins = new PluginService();
        this.$proxies = {};
        this._hiddenIndices = {};
        this.attached = false;
        this._animationsDisabled = undefined;
        this.$context = undefined;
        this._doResize = debounce$1((mode)=>this.update(mode), options.resizeDelay || 0);
        this._dataChanges = [];
        instances[this.id] = this;
        if (!context || !canvas) {
            console.error("Failed to create chart: can't acquire context from the given item");
            return;
        }
        animator.listen(this, 'complete', onAnimationsComplete);
        animator.listen(this, 'progress', onAnimationProgress);
        this._initialize();
        if (this.attached) {
            this.update();
        }
    }
    get aspectRatio() {
        const { options: { aspectRatio , maintainAspectRatio  } , width , height , _aspectRatio  } = this;
        if (!isNullOrUndef(aspectRatio)) {
            return aspectRatio;
        }
        if (maintainAspectRatio && _aspectRatio) {
            return _aspectRatio;
        }
        return height ? width / height : null;
    }
    get data() {
        return this.config.data;
    }
    set data(data) {
        this.config.data = data;
    }
    get options() {
        return this._options;
    }
    set options(options) {
        this.config.options = options;
    }
    get registry() {
        return registry;
    }
 _initialize() {
        this.notifyPlugins('beforeInit');
        if (this.options.responsive) {
            this.resize();
        } else {
            retinaScale(this, this.options.devicePixelRatio);
        }
        this.bindEvents();
        this.notifyPlugins('afterInit');
        return this;
    }
    clear() {
        clearCanvas(this.canvas, this.ctx);
        return this;
    }
    stop() {
        animator.stop(this);
        return this;
    }
 resize(width, height) {
        if (!animator.running(this)) {
            this._resize(width, height);
        } else {
            this._resizeBeforeDraw = {
                width,
                height
            };
        }
    }
    _resize(width, height) {
        const options = this.options;
        const canvas = this.canvas;
        const aspectRatio = options.maintainAspectRatio && this.aspectRatio;
        const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio);
        const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio();
        const mode = this.width ? 'resize' : 'attach';
        this.width = newSize.width;
        this.height = newSize.height;
        this._aspectRatio = this.aspectRatio;
        if (!retinaScale(this, newRatio, true)) {
            return;
        }
        this.notifyPlugins('resize', {
            size: newSize
        });
        callback(options.onResize, [
            this,
            newSize
        ], this);
        if (this.attached) {
            if (this._doResize(mode)) {
                this.render();
            }
        }
    }
    ensureScalesHaveIDs() {
        const options = this.options;
        const scalesOptions = options.scales || {};
        each(scalesOptions, (axisOptions, axisID)=>{
            axisOptions.id = axisID;
        });
    }
 buildOrUpdateScales() {
        const options = this.options;
        const scaleOpts = options.scales;
        const scales = this.scales;
        const updated = Object.keys(scales).reduce((obj, id)=>{
            obj[id] = false;
            return obj;
        }, {});
        let items = [];
        if (scaleOpts) {
            items = items.concat(Object.keys(scaleOpts).map((id)=>{
                const scaleOptions = scaleOpts[id];
                const axis = determineAxis(id, scaleOptions);
                const isRadial = axis === 'r';
                const isHorizontal = axis === 'x';
                return {
                    options: scaleOptions,
                    dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
                    dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'
                };
            }));
        }
        each(items, (item)=>{
            const scaleOptions = item.options;
            const id = scaleOptions.id;
            const axis = determineAxis(id, scaleOptions);
            const scaleType = valueOrDefault(scaleOptions.type, item.dtype);
            if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
                scaleOptions.position = item.dposition;
            }
            updated[id] = true;
            let scale = null;
            if (id in scales && scales[id].type === scaleType) {
                scale = scales[id];
            } else {
                const scaleClass = registry.getScale(scaleType);
                scale = new scaleClass({
                    id,
                    type: scaleType,
                    ctx: this.ctx,
                    chart: this
                });
                scales[scale.id] = scale;
            }
            scale.init(scaleOptions, options);
        });
        each(updated, (hasUpdated, id)=>{
            if (!hasUpdated) {
                delete scales[id];
            }
        });
        each(scales, (scale)=>{
            layouts.configure(this, scale, scale.options);
            layouts.addBox(this, scale);
        });
    }
 _updateMetasets() {
        const metasets = this._metasets;
        const numData = this.data.datasets.length;
        const numMeta = metasets.length;
        metasets.sort((a, b)=>a.index - b.index);
        if (numMeta > numData) {
            for(let i = numData; i < numMeta; ++i){
                this._destroyDatasetMeta(i);
            }
            metasets.splice(numData, numMeta - numData);
        }
        this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
    }
 _removeUnreferencedMetasets() {
        const { _metasets: metasets , data: { datasets  }  } = this;
        if (metasets.length > datasets.length) {
            delete this._stacks;
        }
        metasets.forEach((meta, index)=>{
            if (datasets.filter((x)=>x === meta._dataset).length === 0) {
                this._destroyDatasetMeta(index);
            }
        });
    }
    buildOrUpdateControllers() {
        const newControllers = [];
        const datasets = this.data.datasets;
        let i, ilen;
        this._removeUnreferencedMetasets();
        for(i = 0, ilen = datasets.length; i < ilen; i++){
            const dataset = datasets[i];
            let meta = this.getDatasetMeta(i);
            const type = dataset.type || this.config.type;
            if (meta.type && meta.type !== type) {
                this._destroyDatasetMeta(i);
                meta = this.getDatasetMeta(i);
            }
            meta.type = type;
            meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options);
            meta.order = dataset.order || 0;
            meta.index = i;
            meta.label = '' + dataset.label;
            meta.visible = this.isDatasetVisible(i);
            if (meta.controller) {
                meta.controller.updateIndex(i);
                meta.controller.linkScales();
            } else {
                const ControllerClass = registry.getController(type);
                const { datasetElementType , dataElementType  } = defaults.datasets[type];
                Object.assign(ControllerClass, {
                    dataElementType: registry.getElement(dataElementType),
                    datasetElementType: datasetElementType && registry.getElement(datasetElementType)
                });
                meta.controller = new ControllerClass(this, i);
                newControllers.push(meta.controller);
            }
        }
        this._updateMetasets();
        return newControllers;
    }
 _resetElements() {
        each(this.data.datasets, (dataset, datasetIndex)=>{
            this.getDatasetMeta(datasetIndex).controller.reset();
        }, this);
    }
 reset() {
        this._resetElements();
        this.notifyPlugins('reset');
    }
    update(mode) {
        const config = this.config;
        config.update();
        const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext());
        const animsDisabled = this._animationsDisabled = !options.animation;
        this._updateScales();
        this._checkEventBindings();
        this._updateHiddenIndices();
        this._plugins.invalidate();
        if (this.notifyPlugins('beforeUpdate', {
            mode,
            cancelable: true
        }) === false) {
            return;
        }
        const newControllers = this.buildOrUpdateControllers();
        this.notifyPlugins('beforeElementsUpdate');
        let minPadding = 0;
        for(let i = 0, ilen = this.data.datasets.length; i < ilen; i++){
            const { controller  } = this.getDatasetMeta(i);
            const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
            controller.buildOrUpdateElements(reset);
            minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
        }
        minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0;
        this._updateLayout(minPadding);
        if (!animsDisabled) {
            each(newControllers, (controller)=>{
                controller.reset();
            });
        }
        this._updateDatasets(mode);
        this.notifyPlugins('afterUpdate', {
            mode
        });
        this._layers.sort(compare2Level('z', '_idx'));
        const { _active , _lastEvent  } = this;
        if (_lastEvent) {
            this._eventHandler(_lastEvent, true);
        } else if (_active.length) {
            this._updateHoverStyles(_active, _active, true);
        }
        this.render();
    }
 _updateScales() {
        each(this.scales, (scale)=>{
            layouts.removeBox(this, scale);
        });
        this.ensureScalesHaveIDs();
        this.buildOrUpdateScales();
    }
 _checkEventBindings() {
        const options = this.options;
        const existingEvents = new Set(Object.keys(this._listeners));
        const newEvents = new Set(options.events);
        if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) {
            this.unbindEvents();
            this.bindEvents();
        }
    }
 _updateHiddenIndices() {
        const { _hiddenIndices  } = this;
        const changes = this._getUniformDataChanges() || [];
        for (const { method , start , count  } of changes){
            const move = method === '_removeElements' ? -count : count;
            moveNumericKeys(_hiddenIndices, start, move);
        }
    }
 _getUniformDataChanges() {
        const _dataChanges = this._dataChanges;
        if (!_dataChanges || !_dataChanges.length) {
            return;
        }
        this._dataChanges = [];
        const datasetCount = this.data.datasets.length;
        const makeSet = (idx)=>new Set(_dataChanges.filter((c)=>c[0] === idx).map((c, i)=>i + ',' + c.splice(1).join(',')));
        const changeSet = makeSet(0);
        for(let i = 1; i < datasetCount; i++){
            if (!setsEqual(changeSet, makeSet(i))) {
                return;
            }
        }
        return Array.from(changeSet).map((c)=>c.split(',')).map((a)=>({
                method: a[1],
                start: +a[2],
                count: +a[3]
            }));
    }
 _updateLayout(minPadding) {
        if (this.notifyPlugins('beforeLayout', {
            cancelable: true
        }) === false) {
            return;
        }
        layouts.update(this, this.width, this.height, minPadding);
        const area = this.chartArea;
        const noArea = area.width <= 0 || area.height <= 0;
        this._layers = [];
        each(this.boxes, (box)=>{
            if (noArea && box.position === 'chartArea') {
                return;
            }
            if (box.configure) {
                box.configure();
            }
            this._layers.push(...box._layers());
        }, this);
        this._layers.forEach((item, index)=>{
            item._idx = index;
        });
        this.notifyPlugins('afterLayout');
    }
 _updateDatasets(mode) {
        if (this.notifyPlugins('beforeDatasetsUpdate', {
            mode,
            cancelable: true
        }) === false) {
            return;
        }
        for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
            this.getDatasetMeta(i).controller.configure();
        }
        for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
            this._updateDataset(i, isFunction(mode) ? mode({
                datasetIndex: i
            }) : mode);
        }
        this.notifyPlugins('afterDatasetsUpdate', {
            mode
        });
    }
 _updateDataset(index, mode) {
        const meta = this.getDatasetMeta(index);
        const args = {
            meta,
            index,
            mode,
            cancelable: true
        };
        if (this.notifyPlugins('beforeDatasetUpdate', args) === false) {
            return;
        }
        meta.controller._update(mode);
        args.cancelable = false;
        this.notifyPlugins('afterDatasetUpdate', args);
    }
    render() {
        if (this.notifyPlugins('beforeRender', {
            cancelable: true
        }) === false) {
            return;
        }
        if (animator.has(this)) {
            if (this.attached && !animator.running(this)) {
                animator.start(this);
            }
        } else {
            this.draw();
            onAnimationsComplete({
                chart: this
            });
        }
    }
    draw() {
        let i;
        if (this._resizeBeforeDraw) {
            const { width , height  } = this._resizeBeforeDraw;
            this._resizeBeforeDraw = null;
            this._resize(width, height);
        }
        this.clear();
        if (this.width <= 0 || this.height <= 0) {
            return;
        }
        if (this.notifyPlugins('beforeDraw', {
            cancelable: true
        }) === false) {
            return;
        }
        const layers = this._layers;
        for(i = 0; i < layers.length && layers[i].z <= 0; ++i){
            layers[i].draw(this.chartArea);
        }
        this._drawDatasets();
        for(; i < layers.length; ++i){
            layers[i].draw(this.chartArea);
        }
        this.notifyPlugins('afterDraw');
    }
 _getSortedDatasetMetas(filterVisible) {
        const metasets = this._sortedMetasets;
        const result = [];
        let i, ilen;
        for(i = 0, ilen = metasets.length; i < ilen; ++i){
            const meta = metasets[i];
            if (!filterVisible || meta.visible) {
                result.push(meta);
            }
        }
        return result;
    }
 getSortedVisibleDatasetMetas() {
        return this._getSortedDatasetMetas(true);
    }
 _drawDatasets() {
        if (this.notifyPlugins('beforeDatasetsDraw', {
            cancelable: true
        }) === false) {
            return;
        }
        const metasets = this.getSortedVisibleDatasetMetas();
        for(let i = metasets.length - 1; i >= 0; --i){
            this._drawDataset(metasets[i]);
        }
        this.notifyPlugins('afterDatasetsDraw');
    }
 _drawDataset(meta) {
        const ctx = this.ctx;
        const args = {
            meta,
            index: meta.index,
            cancelable: true
        };
        const clip = getDatasetClipArea(this, meta);
        if (this.notifyPlugins('beforeDatasetDraw', args) === false) {
            return;
        }
        if (clip) {
            clipArea(ctx, clip);
        }
        meta.controller.draw();
        if (clip) {
            unclipArea(ctx);
        }
        args.cancelable = false;
        this.notifyPlugins('afterDatasetDraw', args);
    }
 isPointInArea(point) {
        return _isPointInArea(point, this.chartArea, this._minPadding);
    }
    getElementsAtEventForMode(e, mode, options, useFinalPosition) {
        const method = Interaction.modes[mode];
        if (typeof method === 'function') {
            return method(this, e, options, useFinalPosition);
        }
        return [];
    }
    getDatasetMeta(datasetIndex) {
        const dataset = this.data.datasets[datasetIndex];
        const metasets = this._metasets;
        let meta = metasets.filter((x)=>x && x._dataset === dataset).pop();
        if (!meta) {
            meta = {
                type: null,
                data: [],
                dataset: null,
                controller: null,
                hidden: null,
                xAxisID: null,
                yAxisID: null,
                order: dataset && dataset.order || 0,
                index: datasetIndex,
                _dataset: dataset,
                _parsed: [],
                _sorted: false
            };
            metasets.push(meta);
        }
        return meta;
    }
    getContext() {
        return this.$context || (this.$context = createContext(null, {
            chart: this,
            type: 'chart'
        }));
    }
    getVisibleDatasetCount() {
        return this.getSortedVisibleDatasetMetas().length;
    }
    isDatasetVisible(datasetIndex) {
        const dataset = this.data.datasets[datasetIndex];
        if (!dataset) {
            return false;
        }
        const meta = this.getDatasetMeta(datasetIndex);
        return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;
    }
    setDatasetVisibility(datasetIndex, visible) {
        const meta = this.getDatasetMeta(datasetIndex);
        meta.hidden = !visible;
    }
    toggleDataVisibility(index) {
        this._hiddenIndices[index] = !this._hiddenIndices[index];
    }
    getDataVisibility(index) {
        return !this._hiddenIndices[index];
    }
 _updateVisibility(datasetIndex, dataIndex, visible) {
        const mode = visible ? 'show' : 'hide';
        const meta = this.getDatasetMeta(datasetIndex);
        const anims = meta.controller._resolveAnimations(undefined, mode);
        if (defined(dataIndex)) {
            meta.data[dataIndex].hidden = !visible;
            this.update();
        } else {
            this.setDatasetVisibility(datasetIndex, visible);
            anims.update(meta, {
                visible
            });
            this.update((ctx)=>ctx.datasetIndex === datasetIndex ? mode : undefined);
        }
    }
    hide(datasetIndex, dataIndex) {
        this._updateVisibility(datasetIndex, dataIndex, false);
    }
    show(datasetIndex, dataIndex) {
        this._updateVisibility(datasetIndex, dataIndex, true);
    }
 _destroyDatasetMeta(datasetIndex) {
        const meta = this._metasets[datasetIndex];
        if (meta && meta.controller) {
            meta.controller._destroy();
        }
        delete this._metasets[datasetIndex];
    }
    _stop() {
        let i, ilen;
        this.stop();
        animator.remove(this);
        for(i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
            this._destroyDatasetMeta(i);
        }
    }
    destroy() {
        this.notifyPlugins('beforeDestroy');
        const { canvas , ctx  } = this;
        this._stop();
        this.config.clearCache();
        if (canvas) {
            this.unbindEvents();
            clearCanvas(canvas, ctx);
            this.platform.releaseContext(ctx);
            this.canvas = null;
            this.ctx = null;
        }
        delete instances[this.id];
        this.notifyPlugins('afterDestroy');
    }
    toBase64Image(...args) {
        return this.canvas.toDataURL(...args);
    }
 bindEvents() {
        this.bindUserEvents();
        if (this.options.responsive) {
            this.bindResponsiveEvents();
        } else {
            this.attached = true;
        }
    }
 bindUserEvents() {
        const listeners = this._listeners;
        const platform = this.platform;
        const _add = (type, listener)=>{
            platform.addEventListener(this, type, listener);
            listeners[type] = listener;
        };
        const listener = (e, x, y)=>{
            e.offsetX = x;
            e.offsetY = y;
            this._eventHandler(e);
        };
        each(this.options.events, (type)=>_add(type, listener));
    }
 bindResponsiveEvents() {
        if (!this._responsiveListeners) {
            this._responsiveListeners = {};
        }
        const listeners = this._responsiveListeners;
        const platform = this.platform;
        const _add = (type, listener)=>{
            platform.addEventListener(this, type, listener);
            listeners[type] = listener;
        };
        const _remove = (type, listener)=>{
            if (listeners[type]) {
                platform.removeEventListener(this, type, listener);
                delete listeners[type];
            }
        };
        const listener = (width, height)=>{
            if (this.canvas) {
                this.resize(width, height);
            }
        };
        let detached;
        const attached = ()=>{
            _remove('attach', attached);
            this.attached = true;
            this.resize();
            _add('resize', listener);
            _add('detach', detached);
        };
        detached = ()=>{
            this.attached = false;
            _remove('resize', listener);
            this._stop();
            this._resize(0, 0);
            _add('attach', attached);
        };
        if (platform.isAttached(this.canvas)) {
            attached();
        } else {
            detached();
        }
    }
 unbindEvents() {
        each(this._listeners, (listener, type)=>{
            this.platform.removeEventListener(this, type, listener);
        });
        this._listeners = {};
        each(this._responsiveListeners, (listener, type)=>{
            this.platform.removeEventListener(this, type, listener);
        });
        this._responsiveListeners = undefined;
    }
    updateHoverStyle(items, mode, enabled) {
        const prefix = enabled ? 'set' : 'remove';
        let meta, item, i, ilen;
        if (mode === 'dataset') {
            meta = this.getDatasetMeta(items[0].datasetIndex);
            meta.controller['_' + prefix + 'DatasetHoverStyle']();
        }
        for(i = 0, ilen = items.length; i < ilen; ++i){
            item = items[i];
            const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
            if (controller) {
                controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
            }
        }
    }
 getActiveElements() {
        return this._active || [];
    }
 setActiveElements(activeElements) {
        const lastActive = this._active || [];
        const active = activeElements.map(({ datasetIndex , index  })=>{
            const meta = this.getDatasetMeta(datasetIndex);
            if (!meta) {
                throw new Error('No dataset found at index ' + datasetIndex);
            }
            return {
                datasetIndex,
                element: meta.data[index],
                index
            };
        });
        const changed = !_elementsEqual(active, lastActive);
        if (changed) {
            this._active = active;
            this._lastEvent = null;
            this._updateHoverStyles(active, lastActive);
        }
    }
 notifyPlugins(hook, args, filter) {
        return this._plugins.notify(this, hook, args, filter);
    }
 isPluginEnabled(pluginId) {
        return this._plugins._cache.filter((p)=>p.plugin.id === pluginId).length === 1;
    }
 _updateHoverStyles(active, lastActive, replay) {
        const hoverOptions = this.options.hover;
        const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.datasetIndex === y.datasetIndex && x.index === y.index));
        const deactivated = diff(lastActive, active);
        const activated = replay ? active : diff(active, lastActive);
        if (deactivated.length) {
            this.updateHoverStyle(deactivated, hoverOptions.mode, false);
        }
        if (activated.length && hoverOptions.mode) {
            this.updateHoverStyle(activated, hoverOptions.mode, true);
        }
    }
 _eventHandler(e, replay) {
        const args = {
            event: e,
            replay,
            cancelable: true,
            inChartArea: this.isPointInArea(e)
        };
        const eventFilter = (plugin)=>(plugin.options.events || this.options.events).includes(e.native.type);
        if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) {
            return;
        }
        const changed = this._handleEvent(e, replay, args.inChartArea);
        args.cancelable = false;
        this.notifyPlugins('afterEvent', args, eventFilter);
        if (changed || args.changed) {
            this.render();
        }
        return this;
    }
 _handleEvent(e, replay, inChartArea) {
        const { _active: lastActive = [] , options  } = this;
        const useFinalPosition = replay;
        const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition);
        const isClick = _isClickEvent(e);
        const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick);
        if (inChartArea) {
            this._lastEvent = null;
            callback(options.onHover, [
                e,
                active,
                this
            ], this);
            if (isClick) {
                callback(options.onClick, [
                    e,
                    active,
                    this
                ], this);
            }
        }
        const changed = !_elementsEqual(active, lastActive);
        if (changed || replay) {
            this._active = active;
            this._updateHoverStyles(active, lastActive, replay);
        }
        this._lastEvent = lastEvent;
        return changed;
    }
 _getActiveElements(e, lastActive, inChartArea, useFinalPosition) {
        if (e.type === 'mouseout') {
            return [];
        }
        if (!inChartArea) {
            return lastActive;
        }
        const hoverOptions = this.options.hover;
        return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);
    }
};
function invalidatePlugins() {
    return each(Chart$1.instances, (chart)=>chart._plugins.invalidate());
}

function clipSelf(ctx, element, endAngle) {
    const { startAngle , x , y , outerRadius , innerRadius , options  } = element;
    const { borderWidth , borderJoinStyle  } = options;
    const outerAngleClip = Math.min(borderWidth / outerRadius, _normalizeAngle(startAngle - endAngle));
    ctx.beginPath();
    ctx.arc(x, y, outerRadius - borderWidth / 2, startAngle + outerAngleClip / 2, endAngle - outerAngleClip / 2);
    if (innerRadius > 0) {
        const innerAngleClip = Math.min(borderWidth / innerRadius, _normalizeAngle(startAngle - endAngle));
        ctx.arc(x, y, innerRadius + borderWidth / 2, endAngle - innerAngleClip / 2, startAngle + innerAngleClip / 2, true);
    } else {
        const clipWidth = Math.min(borderWidth / 2, outerRadius * _normalizeAngle(startAngle - endAngle));
        if (borderJoinStyle === 'round') {
            ctx.arc(x, y, clipWidth, endAngle - PI / 2, startAngle + PI / 2, true);
        } else if (borderJoinStyle === 'bevel') {
            const r = 2 * clipWidth * clipWidth;
            const endX = -r * Math.cos(endAngle + PI / 2) + x;
            const endY = -r * Math.sin(endAngle + PI / 2) + y;
            const startX = r * Math.cos(startAngle + PI / 2) + x;
            const startY = r * Math.sin(startAngle + PI / 2) + y;
            ctx.lineTo(endX, endY);
            ctx.lineTo(startX, startY);
        }
    }
    ctx.closePath();
    ctx.moveTo(0, 0);
    ctx.rect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.clip('evenodd');
}
function clipArc(ctx, element, endAngle) {
    const { startAngle , pixelMargin , x , y , outerRadius , innerRadius  } = element;
    let angleMargin = pixelMargin / outerRadius;
    // Draw an inner border by clipping the arc and drawing a double-width border
    // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
    ctx.beginPath();
    ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);
    if (innerRadius > pixelMargin) {
        angleMargin = pixelMargin / innerRadius;
        ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);
    } else {
        ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);
    }
    ctx.closePath();
    ctx.clip();
}
function toRadiusCorners(value) {
    return _readValueToProps(value, [
        'outerStart',
        'outerEnd',
        'innerStart',
        'innerEnd'
    ]);
}
/**
 * Parse border radius from the provided options
 */ function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {
    const o = toRadiusCorners(arc.options.borderRadius);
    const halfThickness = (outerRadius - innerRadius) / 2;
    const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);
    // Outer limits are complicated. We want to compute the available angular distance at
    // a radius of outerRadius - borderRadius because for small angular distances, this term limits.
    // We compute at r = outerRadius - borderRadius because this circle defines the center of the border corners.
    //
    // If the borderRadius is large, that value can become negative.
    // This causes the outer borders to lose their radius entirely, which is rather unexpected. To solve that, if borderRadius > outerRadius
    // we know that the thickness term will dominate and compute the limits at that point
    const computeOuterLimit = (val)=>{
        const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;
        return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));
    };
    return {
        outerStart: computeOuterLimit(o.outerStart),
        outerEnd: computeOuterLimit(o.outerEnd),
        innerStart: _limitValue(o.innerStart, 0, innerLimit),
        innerEnd: _limitValue(o.innerEnd, 0, innerLimit)
    };
}
/**
 * Convert (r, 𝜃) to (x, y)
 */ function rThetaToXY(r, theta, x, y) {
    return {
        x: x + r * Math.cos(theta),
        y: y + r * Math.sin(theta)
    };
}
/**
 * Path the arc, respecting border radius by separating into left and right halves.
 *
 *   Start      End
 *
 *    1--->a--->2    Outer
 *   /           \
 *   8           3
 *   |           |
 *   |           |
 *   7           4
 *   \           /
 *    6<---b<---5    Inner
 */ function pathArc(ctx, element, offset, spacing, end, circular) {
    const { x , y , startAngle: start , pixelMargin , innerRadius: innerR  } = element;
    const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);
    const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;
    let spacingOffset = 0;
    const alpha = end - start;
    if (spacing) {
        // When spacing is present, it is the same for all items
        // So we adjust the start and end angle of the arc such that
        // the distance is the same as it would be without the spacing
        const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;
        const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;
        const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;
        const adjustedAngle = avNogSpacingRadius !== 0 ? alpha * avNogSpacingRadius / (avNogSpacingRadius + spacing) : alpha;
        spacingOffset = (alpha - adjustedAngle) / 2;
    }
    const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius;
    const angleOffset = (alpha - beta) / 2;
    const startAngle = start + angleOffset + spacingOffset;
    const endAngle = end - angleOffset - spacingOffset;
    const { outerStart , outerEnd , innerStart , innerEnd  } = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);
    const outerStartAdjustedRadius = outerRadius - outerStart;
    const outerEndAdjustedRadius = outerRadius - outerEnd;
    const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;
    const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;
    const innerStartAdjustedRadius = innerRadius + innerStart;
    const innerEndAdjustedRadius = innerRadius + innerEnd;
    const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;
    const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;
    ctx.beginPath();
    if (circular) {
        // The first arc segments from point 1 to point a to point 2
        const outerMidAdjustedAngle = (outerStartAdjustedAngle + outerEndAdjustedAngle) / 2;
        ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerMidAdjustedAngle);
        ctx.arc(x, y, outerRadius, outerMidAdjustedAngle, outerEndAdjustedAngle);
        // The corner segment from point 2 to point 3
        if (outerEnd > 0) {
            const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);
            ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);
        }
        // The line from point 3 to point 4
        const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);
        ctx.lineTo(p4.x, p4.y);
        // The corner segment from point 4 to point 5
        if (innerEnd > 0) {
            const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);
            ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);
        }
        // The inner arc from point 5 to point b to point 6
        const innerMidAdjustedAngle = (endAngle - innerEnd / innerRadius + (startAngle + innerStart / innerRadius)) / 2;
        ctx.arc(x, y, innerRadius, endAngle - innerEnd / innerRadius, innerMidAdjustedAngle, true);
        ctx.arc(x, y, innerRadius, innerMidAdjustedAngle, startAngle + innerStart / innerRadius, true);
        // The corner segment from point 6 to point 7
        if (innerStart > 0) {
            const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);
            ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);
        }
        // The line from point 7 to point 8
        const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);
        ctx.lineTo(p8.x, p8.y);
        // The corner segment from point 8 to point 1
        if (outerStart > 0) {
            const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);
            ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);
        }
    } else {
        ctx.moveTo(x, y);
        const outerStartX = Math.cos(outerStartAdjustedAngle) * outerRadius + x;
        const outerStartY = Math.sin(outerStartAdjustedAngle) * outerRadius + y;
        ctx.lineTo(outerStartX, outerStartY);
        const outerEndX = Math.cos(outerEndAdjustedAngle) * outerRadius + x;
        const outerEndY = Math.sin(outerEndAdjustedAngle) * outerRadius + y;
        ctx.lineTo(outerEndX, outerEndY);
    }
    ctx.closePath();
}
function drawArc(ctx, element, offset, spacing, circular) {
    const { fullCircles , startAngle , circumference  } = element;
    let endAngle = element.endAngle;
    if (fullCircles) {
        pathArc(ctx, element, offset, spacing, endAngle, circular);
        for(let i = 0; i < fullCircles; ++i){
            ctx.fill();
        }
        if (!isNaN(circumference)) {
            endAngle = startAngle + (circumference % TAU || TAU);
        }
    }
    pathArc(ctx, element, offset, spacing, endAngle, circular);
    ctx.fill();
    return endAngle;
}
function drawBorder(ctx, element, offset, spacing, circular) {
    const { fullCircles , startAngle , circumference , options  } = element;
    const { borderWidth , borderJoinStyle , borderDash , borderDashOffset , borderRadius  } = options;
    const inner = options.borderAlign === 'inner';
    if (!borderWidth) {
        return;
    }
    ctx.setLineDash(borderDash || []);
    ctx.lineDashOffset = borderDashOffset;
    if (inner) {
        ctx.lineWidth = borderWidth * 2;
        ctx.lineJoin = borderJoinStyle || 'round';
    } else {
        ctx.lineWidth = borderWidth;
        ctx.lineJoin = borderJoinStyle || 'bevel';
    }
    let endAngle = element.endAngle;
    if (fullCircles) {
        pathArc(ctx, element, offset, spacing, endAngle, circular);
        for(let i = 0; i < fullCircles; ++i){
            ctx.stroke();
        }
        if (!isNaN(circumference)) {
            endAngle = startAngle + (circumference % TAU || TAU);
        }
    }
    if (inner) {
        clipArc(ctx, element, endAngle);
    }
    if (options.selfJoin && endAngle - startAngle >= PI && borderRadius === 0 && borderJoinStyle !== 'miter') {
        clipSelf(ctx, element, endAngle);
    }
    if (!fullCircles) {
        pathArc(ctx, element, offset, spacing, endAngle, circular);
        ctx.stroke();
    }
}
class ArcElement extends Element$1 {
    static id = 'arc';
    static defaults = {
        borderAlign: 'center',
        borderColor: '#fff',
        borderDash: [],
        borderDashOffset: 0,
        borderJoinStyle: undefined,
        borderRadius: 0,
        borderWidth: 2,
        offset: 0,
        spacing: 0,
        angle: undefined,
        circular: true,
        selfJoin: false
    };
    static defaultRoutes = {
        backgroundColor: 'backgroundColor'
    };
    static descriptors = {
        _scriptable: true,
        _indexable: (name)=>name !== 'borderDash'
    };
    circumference;
    endAngle;
    fullCircles;
    innerRadius;
    outerRadius;
    pixelMargin;
    startAngle;
    constructor(cfg){
        super();
        this.options = undefined;
        this.circumference = undefined;
        this.startAngle = undefined;
        this.endAngle = undefined;
        this.innerRadius = undefined;
        this.outerRadius = undefined;
        this.pixelMargin = 0;
        this.fullCircles = 0;
        if (cfg) {
            Object.assign(this, cfg);
        }
    }
    inRange(chartX, chartY, useFinalPosition) {
        const point = this.getProps([
            'x',
            'y'
        ], useFinalPosition);
        const { angle , distance  } = getAngleFromPoint(point, {
            x: chartX,
            y: chartY
        });
        const { startAngle , endAngle , innerRadius , outerRadius , circumference  } = this.getProps([
            'startAngle',
            'endAngle',
            'innerRadius',
            'outerRadius',
            'circumference'
        ], useFinalPosition);
        const rAdjust = (this.options.spacing + this.options.borderWidth) / 2;
        const _circumference = valueOrDefault(circumference, endAngle - startAngle);
        const nonZeroBetween = _angleBetween(angle, startAngle, endAngle) && startAngle !== endAngle;
        const betweenAngles = _circumference >= TAU || nonZeroBetween;
        const withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust);
        return betweenAngles && withinRadius;
    }
    getCenterPoint(useFinalPosition) {
        const { x , y , startAngle , endAngle , innerRadius , outerRadius  } = this.getProps([
            'x',
            'y',
            'startAngle',
            'endAngle',
            'innerRadius',
            'outerRadius'
        ], useFinalPosition);
        const { offset , spacing  } = this.options;
        const halfAngle = (startAngle + endAngle) / 2;
        const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2;
        return {
            x: x + Math.cos(halfAngle) * halfRadius,
            y: y + Math.sin(halfAngle) * halfRadius
        };
    }
    tooltipPosition(useFinalPosition) {
        return this.getCenterPoint(useFinalPosition);
    }
    draw(ctx) {
        const { options , circumference  } = this;
        const offset = (options.offset || 0) / 4;
        const spacing = (options.spacing || 0) / 2;
        const circular = options.circular;
        this.pixelMargin = options.borderAlign === 'inner' ? 0.33 : 0;
        this.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0;
        if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) {
            return;
        }
        ctx.save();
        const halfAngle = (this.startAngle + this.endAngle) / 2;
        ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset);
        const fix = 1 - Math.sin(Math.min(PI, circumference || 0));
        const radiusOffset = offset * fix;
        ctx.fillStyle = options.backgroundColor;
        ctx.strokeStyle = options.borderColor;
        drawArc(ctx, this, radiusOffset, spacing, circular);
        drawBorder(ctx, this, radiusOffset, spacing, circular);
        ctx.restore();
    }
}

function setStyle(ctx, options, style = options) {
    ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);
    ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));
    ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);
    ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);
    ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);
    ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);
}
function lineTo(ctx, previous, target) {
    ctx.lineTo(target.x, target.y);
}
 function getLineMethod(options) {
    if (options.stepped) {
        return _steppedLineTo;
    }
    if (options.tension || options.cubicInterpolationMode === 'monotone') {
        return _bezierCurveTo;
    }
    return lineTo;
}
function pathVars(points, segment, params = {}) {
    const count = points.length;
    const { start: paramsStart = 0 , end: paramsEnd = count - 1  } = params;
    const { start: segmentStart , end: segmentEnd  } = segment;
    const start = Math.max(paramsStart, segmentStart);
    const end = Math.min(paramsEnd, segmentEnd);
    const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;
    return {
        count,
        start,
        loop: segment.loop,
        ilen: end < start && !outside ? count + end - start : end - start
    };
}
 function pathSegment(ctx, line, segment, params) {
    const { points , options  } = line;
    const { count , start , loop , ilen  } = pathVars(points, segment, params);
    const lineMethod = getLineMethod(options);
    let { move =true , reverse  } = params || {};
    let i, point, prev;
    for(i = 0; i <= ilen; ++i){
        point = points[(start + (reverse ? ilen - i : i)) % count];
        if (point.skip) {
            continue;
        } else if (move) {
            ctx.moveTo(point.x, point.y);
            move = false;
        } else {
            lineMethod(ctx, prev, point, reverse, options.stepped);
        }
        prev = point;
    }
    if (loop) {
        point = points[(start + (reverse ? ilen : 0)) % count];
        lineMethod(ctx, prev, point, reverse, options.stepped);
    }
    return !!loop;
}
 function fastPathSegment(ctx, line, segment, params) {
    const points = line.points;
    const { count , start , ilen  } = pathVars(points, segment, params);
    const { move =true , reverse  } = params || {};
    let avgX = 0;
    let countX = 0;
    let i, point, prevX, minY, maxY, lastY;
    const pointIndex = (index)=>(start + (reverse ? ilen - index : index)) % count;
    const drawX = ()=>{
        if (minY !== maxY) {
            ctx.lineTo(avgX, maxY);
            ctx.lineTo(avgX, minY);
            ctx.lineTo(avgX, lastY);
        }
    };
    if (move) {
        point = points[pointIndex(0)];
        ctx.moveTo(point.x, point.y);
    }
    for(i = 0; i <= ilen; ++i){
        point = points[pointIndex(i)];
        if (point.skip) {
            continue;
        }
        const x = point.x;
        const y = point.y;
        const truncX = x | 0;
        if (truncX === prevX) {
            if (y < minY) {
                minY = y;
            } else if (y > maxY) {
                maxY = y;
            }
            avgX = (countX * avgX + x) / ++countX;
        } else {
            drawX();
            ctx.lineTo(x, y);
            prevX = truncX;
            countX = 0;
            minY = maxY = y;
        }
        lastY = y;
    }
    drawX();
}
 function _getSegmentMethod(line) {
    const opts = line.options;
    const borderDash = opts.borderDash && opts.borderDash.length;
    const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;
    return useFastPath ? fastPathSegment : pathSegment;
}
 function _getInterpolationMethod(options) {
    if (options.stepped) {
        return _steppedInterpolation;
    }
    if (options.tension || options.cubicInterpolationMode === 'monotone') {
        return _bezierInterpolation;
    }
    return _pointInLine;
}
function strokePathWithCache(ctx, line, start, count) {
    let path = line._path;
    if (!path) {
        path = line._path = new Path2D();
        if (line.path(path, start, count)) {
            path.closePath();
        }
    }
    setStyle(ctx, line.options);
    ctx.stroke(path);
}
function strokePathDirect(ctx, line, start, count) {
    const { segments , options  } = line;
    const segmentMethod = _getSegmentMethod(line);
    for (const segment of segments){
        setStyle(ctx, options, segment.style);
        ctx.beginPath();
        if (segmentMethod(ctx, line, segment, {
            start,
            end: start + count - 1
        })) {
            ctx.closePath();
        }
        ctx.stroke();
    }
}
const usePath2D = typeof Path2D === 'function';
function draw(ctx, line, start, count) {
    if (usePath2D && !line.options.segment) {
        strokePathWithCache(ctx, line, start, count);
    } else {
        strokePathDirect(ctx, line, start, count);
    }
}
class LineElement extends Element$1 {
    static id = 'line';
 static defaults = {
        borderCapStyle: 'butt',
        borderDash: [],
        borderDashOffset: 0,
        borderJoinStyle: 'miter',
        borderWidth: 3,
        capBezierPoints: true,
        cubicInterpolationMode: 'default',
        fill: false,
        spanGaps: false,
        stepped: false,
        tension: 0
    };
 static defaultRoutes = {
        backgroundColor: 'backgroundColor',
        borderColor: 'borderColor'
    };
    static descriptors = {
        _scriptable: true,
        _indexable: (name)=>name !== 'borderDash' && name !== 'fill'
    };
    constructor(cfg){
        super();
        this.animated = true;
        this.options = undefined;
        this._chart = undefined;
        this._loop = undefined;
        this._fullLoop = undefined;
        this._path = undefined;
        this._points = undefined;
        this._segments = undefined;
        this._decimated = false;
        this._pointsUpdated = false;
        this._datasetIndex = undefined;
        if (cfg) {
            Object.assign(this, cfg);
        }
    }
    updateControlPoints(chartArea, indexAxis) {
        const options = this.options;
        if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) {
            const loop = options.spanGaps ? this._loop : this._fullLoop;
            _updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis);
            this._pointsUpdated = true;
        }
    }
    set points(points) {
        this._points = points;
        delete this._segments;
        delete this._path;
        this._pointsUpdated = false;
    }
    get points() {
        return this._points;
    }
    get segments() {
        return this._segments || (this._segments = _computeSegments(this, this.options.segment));
    }
 first() {
        const segments = this.segments;
        const points = this.points;
        return segments.length && points[segments[0].start];
    }
 last() {
        const segments = this.segments;
        const points = this.points;
        const count = segments.length;
        return count && points[segments[count - 1].end];
    }
 interpolate(point, property) {
        const options = this.options;
        const value = point[property];
        const points = this.points;
        const segments = _boundSegments(this, {
            property,
            start: value,
            end: value
        });
        if (!segments.length) {
            return;
        }
        const result = [];
        const _interpolate = _getInterpolationMethod(options);
        let i, ilen;
        for(i = 0, ilen = segments.length; i < ilen; ++i){
            const { start , end  } = segments[i];
            const p1 = points[start];
            const p2 = points[end];
            if (p1 === p2) {
                result.push(p1);
                continue;
            }
            const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
            const interpolated = _interpolate(p1, p2, t, options.stepped);
            interpolated[property] = point[property];
            result.push(interpolated);
        }
        return result.length === 1 ? result[0] : result;
    }
 pathSegment(ctx, segment, params) {
        const segmentMethod = _getSegmentMethod(this);
        return segmentMethod(ctx, this, segment, params);
    }
 path(ctx, start, count) {
        const segments = this.segments;
        const segmentMethod = _getSegmentMethod(this);
        let loop = this._loop;
        start = start || 0;
        count = count || this.points.length - start;
        for (const segment of segments){
            loop &= segmentMethod(ctx, this, segment, {
                start,
                end: start + count - 1
            });
        }
        return !!loop;
    }
 draw(ctx, chartArea, start, count) {
        const options = this.options || {};
        const points = this.points || [];
        if (points.length && options.borderWidth) {
            ctx.save();
            draw(ctx, this, start, count);
            ctx.restore();
        }
        if (this.animated) {
            this._pointsUpdated = false;
            this._path = undefined;
        }
    }
}

function inRange$1(el, pos, axis, useFinalPosition) {
    const options = el.options;
    const { [axis]: value  } = el.getProps([
        axis
    ], useFinalPosition);
    return Math.abs(pos - value) < options.radius + options.hitRadius;
}
class PointElement extends Element$1 {
    static id = 'point';
    parsed;
    skip;
    stop;
    /**
   * @type {any}
   */ static defaults = {
        borderWidth: 1,
        hitRadius: 1,
        hoverBorderWidth: 1,
        hoverRadius: 4,
        pointStyle: 'circle',
        radius: 3,
        rotation: 0
    };
    /**
   * @type {any}
   */ static defaultRoutes = {
        backgroundColor: 'backgroundColor',
        borderColor: 'borderColor'
    };
    constructor(cfg){
        super();
        this.options = undefined;
        this.parsed = undefined;
        this.skip = undefined;
        this.stop = undefined;
        if (cfg) {
            Object.assign(this, cfg);
        }
    }
    inRange(mouseX, mouseY, useFinalPosition) {
        const options = this.options;
        const { x , y  } = this.getProps([
            'x',
            'y'
        ], useFinalPosition);
        return Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2) < Math.pow(options.hitRadius + options.radius, 2);
    }
    inXRange(mouseX, useFinalPosition) {
        return inRange$1(this, mouseX, 'x', useFinalPosition);
    }
    inYRange(mouseY, useFinalPosition) {
        return inRange$1(this, mouseY, 'y', useFinalPosition);
    }
    getCenterPoint(useFinalPosition) {
        const { x , y  } = this.getProps([
            'x',
            'y'
        ], useFinalPosition);
        return {
            x,
            y
        };
    }
    size(options) {
        options = options || this.options || {};
        let radius = options.radius || 0;
        radius = Math.max(radius, radius && options.hoverRadius || 0);
        const borderWidth = radius && options.borderWidth || 0;
        return (radius + borderWidth) * 2;
    }
    draw(ctx, area) {
        const options = this.options;
        if (this.skip || options.radius < 0.1 || !_isPointInArea(this, area, this.size(options) / 2)) {
            return;
        }
        ctx.strokeStyle = options.borderColor;
        ctx.lineWidth = options.borderWidth;
        ctx.fillStyle = options.backgroundColor;
        drawPoint(ctx, options, this.x, this.y);
    }
    getRange() {
        const options = this.options || {};
        // @ts-expect-error Fallbacks should never be hit in practice
        return options.radius + options.hitRadius;
    }
}

function getBarBounds(bar, useFinalPosition) {
    const { x , y , base , width , height  } =  bar.getProps([
        'x',
        'y',
        'base',
        'width',
        'height'
    ], useFinalPosition);
    let left, right, top, bottom, half;
    if (bar.horizontal) {
        half = height / 2;
        left = Math.min(x, base);
        right = Math.max(x, base);
        top = y - half;
        bottom = y + half;
    } else {
        half = width / 2;
        left = x - half;
        right = x + half;
        top = Math.min(y, base);
        bottom = Math.max(y, base);
    }
    return {
        left,
        top,
        right,
        bottom
    };
}
function skipOrLimit(skip, value, min, max) {
    return skip ? 0 : _limitValue(value, min, max);
}
function parseBorderWidth(bar, maxW, maxH) {
    const value = bar.options.borderWidth;
    const skip = bar.borderSkipped;
    const o = toTRBL(value);
    return {
        t: skipOrLimit(skip.top, o.top, 0, maxH),
        r: skipOrLimit(skip.right, o.right, 0, maxW),
        b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),
        l: skipOrLimit(skip.left, o.left, 0, maxW)
    };
}
function parseBorderRadius(bar, maxW, maxH) {
    const { enableBorderRadius  } = bar.getProps([
        'enableBorderRadius'
    ]);
    const value = bar.options.borderRadius;
    const o = toTRBLCorners(value);
    const maxR = Math.min(maxW, maxH);
    const skip = bar.borderSkipped;
    const enableBorder = enableBorderRadius || isObject(value);
    return {
        topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),
        topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),
        bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),
        bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)
    };
}
function boundingRects(bar) {
    const bounds = getBarBounds(bar);
    const width = bounds.right - bounds.left;
    const height = bounds.bottom - bounds.top;
    const border = parseBorderWidth(bar, width / 2, height / 2);
    const radius = parseBorderRadius(bar, width / 2, height / 2);
    return {
        outer: {
            x: bounds.left,
            y: bounds.top,
            w: width,
            h: height,
            radius
        },
        inner: {
            x: bounds.left + border.l,
            y: bounds.top + border.t,
            w: width - border.l - border.r,
            h: height - border.t - border.b,
            radius: {
                topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),
                topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),
                bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),
                bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r))
            }
        }
    };
}
function inRange(bar, x, y, useFinalPosition) {
    const skipX = x === null;
    const skipY = y === null;
    const skipBoth = skipX && skipY;
    const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);
    return bounds && (skipX || _isBetween(x, bounds.left, bounds.right)) && (skipY || _isBetween(y, bounds.top, bounds.bottom));
}
function hasRadius(radius) {
    return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;
}
 function addNormalRectPath(ctx, rect) {
    ctx.rect(rect.x, rect.y, rect.w, rect.h);
}
function inflateRect(rect, amount, refRect = {}) {
    const x = rect.x !== refRect.x ? -amount : 0;
    const y = rect.y !== refRect.y ? -amount : 0;
    const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x;
    const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y;
    return {
        x: rect.x + x,
        y: rect.y + y,
        w: rect.w + w,
        h: rect.h + h,
        radius: rect.radius
    };
}
class BarElement extends Element$1 {
    static id = 'bar';
 static defaults = {
        borderSkipped: 'start',
        borderWidth: 0,
        borderRadius: 0,
        inflateAmount: 'auto',
        pointStyle: undefined
    };
 static defaultRoutes = {
        backgroundColor: 'backgroundColor',
        borderColor: 'borderColor'
    };
    constructor(cfg){
        super();
        this.options = undefined;
        this.horizontal = undefined;
        this.base = undefined;
        this.width = undefined;
        this.height = undefined;
        this.inflateAmount = undefined;
        if (cfg) {
            Object.assign(this, cfg);
        }
    }
    draw(ctx) {
        const { inflateAmount , options: { borderColor , backgroundColor  }  } = this;
        const { inner , outer  } = boundingRects(this);
        const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;
        ctx.save();
        if (outer.w !== inner.w || outer.h !== inner.h) {
            ctx.beginPath();
            addRectPath(ctx, inflateRect(outer, inflateAmount, inner));
            ctx.clip();
            addRectPath(ctx, inflateRect(inner, -inflateAmount, outer));
            ctx.fillStyle = borderColor;
            ctx.fill('evenodd');
        }
        ctx.beginPath();
        addRectPath(ctx, inflateRect(inner, inflateAmount));
        ctx.fillStyle = backgroundColor;
        ctx.fill();
        ctx.restore();
    }
    inRange(mouseX, mouseY, useFinalPosition) {
        return inRange(this, mouseX, mouseY, useFinalPosition);
    }
    inXRange(mouseX, useFinalPosition) {
        return inRange(this, mouseX, null, useFinalPosition);
    }
    inYRange(mouseY, useFinalPosition) {
        return inRange(this, null, mouseY, useFinalPosition);
    }
    getCenterPoint(useFinalPosition) {
        const { x , y , base , horizontal  } =  this.getProps([
            'x',
            'y',
            'base',
            'horizontal'
        ], useFinalPosition);
        return {
            x: horizontal ? (x + base) / 2 : x,
            y: horizontal ? y : (y + base) / 2
        };
    }
    getRange(axis) {
        return axis === 'x' ? this.width / 2 : this.height / 2;
    }
}

var elements = /*#__PURE__*/Object.freeze({
__proto__: null,
ArcElement: ArcElement,
BarElement: BarElement,
LineElement: LineElement,
PointElement: PointElement
});

const BORDER_COLORS = [
    'rgb(54, 162, 235)',
    'rgb(255, 99, 132)',
    'rgb(255, 159, 64)',
    'rgb(255, 205, 86)',
    'rgb(75, 192, 192)',
    'rgb(153, 102, 255)',
    'rgb(201, 203, 207)' // grey
];
// Border colors with 50% transparency
const BACKGROUND_COLORS = /* #__PURE__ */ BORDER_COLORS.map((color)=>color.replace('rgb(', 'rgba(').replace(')', ', 0.5)'));
function getBorderColor(i) {
    return BORDER_COLORS[i % BORDER_COLORS.length];
}
function getBackgroundColor(i) {
    return BACKGROUND_COLORS[i % BACKGROUND_COLORS.length];
}
function colorizeDefaultDataset(dataset, i) {
    dataset.borderColor = getBorderColor(i);
    dataset.backgroundColor = getBackgroundColor(i);
    return ++i;
}
function colorizeDoughnutDataset(dataset, i) {
    dataset.backgroundColor = dataset.data.map(()=>getBorderColor(i++));
    return i;
}
function colorizePolarAreaDataset(dataset, i) {
    dataset.backgroundColor = dataset.data.map(()=>getBackgroundColor(i++));
    return i;
}
function getColorizer(chart) {
    let i = 0;
    return (dataset, datasetIndex)=>{
        const controller = chart.getDatasetMeta(datasetIndex).controller;
        if (controller instanceof DoughnutController) {
            i = colorizeDoughnutDataset(dataset, i);
        } else if (controller instanceof PolarAreaController) {
            i = colorizePolarAreaDataset(dataset, i);
        } else if (controller) {
            i = colorizeDefaultDataset(dataset, i);
        }
    };
}
function containsColorsDefinitions(descriptors) {
    let k;
    for(k in descriptors){
        if (descriptors[k].borderColor || descriptors[k].backgroundColor) {
            return true;
        }
    }
    return false;
}
function containsColorsDefinition(descriptor) {
    return descriptor && (descriptor.borderColor || descriptor.backgroundColor);
}
function containsDefaultColorsDefenitions() {
    return defaults.borderColor !== 'rgba(0,0,0,0.1)' || defaults.backgroundColor !== 'rgba(0,0,0,0.1)';
}
var plugin_colors = {
    id: 'colors',
    defaults: {
        enabled: true,
        forceOverride: false
    },
    beforeLayout (chart, _args, options) {
        if (!options.enabled) {
            return;
        }
        const { data: { datasets  } , options: chartOptions  } = chart.config;
        const { elements  } = chartOptions;
        const containsColorDefenition = containsColorsDefinitions(datasets) || containsColorsDefinition(chartOptions) || elements && containsColorsDefinitions(elements) || containsDefaultColorsDefenitions();
        if (!options.forceOverride && containsColorDefenition) {
            return;
        }
        const colorizer = getColorizer(chart);
        datasets.forEach(colorizer);
    }
};

function lttbDecimation(data, start, count, availableWidth, options) {
 const samples = options.samples || availableWidth;
    if (samples >= count) {
        return data.slice(start, start + count);
    }
    const decimated = [];
    const bucketWidth = (count - 2) / (samples - 2);
    let sampledIndex = 0;
    const endIndex = start + count - 1;
    let a = start;
    let i, maxAreaPoint, maxArea, area, nextA;
    decimated[sampledIndex++] = data[a];
    for(i = 0; i < samples - 2; i++){
        let avgX = 0;
        let avgY = 0;
        let j;
        const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;
        const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;
        const avgRangeLength = avgRangeEnd - avgRangeStart;
        for(j = avgRangeStart; j < avgRangeEnd; j++){
            avgX += data[j].x;
            avgY += data[j].y;
        }
        avgX /= avgRangeLength;
        avgY /= avgRangeLength;
        const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;
        const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start;
        const { x: pointAx , y: pointAy  } = data[a];
        maxArea = area = -1;
        for(j = rangeOffs; j < rangeTo; j++){
            area = 0.5 * Math.abs((pointAx - avgX) * (data[j].y - pointAy) - (pointAx - data[j].x) * (avgY - pointAy));
            if (area > maxArea) {
                maxArea = area;
                maxAreaPoint = data[j];
                nextA = j;
            }
        }
        decimated[sampledIndex++] = maxAreaPoint;
        a = nextA;
    }
    decimated[sampledIndex++] = data[endIndex];
    return decimated;
}
function minMaxDecimation(data, start, count, availableWidth) {
    let avgX = 0;
    let countX = 0;
    let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;
    const decimated = [];
    const endIndex = start + count - 1;
    const xMin = data[start].x;
    const xMax = data[endIndex].x;
    const dx = xMax - xMin;
    for(i = start; i < start + count; ++i){
        point = data[i];
        x = (point.x - xMin) / dx * availableWidth;
        y = point.y;
        const truncX = x | 0;
        if (truncX === prevX) {
            if (y < minY) {
                minY = y;
                minIndex = i;
            } else if (y > maxY) {
                maxY = y;
                maxIndex = i;
            }
            avgX = (countX * avgX + point.x) / ++countX;
        } else {
            const lastIndex = i - 1;
            if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {
                const intermediateIndex1 = Math.min(minIndex, maxIndex);
                const intermediateIndex2 = Math.max(minIndex, maxIndex);
                if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
                    decimated.push({
                        ...data[intermediateIndex1],
                        x: avgX
                    });
                }
                if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {
                    decimated.push({
                        ...data[intermediateIndex2],
                        x: avgX
                    });
                }
            }
            if (i > 0 && lastIndex !== startIndex) {
                decimated.push(data[lastIndex]);
            }
            decimated.push(point);
            prevX = truncX;
            countX = 0;
            minY = maxY = y;
            minIndex = maxIndex = startIndex = i;
        }
    }
    return decimated;
}
function cleanDecimatedDataset(dataset) {
    if (dataset._decimated) {
        const data = dataset._data;
        delete dataset._decimated;
        delete dataset._data;
        Object.defineProperty(dataset, 'data', {
            configurable: true,
            enumerable: true,
            writable: true,
            value: data
        });
    }
}
function cleanDecimatedData(chart) {
    chart.data.datasets.forEach((dataset)=>{
        cleanDecimatedDataset(dataset);
    });
}
function getStartAndCountOfVisiblePointsSimplified(meta, points) {
    const pointCount = points.length;
    let start = 0;
    let count;
    const { iScale  } = meta;
    const { min , max , minDefined , maxDefined  } = iScale.getUserBounds();
    if (minDefined) {
        start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);
    }
    if (maxDefined) {
        count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;
    } else {
        count = pointCount - start;
    }
    return {
        start,
        count
    };
}
var plugin_decimation = {
    id: 'decimation',
    defaults: {
        algorithm: 'min-max',
        enabled: false
    },
    beforeElementsUpdate: (chart, args, options)=>{
        if (!options.enabled) {
            cleanDecimatedData(chart);
            return;
        }
        const availableWidth = chart.width;
        chart.data.datasets.forEach((dataset, datasetIndex)=>{
            const { _data , indexAxis  } = dataset;
            const meta = chart.getDatasetMeta(datasetIndex);
            const data = _data || dataset.data;
            if (resolve([
                indexAxis,
                chart.options.indexAxis
            ]) === 'y') {
                return;
            }
            if (!meta.controller.supportsDecimation) {
                return;
            }
            const xAxis = chart.scales[meta.xAxisID];
            if (xAxis.type !== 'linear' && xAxis.type !== 'time') {
                return;
            }
            if (chart.options.parsing) {
                return;
            }
            let { start , count  } = getStartAndCountOfVisiblePointsSimplified(meta, data);
            const threshold = options.threshold || 4 * availableWidth;
            if (count <= threshold) {
                cleanDecimatedDataset(dataset);
                return;
            }
            if (isNullOrUndef(_data)) {
                dataset._data = data;
                delete dataset.data;
                Object.defineProperty(dataset, 'data', {
                    configurable: true,
                    enumerable: true,
                    get: function() {
                        return this._decimated;
                    },
                    set: function(d) {
                        this._data = d;
                    }
                });
            }
            let decimated;
            switch(options.algorithm){
                case 'lttb':
                    decimated = lttbDecimation(data, start, count, availableWidth, options);
                    break;
                case 'min-max':
                    decimated = minMaxDecimation(data, start, count, availableWidth);
                    break;
                default:
                    throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);
            }
            dataset._decimated = decimated;
        });
    },
    destroy (chart) {
        cleanDecimatedData(chart);
    }
};

function _segments(line, target, property) {
    const segments = line.segments;
    const points = line.points;
    const tpoints = target.points;
    const parts = [];
    for (const segment of segments){
        let { start , end  } = segment;
        end = _findSegmentEnd(start, end, points);
        const bounds = _getBounds(property, points[start], points[end], segment.loop);
        if (!target.segments) {
            parts.push({
                source: segment,
                target: bounds,
                start: points[start],
                end: points[end]
            });
            continue;
        }
        const targetSegments = _boundSegments(target, bounds);
        for (const tgt of targetSegments){
            const subBounds = _getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);
            const fillSources = _boundSegment(segment, points, subBounds);
            for (const fillSource of fillSources){
                parts.push({
                    source: fillSource,
                    target: tgt,
                    start: {
                        [property]: _getEdge(bounds, subBounds, 'start', Math.max)
                    },
                    end: {
                        [property]: _getEdge(bounds, subBounds, 'end', Math.min)
                    }
                });
            }
        }
    }
    return parts;
}
function _getBounds(property, first, last, loop) {
    if (loop) {
        return;
    }
    let start = first[property];
    let end = last[property];
    if (property === 'angle') {
        start = _normalizeAngle(start);
        end = _normalizeAngle(end);
    }
    return {
        property,
        start,
        end
    };
}
function _pointsFromSegments(boundary, line) {
    const { x =null , y =null  } = boundary || {};
    const linePoints = line.points;
    const points = [];
    line.segments.forEach(({ start , end  })=>{
        end = _findSegmentEnd(start, end, linePoints);
        const first = linePoints[start];
        const last = linePoints[end];
        if (y !== null) {
            points.push({
                x: first.x,
                y
            });
            points.push({
                x: last.x,
                y
            });
        } else if (x !== null) {
            points.push({
                x,
                y: first.y
            });
            points.push({
                x,
                y: last.y
            });
        }
    });
    return points;
}
function _findSegmentEnd(start, end, points) {
    for(; end > start; end--){
        const point = points[end];
        if (!isNaN(point.x) && !isNaN(point.y)) {
            break;
        }
    }
    return end;
}
function _getEdge(a, b, prop, fn) {
    if (a && b) {
        return fn(a[prop], b[prop]);
    }
    return a ? a[prop] : b ? b[prop] : 0;
}

function _createBoundaryLine(boundary, line) {
    let points = [];
    let _loop = false;
    if (isArray(boundary)) {
        _loop = true;
        points = boundary;
    } else {
        points = _pointsFromSegments(boundary, line);
    }
    return points.length ? new LineElement({
        points,
        options: {
            tension: 0
        },
        _loop,
        _fullLoop: _loop
    }) : null;
}
function _shouldApplyFill(source) {
    return source && source.fill !== false;
}

function _resolveTarget(sources, index, propagate) {
    const source = sources[index];
    let fill = source.fill;
    const visited = [
        index
    ];
    let target;
    if (!propagate) {
        return fill;
    }
    while(fill !== false && visited.indexOf(fill) === -1){
        if (!isNumberFinite(fill)) {
            return fill;
        }
        target = sources[fill];
        if (!target) {
            return false;
        }
        if (target.visible) {
            return fill;
        }
        visited.push(fill);
        fill = target.fill;
    }
    return false;
}
 function _decodeFill(line, index, count) {
     const fill = parseFillOption(line);
    if (isObject(fill)) {
        return isNaN(fill.value) ? false : fill;
    }
    let target = parseFloat(fill);
    if (isNumberFinite(target) && Math.floor(target) === target) {
        return decodeTargetIndex(fill[0], index, target, count);
    }
    return [
        'origin',
        'start',
        'end',
        'stack',
        'shape'
    ].indexOf(fill) >= 0 && fill;
}
function decodeTargetIndex(firstCh, index, target, count) {
    if (firstCh === '-' || firstCh === '+') {
        target = index + target;
    }
    if (target === index || target < 0 || target >= count) {
        return false;
    }
    return target;
}
 function _getTargetPixel(fill, scale) {
    let pixel = null;
    if (fill === 'start') {
        pixel = scale.bottom;
    } else if (fill === 'end') {
        pixel = scale.top;
    } else if (isObject(fill)) {
        pixel = scale.getPixelForValue(fill.value);
    } else if (scale.getBasePixel) {
        pixel = scale.getBasePixel();
    }
    return pixel;
}
 function _getTargetValue(fill, scale, startValue) {
    let value;
    if (fill === 'start') {
        value = startValue;
    } else if (fill === 'end') {
        value = scale.options.reverse ? scale.min : scale.max;
    } else if (isObject(fill)) {
        value = fill.value;
    } else {
        value = scale.getBaseValue();
    }
    return value;
}
 function parseFillOption(line) {
    const options = line.options;
    const fillOption = options.fill;
    let fill = valueOrDefault(fillOption && fillOption.target, fillOption);
    if (fill === undefined) {
        fill = !!options.backgroundColor;
    }
    if (fill === false || fill === null) {
        return false;
    }
    if (fill === true) {
        return 'origin';
    }
    return fill;
}

function _buildStackLine(source) {
    const { scale , index , line  } = source;
    const points = [];
    const segments = line.segments;
    const sourcePoints = line.points;
    const linesBelow = getLinesBelow(scale, index);
    linesBelow.push(_createBoundaryLine({
        x: null,
        y: scale.bottom
    }, line));
    for(let i = 0; i < segments.length; i++){
        const segment = segments[i];
        for(let j = segment.start; j <= segment.end; j++){
            addPointsBelow(points, sourcePoints[j], linesBelow);
        }
    }
    return new LineElement({
        points,
        options: {}
    });
}
 function getLinesBelow(scale, index) {
    const below = [];
    const metas = scale.getMatchingVisibleMetas('line');
    for(let i = 0; i < metas.length; i++){
        const meta = metas[i];
        if (meta.index === index) {
            break;
        }
        if (!meta.hidden) {
            below.unshift(meta.dataset);
        }
    }
    return below;
}
 function addPointsBelow(points, sourcePoint, linesBelow) {
    const postponed = [];
    for(let j = 0; j < linesBelow.length; j++){
        const line = linesBelow[j];
        const { first , last , point  } = findPoint(line, sourcePoint, 'x');
        if (!point || first && last) {
            continue;
        }
        if (first) {
            postponed.unshift(point);
        } else {
            points.push(point);
            if (!last) {
                break;
            }
        }
    }
    points.push(...postponed);
}
 function findPoint(line, sourcePoint, property) {
    const point = line.interpolate(sourcePoint, property);
    if (!point) {
        return {};
    }
    const pointValue = point[property];
    const segments = line.segments;
    const linePoints = line.points;
    let first = false;
    let last = false;
    for(let i = 0; i < segments.length; i++){
        const segment = segments[i];
        const firstValue = linePoints[segment.start][property];
        const lastValue = linePoints[segment.end][property];
        if (_isBetween(pointValue, firstValue, lastValue)) {
            first = pointValue === firstValue;
            last = pointValue === lastValue;
            break;
        }
    }
    return {
        first,
        last,
        point
    };
}

class simpleArc {
    constructor(opts){
        this.x = opts.x;
        this.y = opts.y;
        this.radius = opts.radius;
    }
    pathSegment(ctx, bounds, opts) {
        const { x , y , radius  } = this;
        bounds = bounds || {
            start: 0,
            end: TAU
        };
        ctx.arc(x, y, radius, bounds.end, bounds.start, true);
        return !opts.bounds;
    }
    interpolate(point) {
        const { x , y , radius  } = this;
        const angle = point.angle;
        return {
            x: x + Math.cos(angle) * radius,
            y: y + Math.sin(angle) * radius,
            angle
        };
    }
}

function _getTarget(source) {
    const { chart , fill , line  } = source;
    if (isNumberFinite(fill)) {
        return getLineByIndex(chart, fill);
    }
    if (fill === 'stack') {
        return _buildStackLine(source);
    }
    if (fill === 'shape') {
        return true;
    }
    const boundary = computeBoundary(source);
    if (boundary instanceof simpleArc) {
        return boundary;
    }
    return _createBoundaryLine(boundary, line);
}
 function getLineByIndex(chart, index) {
    const meta = chart.getDatasetMeta(index);
    const visible = meta && chart.isDatasetVisible(index);
    return visible ? meta.dataset : null;
}
function computeBoundary(source) {
    const scale = source.scale || {};
    if (scale.getPointPositionForValue) {
        return computeCircularBoundary(source);
    }
    return computeLinearBoundary(source);
}
function computeLinearBoundary(source) {
    const { scale ={} , fill  } = source;
    const pixel = _getTargetPixel(fill, scale);
    if (isNumberFinite(pixel)) {
        const horizontal = scale.isHorizontal();
        return {
            x: horizontal ? pixel : null,
            y: horizontal ? null : pixel
        };
    }
    return null;
}
function computeCircularBoundary(source) {
    const { scale , fill  } = source;
    const options = scale.options;
    const length = scale.getLabels().length;
    const start = options.reverse ? scale.max : scale.min;
    const value = _getTargetValue(fill, scale, start);
    const target = [];
    if (options.grid.circular) {
        const center = scale.getPointPositionForValue(0, start);
        return new simpleArc({
            x: center.x,
            y: center.y,
            radius: scale.getDistanceFromCenterForValue(value)
        });
    }
    for(let i = 0; i < length; ++i){
        target.push(scale.getPointPositionForValue(i, value));
    }
    return target;
}

function _drawfill(ctx, source, area) {
    const target = _getTarget(source);
    const { chart , index , line , scale , axis  } = source;
    const lineOpts = line.options;
    const fillOption = lineOpts.fill;
    const color = lineOpts.backgroundColor;
    const { above =color , below =color  } = fillOption || {};
    const meta = chart.getDatasetMeta(index);
    const clip = getDatasetClipArea(chart, meta);
    if (target && line.points.length) {
        clipArea(ctx, area);
        doFill(ctx, {
            line,
            target,
            above,
            below,
            area,
            scale,
            axis,
            clip
        });
        unclipArea(ctx);
    }
}
function doFill(ctx, cfg) {
    const { line , target , above , below , area , scale , clip  } = cfg;
    const property = line._loop ? 'angle' : cfg.axis;
    ctx.save();
    let fillColor = below;
    if (below !== above) {
        if (property === 'x') {
            clipVertical(ctx, target, area.top);
            fill(ctx, {
                line,
                target,
                color: above,
                scale,
                property,
                clip
            });
            ctx.restore();
            ctx.save();
            clipVertical(ctx, target, area.bottom);
        } else if (property === 'y') {
            clipHorizontal(ctx, target, area.left);
            fill(ctx, {
                line,
                target,
                color: below,
                scale,
                property,
                clip
            });
            ctx.restore();
            ctx.save();
            clipHorizontal(ctx, target, area.right);
            fillColor = above;
        }
    }
    fill(ctx, {
        line,
        target,
        color: fillColor,
        scale,
        property,
        clip
    });
    ctx.restore();
}
function clipVertical(ctx, target, clipY) {
    const { segments , points  } = target;
    let first = true;
    let lineLoop = false;
    ctx.beginPath();
    for (const segment of segments){
        const { start , end  } = segment;
        const firstPoint = points[start];
        const lastPoint = points[_findSegmentEnd(start, end, points)];
        if (first) {
            ctx.moveTo(firstPoint.x, firstPoint.y);
            first = false;
        } else {
            ctx.lineTo(firstPoint.x, clipY);
            ctx.lineTo(firstPoint.x, firstPoint.y);
        }
        lineLoop = !!target.pathSegment(ctx, segment, {
            move: lineLoop
        });
        if (lineLoop) {
            ctx.closePath();
        } else {
            ctx.lineTo(lastPoint.x, clipY);
        }
    }
    ctx.lineTo(target.first().x, clipY);
    ctx.closePath();
    ctx.clip();
}
function clipHorizontal(ctx, target, clipX) {
    const { segments , points  } = target;
    let first = true;
    let lineLoop = false;
    ctx.beginPath();
    for (const segment of segments){
        const { start , end  } = segment;
        const firstPoint = points[start];
        const lastPoint = points[_findSegmentEnd(start, end, points)];
        if (first) {
            ctx.moveTo(firstPoint.x, firstPoint.y);
            first = false;
        } else {
            ctx.lineTo(clipX, firstPoint.y);
            ctx.lineTo(firstPoint.x, firstPoint.y);
        }
        lineLoop = !!target.pathSegment(ctx, segment, {
            move: lineLoop
        });
        if (lineLoop) {
            ctx.closePath();
        } else {
            ctx.lineTo(clipX, lastPoint.y);
        }
    }
    ctx.lineTo(clipX, target.first().y);
    ctx.closePath();
    ctx.clip();
}
function fill(ctx, cfg) {
    const { line , target , property , color , scale , clip  } = cfg;
    const segments = _segments(line, target, property);
    for (const { source: src , target: tgt , start , end  } of segments){
        const { style: { backgroundColor =color  } = {}  } = src;
        const notShape = target !== true;
        ctx.save();
        ctx.fillStyle = backgroundColor;
        clipBounds(ctx, scale, clip, notShape && _getBounds(property, start, end));
        ctx.beginPath();
        const lineLoop = !!line.pathSegment(ctx, src);
        let loop;
        if (notShape) {
            if (lineLoop) {
                ctx.closePath();
            } else {
                interpolatedLineTo(ctx, target, end, property);
            }
            const targetLoop = !!target.pathSegment(ctx, tgt, {
                move: lineLoop,
                reverse: true
            });
            loop = lineLoop && targetLoop;
            if (!loop) {
                interpolatedLineTo(ctx, target, start, property);
            }
        }
        ctx.closePath();
        ctx.fill(loop ? 'evenodd' : 'nonzero');
        ctx.restore();
    }
}
function clipBounds(ctx, scale, clip, bounds) {
    const chartArea = scale.chart.chartArea;
    const { property , start , end  } = bounds || {};
    if (property === 'x' || property === 'y') {
        let left, top, right, bottom;
        if (property === 'x') {
            left = start;
            top = chartArea.top;
            right = end;
            bottom = chartArea.bottom;
        } else {
            left = chartArea.left;
            top = start;
            right = chartArea.right;
            bottom = end;
        }
        ctx.beginPath();
        if (clip) {
            left = Math.max(left, clip.left);
            right = Math.min(right, clip.right);
            top = Math.max(top, clip.top);
            bottom = Math.min(bottom, clip.bottom);
        }
        ctx.rect(left, top, right - left, bottom - top);
        ctx.clip();
    }
}
function interpolatedLineTo(ctx, target, point, property) {
    const interpolatedPoint = target.interpolate(point, property);
    if (interpolatedPoint) {
        ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);
    }
}

var index = {
    id: 'filler',
    afterDatasetsUpdate (chart, _args, options) {
        const count = (chart.data.datasets || []).length;
        const sources = [];
        let meta, i, line, source;
        for(i = 0; i < count; ++i){
            meta = chart.getDatasetMeta(i);
            line = meta.dataset;
            source = null;
            if (line && line.options && line instanceof LineElement) {
                source = {
                    visible: chart.isDatasetVisible(i),
                    index: i,
                    fill: _decodeFill(line, i, count),
                    chart,
                    axis: meta.controller.options.indexAxis,
                    scale: meta.vScale,
                    line
                };
            }
            meta.$filler = source;
            sources.push(source);
        }
        for(i = 0; i < count; ++i){
            source = sources[i];
            if (!source || source.fill === false) {
                continue;
            }
            source.fill = _resolveTarget(sources, i, options.propagate);
        }
    },
    beforeDraw (chart, _args, options) {
        const draw = options.drawTime === 'beforeDraw';
        const metasets = chart.getSortedVisibleDatasetMetas();
        const area = chart.chartArea;
        for(let i = metasets.length - 1; i >= 0; --i){
            const source = metasets[i].$filler;
            if (!source) {
                continue;
            }
            source.line.updateControlPoints(area, source.axis);
            if (draw && source.fill) {
                _drawfill(chart.ctx, source, area);
            }
        }
    },
    beforeDatasetsDraw (chart, _args, options) {
        if (options.drawTime !== 'beforeDatasetsDraw') {
            return;
        }
        const metasets = chart.getSortedVisibleDatasetMetas();
        for(let i = metasets.length - 1; i >= 0; --i){
            const source = metasets[i].$filler;
            if (_shouldApplyFill(source)) {
                _drawfill(chart.ctx, source, chart.chartArea);
            }
        }
    },
    beforeDatasetDraw (chart, args, options) {
        const source = args.meta.$filler;
        if (!_shouldApplyFill(source) || options.drawTime !== 'beforeDatasetDraw') {
            return;
        }
        _drawfill(chart.ctx, source, chart.chartArea);
    },
    defaults: {
        propagate: true,
        drawTime: 'beforeDatasetDraw'
    }
};

const getBoxSize = (labelOpts, fontSize)=>{
    let { boxHeight =fontSize , boxWidth =fontSize  } = labelOpts;
    if (labelOpts.usePointStyle) {
        boxHeight = Math.min(boxHeight, fontSize);
        boxWidth = labelOpts.pointStyleWidth || Math.min(boxWidth, fontSize);
    }
    return {
        boxWidth,
        boxHeight,
        itemHeight: Math.max(fontSize, boxHeight)
    };
};
const itemsEqual = (a, b)=>a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;
class Legend extends Element$1 {
 constructor(config){
        super();
        this._added = false;
        this.legendHitBoxes = [];
 this._hoveredItem = null;
        this.doughnutMode = false;
        this.chart = config.chart;
        this.options = config.options;
        this.ctx = config.ctx;
        this.legendItems = undefined;
        this.columnSizes = undefined;
        this.lineWidths = undefined;
        this.maxHeight = undefined;
        this.maxWidth = undefined;
        this.top = undefined;
        this.bottom = undefined;
        this.left = undefined;
        this.right = undefined;
        this.height = undefined;
        this.width = undefined;
        this._margins = undefined;
        this.position = undefined;
        this.weight = undefined;
        this.fullSize = undefined;
    }
    update(maxWidth, maxHeight, margins) {
        this.maxWidth = maxWidth;
        this.maxHeight = maxHeight;
        this._margins = margins;
        this.setDimensions();
        this.buildLabels();
        this.fit();
    }
    setDimensions() {
        if (this.isHorizontal()) {
            this.width = this.maxWidth;
            this.left = this._margins.left;
            this.right = this.width;
        } else {
            this.height = this.maxHeight;
            this.top = this._margins.top;
            this.bottom = this.height;
        }
    }
    buildLabels() {
        const labelOpts = this.options.labels || {};
        let legendItems = callback(labelOpts.generateLabels, [
            this.chart
        ], this) || [];
        if (labelOpts.filter) {
            legendItems = legendItems.filter((item)=>labelOpts.filter(item, this.chart.data));
        }
        if (labelOpts.sort) {
            legendItems = legendItems.sort((a, b)=>labelOpts.sort(a, b, this.chart.data));
        }
        if (this.options.reverse) {
            legendItems.reverse();
        }
        this.legendItems = legendItems;
    }
    fit() {
        const { options , ctx  } = this;
        if (!options.display) {
            this.width = this.height = 0;
            return;
        }
        const labelOpts = options.labels;
        const labelFont = toFont(labelOpts.font);
        const fontSize = labelFont.size;
        const titleHeight = this._computeTitleHeight();
        const { boxWidth , itemHeight  } = getBoxSize(labelOpts, fontSize);
        let width, height;
        ctx.font = labelFont.string;
        if (this.isHorizontal()) {
            width = this.maxWidth;
            height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;
        } else {
            height = this.maxHeight;
            width = this._fitCols(titleHeight, labelFont, boxWidth, itemHeight) + 10;
        }
        this.width = Math.min(width, options.maxWidth || this.maxWidth);
        this.height = Math.min(height, options.maxHeight || this.maxHeight);
    }
 _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {
        const { ctx , maxWidth , options: { labels: { padding  }  }  } = this;
        const hitboxes = this.legendHitBoxes = [];
        const lineWidths = this.lineWidths = [
            0
        ];
        const lineHeight = itemHeight + padding;
        let totalHeight = titleHeight;
        ctx.textAlign = 'left';
        ctx.textBaseline = 'middle';
        let row = -1;
        let top = -lineHeight;
        this.legendItems.forEach((legendItem, i)=>{
            const itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width;
            if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {
                totalHeight += lineHeight;
                lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
                top += lineHeight;
                row++;
            }
            hitboxes[i] = {
                left: 0,
                top,
                row,
                width: itemWidth,
                height: itemHeight
            };
            lineWidths[lineWidths.length - 1] += itemWidth + padding;
        });
        return totalHeight;
    }
    _fitCols(titleHeight, labelFont, boxWidth, _itemHeight) {
        const { ctx , maxHeight , options: { labels: { padding  }  }  } = this;
        const hitboxes = this.legendHitBoxes = [];
        const columnSizes = this.columnSizes = [];
        const heightLimit = maxHeight - titleHeight;
        let totalWidth = padding;
        let currentColWidth = 0;
        let currentColHeight = 0;
        let left = 0;
        let col = 0;
        this.legendItems.forEach((legendItem, i)=>{
            const { itemWidth , itemHeight  } = calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight);
            if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {
                totalWidth += currentColWidth + padding;
                columnSizes.push({
                    width: currentColWidth,
                    height: currentColHeight
                });
                left += currentColWidth + padding;
                col++;
                currentColWidth = currentColHeight = 0;
            }
            hitboxes[i] = {
                left,
                top: currentColHeight,
                col,
                width: itemWidth,
                height: itemHeight
            };
            currentColWidth = Math.max(currentColWidth, itemWidth);
            currentColHeight += itemHeight + padding;
        });
        totalWidth += currentColWidth;
        columnSizes.push({
            width: currentColWidth,
            height: currentColHeight
        });
        return totalWidth;
    }
    adjustHitBoxes() {
        if (!this.options.display) {
            return;
        }
        const titleHeight = this._computeTitleHeight();
        const { legendHitBoxes: hitboxes , options: { align , labels: { padding  } , rtl  }  } = this;
        const rtlHelper = getRtlAdapter(rtl, this.left, this.width);
        if (this.isHorizontal()) {
            let row = 0;
            let left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
            for (const hitbox of hitboxes){
                if (row !== hitbox.row) {
                    row = hitbox.row;
                    left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
                }
                hitbox.top += this.top + titleHeight + padding;
                hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width);
                left += hitbox.width + padding;
            }
        } else {
            let col = 0;
            let top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
            for (const hitbox of hitboxes){
                if (hitbox.col !== col) {
                    col = hitbox.col;
                    top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
                }
                hitbox.top = top;
                hitbox.left += this.left + padding;
                hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width);
                top += hitbox.height + padding;
            }
        }
    }
    isHorizontal() {
        return this.options.position === 'top' || this.options.position === 'bottom';
    }
    draw() {
        if (this.options.display) {
            const ctx = this.ctx;
            clipArea(ctx, this);
            this._draw();
            unclipArea(ctx);
        }
    }
 _draw() {
        const { options: opts , columnSizes , lineWidths , ctx  } = this;
        const { align , labels: labelOpts  } = opts;
        const defaultColor = defaults.color;
        const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);
        const labelFont = toFont(labelOpts.font);
        const { padding  } = labelOpts;
        const fontSize = labelFont.size;
        const halfFontSize = fontSize / 2;
        let cursor;
        this.drawTitle();
        ctx.textAlign = rtlHelper.textAlign('left');
        ctx.textBaseline = 'middle';
        ctx.lineWidth = 0.5;
        ctx.font = labelFont.string;
        const { boxWidth , boxHeight , itemHeight  } = getBoxSize(labelOpts, fontSize);
        const drawLegendBox = function(x, y, legendItem) {
            if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {
                return;
            }
            ctx.save();
            const lineWidth = valueOrDefault(legendItem.lineWidth, 1);
            ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);
            ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt');
            ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);
            ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter');
            ctx.lineWidth = lineWidth;
            ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);
            ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));
            if (labelOpts.usePointStyle) {
                const drawOptions = {
                    radius: boxHeight * Math.SQRT2 / 2,
                    pointStyle: legendItem.pointStyle,
                    rotation: legendItem.rotation,
                    borderWidth: lineWidth
                };
                const centerX = rtlHelper.xPlus(x, boxWidth / 2);
                const centerY = y + halfFontSize;
                drawPointLegend(ctx, drawOptions, centerX, centerY, labelOpts.pointStyleWidth && boxWidth);
            } else {
                const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);
                const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);
                const borderRadius = toTRBLCorners(legendItem.borderRadius);
                ctx.beginPath();
                if (Object.values(borderRadius).some((v)=>v !== 0)) {
                    addRoundedRectPath(ctx, {
                        x: xBoxLeft,
                        y: yBoxTop,
                        w: boxWidth,
                        h: boxHeight,
                        radius: borderRadius
                    });
                } else {
                    ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);
                }
                ctx.fill();
                if (lineWidth !== 0) {
                    ctx.stroke();
                }
            }
            ctx.restore();
        };
        const fillText = function(x, y, legendItem) {
            renderText(ctx, legendItem.text, x, y + itemHeight / 2, labelFont, {
                strikethrough: legendItem.hidden,
                textAlign: rtlHelper.textAlign(legendItem.textAlign)
            });
        };
        const isHorizontal = this.isHorizontal();
        const titleHeight = this._computeTitleHeight();
        if (isHorizontal) {
            cursor = {
                x: _alignStartEnd(align, this.left + padding, this.right - lineWidths[0]),
                y: this.top + padding + titleHeight,
                line: 0
            };
        } else {
            cursor = {
                x: this.left + padding,
                y: _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height),
                line: 0
            };
        }
        overrideTextDirection(this.ctx, opts.textDirection);
        const lineHeight = itemHeight + padding;
        this.legendItems.forEach((legendItem, i)=>{
            ctx.strokeStyle = legendItem.fontColor;
            ctx.fillStyle = legendItem.fontColor;
            const textWidth = ctx.measureText(legendItem.text).width;
            const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));
            const width = boxWidth + halfFontSize + textWidth;
            let x = cursor.x;
            let y = cursor.y;
            rtlHelper.setWidth(this.width);
            if (isHorizontal) {
                if (i > 0 && x + width + padding > this.right) {
                    y = cursor.y += lineHeight;
                    cursor.line++;
                    x = cursor.x = _alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]);
                }
            } else if (i > 0 && y + lineHeight > this.bottom) {
                x = cursor.x = x + columnSizes[cursor.line].width + padding;
                cursor.line++;
                y = cursor.y = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height);
            }
            const realX = rtlHelper.x(x);
            drawLegendBox(realX, y, legendItem);
            x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl);
            fillText(rtlHelper.x(x), y, legendItem);
            if (isHorizontal) {
                cursor.x += width + padding;
            } else if (typeof legendItem.text !== 'string') {
                const fontLineHeight = labelFont.lineHeight;
                cursor.y += calculateLegendItemHeight(legendItem, fontLineHeight) + padding;
            } else {
                cursor.y += lineHeight;
            }
        });
        restoreTextDirection(this.ctx, opts.textDirection);
    }
 drawTitle() {
        const opts = this.options;
        const titleOpts = opts.title;
        const titleFont = toFont(titleOpts.font);
        const titlePadding = toPadding(titleOpts.padding);
        if (!titleOpts.display) {
            return;
        }
        const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);
        const ctx = this.ctx;
        const position = titleOpts.position;
        const halfFontSize = titleFont.size / 2;
        const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;
        let y;
        let left = this.left;
        let maxWidth = this.width;
        if (this.isHorizontal()) {
            maxWidth = Math.max(...this.lineWidths);
            y = this.top + topPaddingPlusHalfFontSize;
            left = _alignStartEnd(opts.align, left, this.right - maxWidth);
        } else {
            const maxHeight = this.columnSizes.reduce((acc, size)=>Math.max(acc, size.height), 0);
            y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight());
        }
        const x = _alignStartEnd(position, left, left + maxWidth);
        ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));
        ctx.textBaseline = 'middle';
        ctx.strokeStyle = titleOpts.color;
        ctx.fillStyle = titleOpts.color;
        ctx.font = titleFont.string;
        renderText(ctx, titleOpts.text, x, y, titleFont);
    }
 _computeTitleHeight() {
        const titleOpts = this.options.title;
        const titleFont = toFont(titleOpts.font);
        const titlePadding = toPadding(titleOpts.padding);
        return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
    }
 _getLegendItemAt(x, y) {
        let i, hitBox, lh;
        if (_isBetween(x, this.left, this.right) && _isBetween(y, this.top, this.bottom)) {
            lh = this.legendHitBoxes;
            for(i = 0; i < lh.length; ++i){
                hitBox = lh[i];
                if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width) && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) {
                    return this.legendItems[i];
                }
            }
        }
        return null;
    }
 handleEvent(e) {
        const opts = this.options;
        if (!isListened(e.type, opts)) {
            return;
        }
        const hoveredItem = this._getLegendItemAt(e.x, e.y);
        if (e.type === 'mousemove' || e.type === 'mouseout') {
            const previous = this._hoveredItem;
            const sameItem = itemsEqual(previous, hoveredItem);
            if (previous && !sameItem) {
                callback(opts.onLeave, [
                    e,
                    previous,
                    this
                ], this);
            }
            this._hoveredItem = hoveredItem;
            if (hoveredItem && !sameItem) {
                callback(opts.onHover, [
                    e,
                    hoveredItem,
                    this
                ], this);
            }
        } else if (hoveredItem) {
            callback(opts.onClick, [
                e,
                hoveredItem,
                this
            ], this);
        }
    }
}
function calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight) {
    const itemWidth = calculateItemWidth(legendItem, boxWidth, labelFont, ctx);
    const itemHeight = calculateItemHeight(_itemHeight, legendItem, labelFont.lineHeight);
    return {
        itemWidth,
        itemHeight
    };
}
function calculateItemWidth(legendItem, boxWidth, labelFont, ctx) {
    let legendItemText = legendItem.text;
    if (legendItemText && typeof legendItemText !== 'string') {
        legendItemText = legendItemText.reduce((a, b)=>a.length > b.length ? a : b);
    }
    return boxWidth + labelFont.size / 2 + ctx.measureText(legendItemText).width;
}
function calculateItemHeight(_itemHeight, legendItem, fontLineHeight) {
    let itemHeight = _itemHeight;
    if (typeof legendItem.text !== 'string') {
        itemHeight = calculateLegendItemHeight(legendItem, fontLineHeight);
    }
    return itemHeight;
}
function calculateLegendItemHeight(legendItem, fontLineHeight) {
    const labelHeight = legendItem.text ? legendItem.text.length : 0;
    return fontLineHeight * labelHeight;
}
function isListened(type, opts) {
    if ((type === 'mousemove' || type === 'mouseout') && (opts.onHover || opts.onLeave)) {
        return true;
    }
    if (opts.onClick && (type === 'click' || type === 'mouseup')) {
        return true;
    }
    return false;
}
var plugin_legend = {
    id: 'legend',
 _element: Legend,
    start (chart, _args, options) {
        const legend = chart.legend = new Legend({
            ctx: chart.ctx,
            options,
            chart
        });
        layouts.configure(chart, legend, options);
        layouts.addBox(chart, legend);
    },
    stop (chart) {
        layouts.removeBox(chart, chart.legend);
        delete chart.legend;
    },
    beforeUpdate (chart, _args, options) {
        const legend = chart.legend;
        layouts.configure(chart, legend, options);
        legend.options = options;
    },
    afterUpdate (chart) {
        const legend = chart.legend;
        legend.buildLabels();
        legend.adjustHitBoxes();
    },
    afterEvent (chart, args) {
        if (!args.replay) {
            chart.legend.handleEvent(args.event);
        }
    },
    defaults: {
        display: true,
        position: 'top',
        align: 'center',
        fullSize: true,
        reverse: false,
        weight: 1000,
        onClick (e, legendItem, legend) {
            const index = legendItem.datasetIndex;
            const ci = legend.chart;
            if (ci.isDatasetVisible(index)) {
                ci.hide(index);
                legendItem.hidden = true;
            } else {
                ci.show(index);
                legendItem.hidden = false;
            }
        },
        onHover: null,
        onLeave: null,
        labels: {
            color: (ctx)=>ctx.chart.options.color,
            boxWidth: 40,
            padding: 10,
            generateLabels (chart) {
                const datasets = chart.data.datasets;
                const { labels: { usePointStyle , pointStyle , textAlign , color , useBorderRadius , borderRadius  }  } = chart.legend.options;
                return chart._getSortedDatasetMetas().map((meta)=>{
                    const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
                    const borderWidth = toPadding(style.borderWidth);
                    return {
                        text: datasets[meta.index].label,
                        fillStyle: style.backgroundColor,
                        fontColor: color,
                        hidden: !meta.visible,
                        lineCap: style.borderCapStyle,
                        lineDash: style.borderDash,
                        lineDashOffset: style.borderDashOffset,
                        lineJoin: style.borderJoinStyle,
                        lineWidth: (borderWidth.width + borderWidth.height) / 4,
                        strokeStyle: style.borderColor,
                        pointStyle: pointStyle || style.pointStyle,
                        rotation: style.rotation,
                        textAlign: textAlign || style.textAlign,
                        borderRadius: useBorderRadius && (borderRadius || style.borderRadius),
                        datasetIndex: meta.index
                    };
                }, this);
            }
        },
        title: {
            color: (ctx)=>ctx.chart.options.color,
            display: false,
            position: 'center',
            text: ''
        }
    },
    descriptors: {
        _scriptable: (name)=>!name.startsWith('on'),
        labels: {
            _scriptable: (name)=>![
                    'generateLabels',
                    'filter',
                    'sort'
                ].includes(name)
        }
    }
};

class Title extends Element$1 {
 constructor(config){
        super();
        this.chart = config.chart;
        this.options = config.options;
        this.ctx = config.ctx;
        this._padding = undefined;
        this.top = undefined;
        this.bottom = undefined;
        this.left = undefined;
        this.right = undefined;
        this.width = undefined;
        this.height = undefined;
        this.position = undefined;
        this.weight = undefined;
        this.fullSize = undefined;
    }
    update(maxWidth, maxHeight) {
        const opts = this.options;
        this.left = 0;
        this.top = 0;
        if (!opts.display) {
            this.width = this.height = this.right = this.bottom = 0;
            return;
        }
        this.width = this.right = maxWidth;
        this.height = this.bottom = maxHeight;
        const lineCount = isArray(opts.text) ? opts.text.length : 1;
        this._padding = toPadding(opts.padding);
        const textSize = lineCount * toFont(opts.font).lineHeight + this._padding.height;
        if (this.isHorizontal()) {
            this.height = textSize;
        } else {
            this.width = textSize;
        }
    }
    isHorizontal() {
        const pos = this.options.position;
        return pos === 'top' || pos === 'bottom';
    }
    _drawArgs(offset) {
        const { top , left , bottom , right , options  } = this;
        const align = options.align;
        let rotation = 0;
        let maxWidth, titleX, titleY;
        if (this.isHorizontal()) {
            titleX = _alignStartEnd(align, left, right);
            titleY = top + offset;
            maxWidth = right - left;
        } else {
            if (options.position === 'left') {
                titleX = left + offset;
                titleY = _alignStartEnd(align, bottom, top);
                rotation = PI * -0.5;
            } else {
                titleX = right - offset;
                titleY = _alignStartEnd(align, top, bottom);
                rotation = PI * 0.5;
            }
            maxWidth = bottom - top;
        }
        return {
            titleX,
            titleY,
            maxWidth,
            rotation
        };
    }
    draw() {
        const ctx = this.ctx;
        const opts = this.options;
        if (!opts.display) {
            return;
        }
        const fontOpts = toFont(opts.font);
        const lineHeight = fontOpts.lineHeight;
        const offset = lineHeight / 2 + this._padding.top;
        const { titleX , titleY , maxWidth , rotation  } = this._drawArgs(offset);
        renderText(ctx, opts.text, 0, 0, fontOpts, {
            color: opts.color,
            maxWidth,
            rotation,
            textAlign: _toLeftRightCenter(opts.align),
            textBaseline: 'middle',
            translation: [
                titleX,
                titleY
            ]
        });
    }
}
function createTitle(chart, titleOpts) {
    const title = new Title({
        ctx: chart.ctx,
        options: titleOpts,
        chart
    });
    layouts.configure(chart, title, titleOpts);
    layouts.addBox(chart, title);
    chart.titleBlock = title;
}
var plugin_title = {
    id: 'title',
 _element: Title,
    start (chart, _args, options) {
        createTitle(chart, options);
    },
    stop (chart) {
        const titleBlock = chart.titleBlock;
        layouts.removeBox(chart, titleBlock);
        delete chart.titleBlock;
    },
    beforeUpdate (chart, _args, options) {
        const title = chart.titleBlock;
        layouts.configure(chart, title, options);
        title.options = options;
    },
    defaults: {
        align: 'center',
        display: false,
        font: {
            weight: 'bold'
        },
        fullSize: true,
        padding: 10,
        position: 'top',
        text: '',
        weight: 2000
    },
    defaultRoutes: {
        color: 'color'
    },
    descriptors: {
        _scriptable: true,
        _indexable: false
    }
};

const map = new WeakMap();
var plugin_subtitle = {
    id: 'subtitle',
    start (chart, _args, options) {
        const title = new Title({
            ctx: chart.ctx,
            options,
            chart
        });
        layouts.configure(chart, title, options);
        layouts.addBox(chart, title);
        map.set(chart, title);
    },
    stop (chart) {
        layouts.removeBox(chart, map.get(chart));
        map.delete(chart);
    },
    beforeUpdate (chart, _args, options) {
        const title = map.get(chart);
        layouts.configure(chart, title, options);
        title.options = options;
    },
    defaults: {
        align: 'center',
        display: false,
        font: {
            weight: 'normal'
        },
        fullSize: true,
        padding: 0,
        position: 'top',
        text: '',
        weight: 1500
    },
    defaultRoutes: {
        color: 'color'
    },
    descriptors: {
        _scriptable: true,
        _indexable: false
    }
};

const positioners = {
 average (items) {
        if (!items.length) {
            return false;
        }
        let i, len;
        let xSet = new Set();
        let y = 0;
        let count = 0;
        for(i = 0, len = items.length; i < len; ++i){
            const el = items[i].element;
            if (el && el.hasValue()) {
                const pos = el.tooltipPosition();
                xSet.add(pos.x);
                y += pos.y;
                ++count;
            }
        }
        if (count === 0 || xSet.size === 0) {
            return false;
        }
        const xAverage = [
            ...xSet
        ].reduce((a, b)=>a + b) / xSet.size;
        return {
            x: xAverage,
            y: y / count
        };
    },
 nearest (items, eventPosition) {
        if (!items.length) {
            return false;
        }
        let x = eventPosition.x;
        let y = eventPosition.y;
        let minDistance = Number.POSITIVE_INFINITY;
        let i, len, nearestElement;
        for(i = 0, len = items.length; i < len; ++i){
            const el = items[i].element;
            if (el && el.hasValue()) {
                const center = el.getCenterPoint();
                const d = distanceBetweenPoints(eventPosition, center);
                if (d < minDistance) {
                    minDistance = d;
                    nearestElement = el;
                }
            }
        }
        if (nearestElement) {
            const tp = nearestElement.tooltipPosition();
            x = tp.x;
            y = tp.y;
        }
        return {
            x,
            y
        };
    }
};
function pushOrConcat(base, toPush) {
    if (toPush) {
        if (isArray(toPush)) {
            Array.prototype.push.apply(base, toPush);
        } else {
            base.push(toPush);
        }
    }
    return base;
}
 function splitNewlines(str) {
    if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
        return str.split('\n');
    }
    return str;
}
 function createTooltipItem(chart, item) {
    const { element , datasetIndex , index  } = item;
    const controller = chart.getDatasetMeta(datasetIndex).controller;
    const { label , value  } = controller.getLabelAndValue(index);
    return {
        chart,
        label,
        parsed: controller.getParsed(index),
        raw: chart.data.datasets[datasetIndex].data[index],
        formattedValue: value,
        dataset: controller.getDataset(),
        dataIndex: index,
        datasetIndex,
        element
    };
}
 function getTooltipSize(tooltip, options) {
    const ctx = tooltip.chart.ctx;
    const { body , footer , title  } = tooltip;
    const { boxWidth , boxHeight  } = options;
    const bodyFont = toFont(options.bodyFont);
    const titleFont = toFont(options.titleFont);
    const footerFont = toFont(options.footerFont);
    const titleLineCount = title.length;
    const footerLineCount = footer.length;
    const bodyLineItemCount = body.length;
    const padding = toPadding(options.padding);
    let height = padding.height;
    let width = 0;
    let combinedBodyLength = body.reduce((count, bodyItem)=>count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);
    combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;
    if (titleLineCount) {
        height += titleLineCount * titleFont.lineHeight + (titleLineCount - 1) * options.titleSpacing + options.titleMarginBottom;
    }
    if (combinedBodyLength) {
        const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;
        height += bodyLineItemCount * bodyLineHeight + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight + (combinedBodyLength - 1) * options.bodySpacing;
    }
    if (footerLineCount) {
        height += options.footerMarginTop + footerLineCount * footerFont.lineHeight + (footerLineCount - 1) * options.footerSpacing;
    }
    let widthPadding = 0;
    const maxLineWidth = function(line) {
        width = Math.max(width, ctx.measureText(line).width + widthPadding);
    };
    ctx.save();
    ctx.font = titleFont.string;
    each(tooltip.title, maxLineWidth);
    ctx.font = bodyFont.string;
    each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);
    widthPadding = options.displayColors ? boxWidth + 2 + options.boxPadding : 0;
    each(body, (bodyItem)=>{
        each(bodyItem.before, maxLineWidth);
        each(bodyItem.lines, maxLineWidth);
        each(bodyItem.after, maxLineWidth);
    });
    widthPadding = 0;
    ctx.font = footerFont.string;
    each(tooltip.footer, maxLineWidth);
    ctx.restore();
    width += padding.width;
    return {
        width,
        height
    };
}
function determineYAlign(chart, size) {
    const { y , height  } = size;
    if (y < height / 2) {
        return 'top';
    } else if (y > chart.height - height / 2) {
        return 'bottom';
    }
    return 'center';
}
function doesNotFitWithAlign(xAlign, chart, options, size) {
    const { x , width  } = size;
    const caret = options.caretSize + options.caretPadding;
    if (xAlign === 'left' && x + width + caret > chart.width) {
        return true;
    }
    if (xAlign === 'right' && x - width - caret < 0) {
        return true;
    }
}
function determineXAlign(chart, options, size, yAlign) {
    const { x , width  } = size;
    const { width: chartWidth , chartArea: { left , right  }  } = chart;
    let xAlign = 'center';
    if (yAlign === 'center') {
        xAlign = x <= (left + right) / 2 ? 'left' : 'right';
    } else if (x <= width / 2) {
        xAlign = 'left';
    } else if (x >= chartWidth - width / 2) {
        xAlign = 'right';
    }
    if (doesNotFitWithAlign(xAlign, chart, options, size)) {
        xAlign = 'center';
    }
    return xAlign;
}
 function determineAlignment(chart, options, size) {
    const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size);
    return {
        xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign),
        yAlign
    };
}
function alignX(size, xAlign) {
    let { x , width  } = size;
    if (xAlign === 'right') {
        x -= width;
    } else if (xAlign === 'center') {
        x -= width / 2;
    }
    return x;
}
function alignY(size, yAlign, paddingAndSize) {
    let { y , height  } = size;
    if (yAlign === 'top') {
        y += paddingAndSize;
    } else if (yAlign === 'bottom') {
        y -= height + paddingAndSize;
    } else {
        y -= height / 2;
    }
    return y;
}
 function getBackgroundPoint(options, size, alignment, chart) {
    const { caretSize , caretPadding , cornerRadius  } = options;
    const { xAlign , yAlign  } = alignment;
    const paddingAndSize = caretSize + caretPadding;
    const { topLeft , topRight , bottomLeft , bottomRight  } = toTRBLCorners(cornerRadius);
    let x = alignX(size, xAlign);
    const y = alignY(size, yAlign, paddingAndSize);
    if (yAlign === 'center') {
        if (xAlign === 'left') {
            x += paddingAndSize;
        } else if (xAlign === 'right') {
            x -= paddingAndSize;
        }
    } else if (xAlign === 'left') {
        x -= Math.max(topLeft, bottomLeft) + caretSize;
    } else if (xAlign === 'right') {
        x += Math.max(topRight, bottomRight) + caretSize;
    }
    return {
        x: _limitValue(x, 0, chart.width - size.width),
        y: _limitValue(y, 0, chart.height - size.height)
    };
}
function getAlignedX(tooltip, align, options) {
    const padding = toPadding(options.padding);
    return align === 'center' ? tooltip.x + tooltip.width / 2 : align === 'right' ? tooltip.x + tooltip.width - padding.right : tooltip.x + padding.left;
}
 function getBeforeAfterBodyLines(callback) {
    return pushOrConcat([], splitNewlines(callback));
}
function createTooltipContext(parent, tooltip, tooltipItems) {
    return createContext(parent, {
        tooltip,
        tooltipItems,
        type: 'tooltip'
    });
}
function overrideCallbacks(callbacks, context) {
    const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;
    return override ? callbacks.override(override) : callbacks;
}
const defaultCallbacks = {
    beforeTitle: noop,
    title (tooltipItems) {
        if (tooltipItems.length > 0) {
            const item = tooltipItems[0];
            const labels = item.chart.data.labels;
            const labelCount = labels ? labels.length : 0;
            if (this && this.options && this.options.mode === 'dataset') {
                return item.dataset.label || '';
            } else if (item.label) {
                return item.label;
            } else if (labelCount > 0 && item.dataIndex < labelCount) {
                return labels[item.dataIndex];
            }
        }
        return '';
    },
    afterTitle: noop,
    beforeBody: noop,
    beforeLabel: noop,
    label (tooltipItem) {
        if (this && this.options && this.options.mode === 'dataset') {
            return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;
        }
        let label = tooltipItem.dataset.label || '';
        if (label) {
            label += ': ';
        }
        const value = tooltipItem.formattedValue;
        if (!isNullOrUndef(value)) {
            label += value;
        }
        return label;
    },
    labelColor (tooltipItem) {
        const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
        const options = meta.controller.getStyle(tooltipItem.dataIndex);
        return {
            borderColor: options.borderColor,
            backgroundColor: options.backgroundColor,
            borderWidth: options.borderWidth,
            borderDash: options.borderDash,
            borderDashOffset: options.borderDashOffset,
            borderRadius: 0
        };
    },
    labelTextColor () {
        return this.options.bodyColor;
    },
    labelPointStyle (tooltipItem) {
        const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
        const options = meta.controller.getStyle(tooltipItem.dataIndex);
        return {
            pointStyle: options.pointStyle,
            rotation: options.rotation
        };
    },
    afterLabel: noop,
    afterBody: noop,
    beforeFooter: noop,
    footer: noop,
    afterFooter: noop
};
 function invokeCallbackWithFallback(callbacks, name, ctx, arg) {
    const result = callbacks[name].call(ctx, arg);
    if (typeof result === 'undefined') {
        return defaultCallbacks[name].call(ctx, arg);
    }
    return result;
}
class Tooltip extends Element$1 {
 static positioners = positioners;
    constructor(config){
        super();
        this.opacity = 0;
        this._active = [];
        this._eventPosition = undefined;
        this._size = undefined;
        this._cachedAnimations = undefined;
        this._tooltipItems = [];
        this.$animations = undefined;
        this.$context = undefined;
        this.chart = config.chart;
        this.options = config.options;
        this.dataPoints = undefined;
        this.title = undefined;
        this.beforeBody = undefined;
        this.body = undefined;
        this.afterBody = undefined;
        this.footer = undefined;
        this.xAlign = undefined;
        this.yAlign = undefined;
        this.x = undefined;
        this.y = undefined;
        this.height = undefined;
        this.width = undefined;
        this.caretX = undefined;
        this.caretY = undefined;
        this.labelColors = undefined;
        this.labelPointStyles = undefined;
        this.labelTextColors = undefined;
    }
    initialize(options) {
        this.options = options;
        this._cachedAnimations = undefined;
        this.$context = undefined;
    }
 _resolveAnimations() {
        const cached = this._cachedAnimations;
        if (cached) {
            return cached;
        }
        const chart = this.chart;
        const options = this.options.setContext(this.getContext());
        const opts = options.enabled && chart.options.animation && options.animations;
        const animations = new Animations(this.chart, opts);
        if (opts._cacheable) {
            this._cachedAnimations = Object.freeze(animations);
        }
        return animations;
    }
 getContext() {
        return this.$context || (this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems));
    }
    getTitle(context, options) {
        const { callbacks  } = options;
        const beforeTitle = invokeCallbackWithFallback(callbacks, 'beforeTitle', this, context);
        const title = invokeCallbackWithFallback(callbacks, 'title', this, context);
        const afterTitle = invokeCallbackWithFallback(callbacks, 'afterTitle', this, context);
        let lines = [];
        lines = pushOrConcat(lines, splitNewlines(beforeTitle));
        lines = pushOrConcat(lines, splitNewlines(title));
        lines = pushOrConcat(lines, splitNewlines(afterTitle));
        return lines;
    }
    getBeforeBody(tooltipItems, options) {
        return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'beforeBody', this, tooltipItems));
    }
    getBody(tooltipItems, options) {
        const { callbacks  } = options;
        const bodyItems = [];
        each(tooltipItems, (context)=>{
            const bodyItem = {
                before: [],
                lines: [],
                after: []
            };
            const scoped = overrideCallbacks(callbacks, context);
            pushOrConcat(bodyItem.before, splitNewlines(invokeCallbackWithFallback(scoped, 'beforeLabel', this, context)));
            pushOrConcat(bodyItem.lines, invokeCallbackWithFallback(scoped, 'label', this, context));
            pushOrConcat(bodyItem.after, splitNewlines(invokeCallbackWithFallback(scoped, 'afterLabel', this, context)));
            bodyItems.push(bodyItem);
        });
        return bodyItems;
    }
    getAfterBody(tooltipItems, options) {
        return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'afterBody', this, tooltipItems));
    }
    getFooter(tooltipItems, options) {
        const { callbacks  } = options;
        const beforeFooter = invokeCallbackWithFallback(callbacks, 'beforeFooter', this, tooltipItems);
        const footer = invokeCallbackWithFallback(callbacks, 'footer', this, tooltipItems);
        const afterFooter = invokeCallbackWithFallback(callbacks, 'afterFooter', this, tooltipItems);
        let lines = [];
        lines = pushOrConcat(lines, splitNewlines(beforeFooter));
        lines = pushOrConcat(lines, splitNewlines(footer));
        lines = pushOrConcat(lines, splitNewlines(afterFooter));
        return lines;
    }
 _createItems(options) {
        const active = this._active;
        const data = this.chart.data;
        const labelColors = [];
        const labelPointStyles = [];
        const labelTextColors = [];
        let tooltipItems = [];
        let i, len;
        for(i = 0, len = active.length; i < len; ++i){
            tooltipItems.push(createTooltipItem(this.chart, active[i]));
        }
        if (options.filter) {
            tooltipItems = tooltipItems.filter((element, index, array)=>options.filter(element, index, array, data));
        }
        if (options.itemSort) {
            tooltipItems = tooltipItems.sort((a, b)=>options.itemSort(a, b, data));
        }
        each(tooltipItems, (context)=>{
            const scoped = overrideCallbacks(options.callbacks, context);
            labelColors.push(invokeCallbackWithFallback(scoped, 'labelColor', this, context));
            labelPointStyles.push(invokeCallbackWithFallback(scoped, 'labelPointStyle', this, context));
            labelTextColors.push(invokeCallbackWithFallback(scoped, 'labelTextColor', this, context));
        });
        this.labelColors = labelColors;
        this.labelPointStyles = labelPointStyles;
        this.labelTextColors = labelTextColors;
        this.dataPoints = tooltipItems;
        return tooltipItems;
    }
    update(changed, replay) {
        const options = this.options.setContext(this.getContext());
        const active = this._active;
        let properties;
        let tooltipItems = [];
        if (!active.length) {
            if (this.opacity !== 0) {
                properties = {
                    opacity: 0
                };
            }
        } else {
            const position = positioners[options.position].call(this, active, this._eventPosition);
            tooltipItems = this._createItems(options);
            this.title = this.getTitle(tooltipItems, options);
            this.beforeBody = this.getBeforeBody(tooltipItems, options);
            this.body = this.getBody(tooltipItems, options);
            this.afterBody = this.getAfterBody(tooltipItems, options);
            this.footer = this.getFooter(tooltipItems, options);
            const size = this._size = getTooltipSize(this, options);
            const positionAndSize = Object.assign({}, position, size);
            const alignment = determineAlignment(this.chart, options, positionAndSize);
            const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart);
            this.xAlign = alignment.xAlign;
            this.yAlign = alignment.yAlign;
            properties = {
                opacity: 1,
                x: backgroundPoint.x,
                y: backgroundPoint.y,
                width: size.width,
                height: size.height,
                caretX: position.x,
                caretY: position.y
            };
        }
        this._tooltipItems = tooltipItems;
        this.$context = undefined;
        if (properties) {
            this._resolveAnimations().update(this, properties);
        }
        if (changed && options.external) {
            options.external.call(this, {
                chart: this.chart,
                tooltip: this,
                replay
            });
        }
    }
    drawCaret(tooltipPoint, ctx, size, options) {
        const caretPosition = this.getCaretPosition(tooltipPoint, size, options);
        ctx.lineTo(caretPosition.x1, caretPosition.y1);
        ctx.lineTo(caretPosition.x2, caretPosition.y2);
        ctx.lineTo(caretPosition.x3, caretPosition.y3);
    }
    getCaretPosition(tooltipPoint, size, options) {
        const { xAlign , yAlign  } = this;
        const { caretSize , cornerRadius  } = options;
        const { topLeft , topRight , bottomLeft , bottomRight  } = toTRBLCorners(cornerRadius);
        const { x: ptX , y: ptY  } = tooltipPoint;
        const { width , height  } = size;
        let x1, x2, x3, y1, y2, y3;
        if (yAlign === 'center') {
            y2 = ptY + height / 2;
            if (xAlign === 'left') {
                x1 = ptX;
                x2 = x1 - caretSize;
                y1 = y2 + caretSize;
                y3 = y2 - caretSize;
            } else {
                x1 = ptX + width;
                x2 = x1 + caretSize;
                y1 = y2 - caretSize;
                y3 = y2 + caretSize;
            }
            x3 = x1;
        } else {
            if (xAlign === 'left') {
                x2 = ptX + Math.max(topLeft, bottomLeft) + caretSize;
            } else if (xAlign === 'right') {
                x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize;
            } else {
                x2 = this.caretX;
            }
            if (yAlign === 'top') {
                y1 = ptY;
                y2 = y1 - caretSize;
                x1 = x2 - caretSize;
                x3 = x2 + caretSize;
            } else {
                y1 = ptY + height;
                y2 = y1 + caretSize;
                x1 = x2 + caretSize;
                x3 = x2 - caretSize;
            }
            y3 = y1;
        }
        return {
            x1,
            x2,
            x3,
            y1,
            y2,
            y3
        };
    }
    drawTitle(pt, ctx, options) {
        const title = this.title;
        const length = title.length;
        let titleFont, titleSpacing, i;
        if (length) {
            const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
            pt.x = getAlignedX(this, options.titleAlign, options);
            ctx.textAlign = rtlHelper.textAlign(options.titleAlign);
            ctx.textBaseline = 'middle';
            titleFont = toFont(options.titleFont);
            titleSpacing = options.titleSpacing;
            ctx.fillStyle = options.titleColor;
            ctx.font = titleFont.string;
            for(i = 0; i < length; ++i){
                ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);
                pt.y += titleFont.lineHeight + titleSpacing;
                if (i + 1 === length) {
                    pt.y += options.titleMarginBottom - titleSpacing;
                }
            }
        }
    }
 _drawColorBox(ctx, pt, i, rtlHelper, options) {
        const labelColor = this.labelColors[i];
        const labelPointStyle = this.labelPointStyles[i];
        const { boxHeight , boxWidth  } = options;
        const bodyFont = toFont(options.bodyFont);
        const colorX = getAlignedX(this, 'left', options);
        const rtlColorX = rtlHelper.x(colorX);
        const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;
        const colorY = pt.y + yOffSet;
        if (options.usePointStyle) {
            const drawOptions = {
                radius: Math.min(boxWidth, boxHeight) / 2,
                pointStyle: labelPointStyle.pointStyle,
                rotation: labelPointStyle.rotation,
                borderWidth: 1
            };
            const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;
            const centerY = colorY + boxHeight / 2;
            ctx.strokeStyle = options.multiKeyBackground;
            ctx.fillStyle = options.multiKeyBackground;
            drawPoint(ctx, drawOptions, centerX, centerY);
            ctx.strokeStyle = labelColor.borderColor;
            ctx.fillStyle = labelColor.backgroundColor;
            drawPoint(ctx, drawOptions, centerX, centerY);
        } else {
            ctx.lineWidth = isObject(labelColor.borderWidth) ? Math.max(...Object.values(labelColor.borderWidth)) : labelColor.borderWidth || 1;
            ctx.strokeStyle = labelColor.borderColor;
            ctx.setLineDash(labelColor.borderDash || []);
            ctx.lineDashOffset = labelColor.borderDashOffset || 0;
            const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);
            const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);
            const borderRadius = toTRBLCorners(labelColor.borderRadius);
            if (Object.values(borderRadius).some((v)=>v !== 0)) {
                ctx.beginPath();
                ctx.fillStyle = options.multiKeyBackground;
                addRoundedRectPath(ctx, {
                    x: outerX,
                    y: colorY,
                    w: boxWidth,
                    h: boxHeight,
                    radius: borderRadius
                });
                ctx.fill();
                ctx.stroke();
                ctx.fillStyle = labelColor.backgroundColor;
                ctx.beginPath();
                addRoundedRectPath(ctx, {
                    x: innerX,
                    y: colorY + 1,
                    w: boxWidth - 2,
                    h: boxHeight - 2,
                    radius: borderRadius
                });
                ctx.fill();
            } else {
                ctx.fillStyle = options.multiKeyBackground;
                ctx.fillRect(outerX, colorY, boxWidth, boxHeight);
                ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);
                ctx.fillStyle = labelColor.backgroundColor;
                ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);
            }
        }
        ctx.fillStyle = this.labelTextColors[i];
    }
    drawBody(pt, ctx, options) {
        const { body  } = this;
        const { bodySpacing , bodyAlign , displayColors , boxHeight , boxWidth , boxPadding  } = options;
        const bodyFont = toFont(options.bodyFont);
        let bodyLineHeight = bodyFont.lineHeight;
        let xLinePadding = 0;
        const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
        const fillLineOfText = function(line) {
            ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);
            pt.y += bodyLineHeight + bodySpacing;
        };
        const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
        let bodyItem, textColor, lines, i, j, ilen, jlen;
        ctx.textAlign = bodyAlign;
        ctx.textBaseline = 'middle';
        ctx.font = bodyFont.string;
        pt.x = getAlignedX(this, bodyAlignForCalculation, options);
        ctx.fillStyle = options.bodyColor;
        each(this.beforeBody, fillLineOfText);
        xLinePadding = displayColors && bodyAlignForCalculation !== 'right' ? bodyAlign === 'center' ? boxWidth / 2 + boxPadding : boxWidth + 2 + boxPadding : 0;
        for(i = 0, ilen = body.length; i < ilen; ++i){
            bodyItem = body[i];
            textColor = this.labelTextColors[i];
            ctx.fillStyle = textColor;
            each(bodyItem.before, fillLineOfText);
            lines = bodyItem.lines;
            if (displayColors && lines.length) {
                this._drawColorBox(ctx, pt, i, rtlHelper, options);
                bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);
            }
            for(j = 0, jlen = lines.length; j < jlen; ++j){
                fillLineOfText(lines[j]);
                bodyLineHeight = bodyFont.lineHeight;
            }
            each(bodyItem.after, fillLineOfText);
        }
        xLinePadding = 0;
        bodyLineHeight = bodyFont.lineHeight;
        each(this.afterBody, fillLineOfText);
        pt.y -= bodySpacing;
    }
    drawFooter(pt, ctx, options) {
        const footer = this.footer;
        const length = footer.length;
        let footerFont, i;
        if (length) {
            const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
            pt.x = getAlignedX(this, options.footerAlign, options);
            pt.y += options.footerMarginTop;
            ctx.textAlign = rtlHelper.textAlign(options.footerAlign);
            ctx.textBaseline = 'middle';
            footerFont = toFont(options.footerFont);
            ctx.fillStyle = options.footerColor;
            ctx.font = footerFont.string;
            for(i = 0; i < length; ++i){
                ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);
                pt.y += footerFont.lineHeight + options.footerSpacing;
            }
        }
    }
    drawBackground(pt, ctx, tooltipSize, options) {
        const { xAlign , yAlign  } = this;
        const { x , y  } = pt;
        const { width , height  } = tooltipSize;
        const { topLeft , topRight , bottomLeft , bottomRight  } = toTRBLCorners(options.cornerRadius);
        ctx.fillStyle = options.backgroundColor;
        ctx.strokeStyle = options.borderColor;
        ctx.lineWidth = options.borderWidth;
        ctx.beginPath();
        ctx.moveTo(x + topLeft, y);
        if (yAlign === 'top') {
            this.drawCaret(pt, ctx, tooltipSize, options);
        }
        ctx.lineTo(x + width - topRight, y);
        ctx.quadraticCurveTo(x + width, y, x + width, y + topRight);
        if (yAlign === 'center' && xAlign === 'right') {
            this.drawCaret(pt, ctx, tooltipSize, options);
        }
        ctx.lineTo(x + width, y + height - bottomRight);
        ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height);
        if (yAlign === 'bottom') {
            this.drawCaret(pt, ctx, tooltipSize, options);
        }
        ctx.lineTo(x + bottomLeft, y + height);
        ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft);
        if (yAlign === 'center' && xAlign === 'left') {
            this.drawCaret(pt, ctx, tooltipSize, options);
        }
        ctx.lineTo(x, y + topLeft);
        ctx.quadraticCurveTo(x, y, x + topLeft, y);
        ctx.closePath();
        ctx.fill();
        if (options.borderWidth > 0) {
            ctx.stroke();
        }
    }
 _updateAnimationTarget(options) {
        const chart = this.chart;
        const anims = this.$animations;
        const animX = anims && anims.x;
        const animY = anims && anims.y;
        if (animX || animY) {
            const position = positioners[options.position].call(this, this._active, this._eventPosition);
            if (!position) {
                return;
            }
            const size = this._size = getTooltipSize(this, options);
            const positionAndSize = Object.assign({}, position, this._size);
            const alignment = determineAlignment(chart, options, positionAndSize);
            const point = getBackgroundPoint(options, positionAndSize, alignment, chart);
            if (animX._to !== point.x || animY._to !== point.y) {
                this.xAlign = alignment.xAlign;
                this.yAlign = alignment.yAlign;
                this.width = size.width;
                this.height = size.height;
                this.caretX = position.x;
                this.caretY = position.y;
                this._resolveAnimations().update(this, point);
            }
        }
    }
 _willRender() {
        return !!this.opacity;
    }
    draw(ctx) {
        const options = this.options.setContext(this.getContext());
        let opacity = this.opacity;
        if (!opacity) {
            return;
        }
        this._updateAnimationTarget(options);
        const tooltipSize = {
            width: this.width,
            height: this.height
        };
        const pt = {
            x: this.x,
            y: this.y
        };
        opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
        const padding = toPadding(options.padding);
        const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length;
        if (options.enabled && hasTooltipContent) {
            ctx.save();
            ctx.globalAlpha = opacity;
            this.drawBackground(pt, ctx, tooltipSize, options);
            overrideTextDirection(ctx, options.textDirection);
            pt.y += padding.top;
            this.drawTitle(pt, ctx, options);
            this.drawBody(pt, ctx, options);
            this.drawFooter(pt, ctx, options);
            restoreTextDirection(ctx, options.textDirection);
            ctx.restore();
        }
    }
 getActiveElements() {
        return this._active || [];
    }
 setActiveElements(activeElements, eventPosition) {
        const lastActive = this._active;
        const active = activeElements.map(({ datasetIndex , index  })=>{
            const meta = this.chart.getDatasetMeta(datasetIndex);
            if (!meta) {
                throw new Error('Cannot find a dataset at index ' + datasetIndex);
            }
            return {
                datasetIndex,
                element: meta.data[index],
                index
            };
        });
        const changed = !_elementsEqual(lastActive, active);
        const positionChanged = this._positionChanged(active, eventPosition);
        if (changed || positionChanged) {
            this._active = active;
            this._eventPosition = eventPosition;
            this._ignoreReplayEvents = true;
            this.update(true);
        }
    }
 handleEvent(e, replay, inChartArea = true) {
        if (replay && this._ignoreReplayEvents) {
            return false;
        }
        this._ignoreReplayEvents = false;
        const options = this.options;
        const lastActive = this._active || [];
        const active = this._getActiveElements(e, lastActive, replay, inChartArea);
        const positionChanged = this._positionChanged(active, e);
        const changed = replay || !_elementsEqual(active, lastActive) || positionChanged;
        if (changed) {
            this._active = active;
            if (options.enabled || options.external) {
                this._eventPosition = {
                    x: e.x,
                    y: e.y
                };
                this.update(true, replay);
            }
        }
        return changed;
    }
 _getActiveElements(e, lastActive, replay, inChartArea) {
        const options = this.options;
        if (e.type === 'mouseout') {
            return [];
        }
        if (!inChartArea) {
            return lastActive.filter((i)=>this.chart.data.datasets[i.datasetIndex] && this.chart.getDatasetMeta(i.datasetIndex).controller.getParsed(i.index) !== undefined);
        }
        const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay);
        if (options.reverse) {
            active.reverse();
        }
        return active;
    }
 _positionChanged(active, e) {
        const { caretX , caretY , options  } = this;
        const position = positioners[options.position].call(this, active, e);
        return position !== false && (caretX !== position.x || caretY !== position.y);
    }
}
var plugin_tooltip = {
    id: 'tooltip',
    _element: Tooltip,
    positioners,
    afterInit (chart, _args, options) {
        if (options) {
            chart.tooltip = new Tooltip({
                chart,
                options
            });
        }
    },
    beforeUpdate (chart, _args, options) {
        if (chart.tooltip) {
            chart.tooltip.initialize(options);
        }
    },
    reset (chart, _args, options) {
        if (chart.tooltip) {
            chart.tooltip.initialize(options);
        }
    },
    afterDraw (chart) {
        const tooltip = chart.tooltip;
        if (tooltip && tooltip._willRender()) {
            const args = {
                tooltip
            };
            if (chart.notifyPlugins('beforeTooltipDraw', {
                ...args,
                cancelable: true
            }) === false) {
                return;
            }
            tooltip.draw(chart.ctx);
            chart.notifyPlugins('afterTooltipDraw', args);
        }
    },
    afterEvent (chart, args) {
        if (chart.tooltip) {
            const useFinalPosition = args.replay;
            if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) {
                args.changed = true;
            }
        }
    },
    defaults: {
        enabled: true,
        external: null,
        position: 'average',
        backgroundColor: 'rgba(0,0,0,0.8)',
        titleColor: '#fff',
        titleFont: {
            weight: 'bold'
        },
        titleSpacing: 2,
        titleMarginBottom: 6,
        titleAlign: 'left',
        bodyColor: '#fff',
        bodySpacing: 2,
        bodyFont: {},
        bodyAlign: 'left',
        footerColor: '#fff',
        footerSpacing: 2,
        footerMarginTop: 6,
        footerFont: {
            weight: 'bold'
        },
        footerAlign: 'left',
        padding: 6,
        caretPadding: 2,
        caretSize: 5,
        cornerRadius: 6,
        boxHeight: (ctx, opts)=>opts.bodyFont.size,
        boxWidth: (ctx, opts)=>opts.bodyFont.size,
        multiKeyBackground: '#fff',
        displayColors: true,
        boxPadding: 0,
        borderColor: 'rgba(0,0,0,0)',
        borderWidth: 0,
        animation: {
            duration: 400,
            easing: 'easeOutQuart'
        },
        animations: {
            numbers: {
                type: 'number',
                properties: [
                    'x',
                    'y',
                    'width',
                    'height',
                    'caretX',
                    'caretY'
                ]
            },
            opacity: {
                easing: 'linear',
                duration: 200
            }
        },
        callbacks: defaultCallbacks
    },
    defaultRoutes: {
        bodyFont: 'font',
        footerFont: 'font',
        titleFont: 'font'
    },
    descriptors: {
        _scriptable: (name)=>name !== 'filter' && name !== 'itemSort' && name !== 'external',
        _indexable: false,
        callbacks: {
            _scriptable: false,
            _indexable: false
        },
        animation: {
            _fallback: false
        },
        animations: {
            _fallback: 'animation'
        }
    },
    additionalOptionScopes: [
        'interaction'
    ]
};

var plugins = /*#__PURE__*/Object.freeze({
__proto__: null,
Colors: plugin_colors,
Decimation: plugin_decimation,
Filler: index,
Legend: plugin_legend,
SubTitle: plugin_subtitle,
Title: plugin_title,
Tooltip: plugin_tooltip
});

const addIfString = (labels, raw, index, addedLabels)=>{
    if (typeof raw === 'string') {
        index = labels.push(raw) - 1;
        addedLabels.unshift({
            index,
            label: raw
        });
    } else if (isNaN(raw)) {
        index = null;
    }
    return index;
};
function findOrAddLabel(labels, raw, index, addedLabels) {
    const first = labels.indexOf(raw);
    if (first === -1) {
        return addIfString(labels, raw, index, addedLabels);
    }
    const last = labels.lastIndexOf(raw);
    return first !== last ? index : first;
}
const validIndex = (index, max)=>index === null ? null : _limitValue(Math.round(index), 0, max);
function _getLabelForValue(value) {
    const labels = this.getLabels();
    if (value >= 0 && value < labels.length) {
        return labels[value];
    }
    return value;
}
class CategoryScale extends Scale {
    static id = 'category';
 static defaults = {
        ticks: {
            callback: _getLabelForValue
        }
    };
    constructor(cfg){
        super(cfg);
         this._startValue = undefined;
        this._valueRange = 0;
        this._addedLabels = [];
    }
    init(scaleOptions) {
        const added = this._addedLabels;
        if (added.length) {
            const labels = this.getLabels();
            for (const { index , label  } of added){
                if (labels[index] === label) {
                    labels.splice(index, 1);
                }
            }
            this._addedLabels = [];
        }
        super.init(scaleOptions);
    }
    parse(raw, index) {
        if (isNullOrUndef(raw)) {
            return null;
        }
        const labels = this.getLabels();
        index = isFinite(index) && labels[index] === raw ? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw), this._addedLabels);
        return validIndex(index, labels.length - 1);
    }
    determineDataLimits() {
        const { minDefined , maxDefined  } = this.getUserBounds();
        let { min , max  } = this.getMinMax(true);
        if (this.options.bounds === 'ticks') {
            if (!minDefined) {
                min = 0;
            }
            if (!maxDefined) {
                max = this.getLabels().length - 1;
            }
        }
        this.min = min;
        this.max = max;
    }
    buildTicks() {
        const min = this.min;
        const max = this.max;
        const offset = this.options.offset;
        const ticks = [];
        let labels = this.getLabels();
        labels = min === 0 && max === labels.length - 1 ? labels : labels.slice(min, max + 1);
        this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);
        this._startValue = this.min - (offset ? 0.5 : 0);
        for(let value = min; value <= max; value++){
            ticks.push({
                value
            });
        }
        return ticks;
    }
    getLabelForValue(value) {
        return _getLabelForValue.call(this, value);
    }
 configure() {
        super.configure();
        if (!this.isHorizontal()) {
            this._reversePixels = !this._reversePixels;
        }
    }
    getPixelForValue(value) {
        if (typeof value !== 'number') {
            value = this.parse(value);
        }
        return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
    }
    getPixelForTick(index) {
        const ticks = this.ticks;
        if (index < 0 || index > ticks.length - 1) {
            return null;
        }
        return this.getPixelForValue(ticks[index].value);
    }
    getValueForPixel(pixel) {
        return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange);
    }
    getBasePixel() {
        return this.bottom;
    }
}

function generateTicks$1(generationOptions, dataRange) {
    const ticks = [];
    const MIN_SPACING = 1e-14;
    const { bounds , step , min , max , precision , count , maxTicks , maxDigits , includeBounds  } = generationOptions;
    const unit = step || 1;
    const maxSpaces = maxTicks - 1;
    const { min: rmin , max: rmax  } = dataRange;
    const minDefined = !isNullOrUndef(min);
    const maxDefined = !isNullOrUndef(max);
    const countDefined = !isNullOrUndef(count);
    const minSpacing = (rmax - rmin) / (maxDigits + 1);
    let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;
    let factor, niceMin, niceMax, numSpaces;
    if (spacing < MIN_SPACING && !minDefined && !maxDefined) {
        return [
            {
                value: rmin
            },
            {
                value: rmax
            }
        ];
    }
    numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
    if (numSpaces > maxSpaces) {
        spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;
    }
    if (!isNullOrUndef(precision)) {
        factor = Math.pow(10, precision);
        spacing = Math.ceil(spacing * factor) / factor;
    }
    if (bounds === 'ticks') {
        niceMin = Math.floor(rmin / spacing) * spacing;
        niceMax = Math.ceil(rmax / spacing) * spacing;
    } else {
        niceMin = rmin;
        niceMax = rmax;
    }
    if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) {
        numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));
        spacing = (max - min) / numSpaces;
        niceMin = min;
        niceMax = max;
    } else if (countDefined) {
        niceMin = minDefined ? min : niceMin;
        niceMax = maxDefined ? max : niceMax;
        numSpaces = count - 1;
        spacing = (niceMax - niceMin) / numSpaces;
    } else {
        numSpaces = (niceMax - niceMin) / spacing;
        if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
            numSpaces = Math.round(numSpaces);
        } else {
            numSpaces = Math.ceil(numSpaces);
        }
    }
    const decimalPlaces = Math.max(_decimalPlaces(spacing), _decimalPlaces(niceMin));
    factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);
    niceMin = Math.round(niceMin * factor) / factor;
    niceMax = Math.round(niceMax * factor) / factor;
    let j = 0;
    if (minDefined) {
        if (includeBounds && niceMin !== min) {
            ticks.push({
                value: min
            });
            if (niceMin < min) {
                j++;
            }
            if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) {
                j++;
            }
        } else if (niceMin < min) {
            j++;
        }
    }
    for(; j < numSpaces; ++j){
        const tickValue = Math.round((niceMin + j * spacing) * factor) / factor;
        if (maxDefined && tickValue > max) {
            break;
        }
        ticks.push({
            value: tickValue
        });
    }
    if (maxDefined && includeBounds && niceMax !== max) {
        if (ticks.length && almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) {
            ticks[ticks.length - 1].value = max;
        } else {
            ticks.push({
                value: max
            });
        }
    } else if (!maxDefined || niceMax === max) {
        ticks.push({
            value: niceMax
        });
    }
    return ticks;
}
function relativeLabelSize(value, minSpacing, { horizontal , minRotation  }) {
    const rad = toRadians(minRotation);
    const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001;
    const length = 0.75 * minSpacing * ('' + value).length;
    return Math.min(minSpacing / ratio, length);
}
class LinearScaleBase extends Scale {
    constructor(cfg){
        super(cfg);
         this.start = undefined;
         this.end = undefined;
         this._startValue = undefined;
         this._endValue = undefined;
        this._valueRange = 0;
    }
    parse(raw, index) {
        if (isNullOrUndef(raw)) {
            return null;
        }
        if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {
            return null;
        }
        return +raw;
    }
    handleTickRangeOptions() {
        const { beginAtZero  } = this.options;
        const { minDefined , maxDefined  } = this.getUserBounds();
        let { min , max  } = this;
        const setMin = (v)=>min = minDefined ? min : v;
        const setMax = (v)=>max = maxDefined ? max : v;
        if (beginAtZero) {
            const minSign = sign(min);
            const maxSign = sign(max);
            if (minSign < 0 && maxSign < 0) {
                setMax(0);
            } else if (minSign > 0 && maxSign > 0) {
                setMin(0);
            }
        }
        if (min === max) {
            let offset = max === 0 ? 1 : Math.abs(max * 0.05);
            setMax(max + offset);
            if (!beginAtZero) {
                setMin(min - offset);
            }
        }
        this.min = min;
        this.max = max;
    }
    getTickLimit() {
        const tickOpts = this.options.ticks;
        let { maxTicksLimit , stepSize  } = tickOpts;
        let maxTicks;
        if (stepSize) {
            maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1;
            if (maxTicks > 1000) {
                console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`);
                maxTicks = 1000;
            }
        } else {
            maxTicks = this.computeTickLimit();
            maxTicksLimit = maxTicksLimit || 11;
        }
        if (maxTicksLimit) {
            maxTicks = Math.min(maxTicksLimit, maxTicks);
        }
        return maxTicks;
    }
 computeTickLimit() {
        return Number.POSITIVE_INFINITY;
    }
    buildTicks() {
        const opts = this.options;
        const tickOpts = opts.ticks;
        let maxTicks = this.getTickLimit();
        maxTicks = Math.max(2, maxTicks);
        const numericGeneratorOptions = {
            maxTicks,
            bounds: opts.bounds,
            min: opts.min,
            max: opts.max,
            precision: tickOpts.precision,
            step: tickOpts.stepSize,
            count: tickOpts.count,
            maxDigits: this._maxDigits(),
            horizontal: this.isHorizontal(),
            minRotation: tickOpts.minRotation || 0,
            includeBounds: tickOpts.includeBounds !== false
        };
        const dataRange = this._range || this;
        const ticks = generateTicks$1(numericGeneratorOptions, dataRange);
        if (opts.bounds === 'ticks') {
            _setMinAndMaxByKey(ticks, this, 'value');
        }
        if (opts.reverse) {
            ticks.reverse();
            this.start = this.max;
            this.end = this.min;
        } else {
            this.start = this.min;
            this.end = this.max;
        }
        return ticks;
    }
 configure() {
        const ticks = this.ticks;
        let start = this.min;
        let end = this.max;
        super.configure();
        if (this.options.offset && ticks.length) {
            const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
            start -= offset;
            end += offset;
        }
        this._startValue = start;
        this._endValue = end;
        this._valueRange = end - start;
    }
    getLabelForValue(value) {
        return formatNumber(value, this.chart.options.locale, this.options.ticks.format);
    }
}

class LinearScale extends LinearScaleBase {
    static id = 'linear';
 static defaults = {
        ticks: {
            callback: Ticks.formatters.numeric
        }
    };
    determineDataLimits() {
        const { min , max  } = this.getMinMax(true);
        this.min = isNumberFinite(min) ? min : 0;
        this.max = isNumberFinite(max) ? max : 1;
        this.handleTickRangeOptions();
    }
 computeTickLimit() {
        const horizontal = this.isHorizontal();
        const length = horizontal ? this.width : this.height;
        const minRotation = toRadians(this.options.ticks.minRotation);
        const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001;
        const tickFont = this._resolveTickFontOptions(0);
        return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));
    }
    getPixelForValue(value) {
        return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
    }
    getValueForPixel(pixel) {
        return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
    }
}

const log10Floor = (v)=>Math.floor(log10(v));
const changeExponent = (v, m)=>Math.pow(10, log10Floor(v) + m);
function isMajor(tickVal) {
    const remain = tickVal / Math.pow(10, log10Floor(tickVal));
    return remain === 1;
}
function steps(min, max, rangeExp) {
    const rangeStep = Math.pow(10, rangeExp);
    const start = Math.floor(min / rangeStep);
    const end = Math.ceil(max / rangeStep);
    return end - start;
}
function startExp(min, max) {
    const range = max - min;
    let rangeExp = log10Floor(range);
    while(steps(min, max, rangeExp) > 10){
        rangeExp++;
    }
    while(steps(min, max, rangeExp) < 10){
        rangeExp--;
    }
    return Math.min(rangeExp, log10Floor(min));
}
 function generateTicks(generationOptions, { min , max  }) {
    min = finiteOrDefault(generationOptions.min, min);
    const ticks = [];
    const minExp = log10Floor(min);
    let exp = startExp(min, max);
    let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
    const stepSize = Math.pow(10, exp);
    const base = minExp > exp ? Math.pow(10, minExp) : 0;
    const start = Math.round((min - base) * precision) / precision;
    const offset = Math.floor((min - base) / stepSize / 10) * stepSize * 10;
    let significand = Math.floor((start - offset) / Math.pow(10, exp));
    let value = finiteOrDefault(generationOptions.min, Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision);
    while(value < max){
        ticks.push({
            value,
            major: isMajor(value),
            significand
        });
        if (significand >= 10) {
            significand = significand < 15 ? 15 : 20;
        } else {
            significand++;
        }
        if (significand >= 20) {
            exp++;
            significand = 2;
            precision = exp >= 0 ? 1 : precision;
        }
        value = Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision;
    }
    const lastTick = finiteOrDefault(generationOptions.max, value);
    ticks.push({
        value: lastTick,
        major: isMajor(lastTick),
        significand
    });
    return ticks;
}
class LogarithmicScale extends Scale {
    static id = 'logarithmic';
 static defaults = {
        ticks: {
            callback: Ticks.formatters.logarithmic,
            major: {
                enabled: true
            }
        }
    };
    constructor(cfg){
        super(cfg);
         this.start = undefined;
         this.end = undefined;
         this._startValue = undefined;
        this._valueRange = 0;
    }
    parse(raw, index) {
        const value = LinearScaleBase.prototype.parse.apply(this, [
            raw,
            index
        ]);
        if (value === 0) {
            this._zero = true;
            return undefined;
        }
        return isNumberFinite(value) && value > 0 ? value : null;
    }
    determineDataLimits() {
        const { min , max  } = this.getMinMax(true);
        this.min = isNumberFinite(min) ? Math.max(0, min) : null;
        this.max = isNumberFinite(max) ? Math.max(0, max) : null;
        if (this.options.beginAtZero) {
            this._zero = true;
        }
        if (this._zero && this.min !== this._suggestedMin && !isNumberFinite(this._userMin)) {
            this.min = min === changeExponent(this.min, 0) ? changeExponent(this.min, -1) : changeExponent(this.min, 0);
        }
        this.handleTickRangeOptions();
    }
    handleTickRangeOptions() {
        const { minDefined , maxDefined  } = this.getUserBounds();
        let min = this.min;
        let max = this.max;
        const setMin = (v)=>min = minDefined ? min : v;
        const setMax = (v)=>max = maxDefined ? max : v;
        if (min === max) {
            if (min <= 0) {
                setMin(1);
                setMax(10);
            } else {
                setMin(changeExponent(min, -1));
                setMax(changeExponent(max, +1));
            }
        }
        if (min <= 0) {
            setMin(changeExponent(max, -1));
        }
        if (max <= 0) {
            setMax(changeExponent(min, +1));
        }
        this.min = min;
        this.max = max;
    }
    buildTicks() {
        const opts = this.options;
        const generationOptions = {
            min: this._userMin,
            max: this._userMax
        };
        const ticks = generateTicks(generationOptions, this);
        if (opts.bounds === 'ticks') {
            _setMinAndMaxByKey(ticks, this, 'value');
        }
        if (opts.reverse) {
            ticks.reverse();
            this.start = this.max;
            this.end = this.min;
        } else {
            this.start = this.min;
            this.end = this.max;
        }
        return ticks;
    }
 getLabelForValue(value) {
        return value === undefined ? '0' : formatNumber(value, this.chart.options.locale, this.options.ticks.format);
    }
 configure() {
        const start = this.min;
        super.configure();
        this._startValue = log10(start);
        this._valueRange = log10(this.max) - log10(start);
    }
    getPixelForValue(value) {
        if (value === undefined || value === 0) {
            value = this.min;
        }
        if (value === null || isNaN(value)) {
            return NaN;
        }
        return this.getPixelForDecimal(value === this.min ? 0 : (log10(value) - this._startValue) / this._valueRange);
    }
    getValueForPixel(pixel) {
        const decimal = this.getDecimalForPixel(pixel);
        return Math.pow(10, this._startValue + decimal * this._valueRange);
    }
}

function getTickBackdropHeight(opts) {
    const tickOpts = opts.ticks;
    if (tickOpts.display && opts.display) {
        const padding = toPadding(tickOpts.backdropPadding);
        return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;
    }
    return 0;
}
function measureLabelSize(ctx, font, label) {
    label = isArray(label) ? label : [
        label
    ];
    return {
        w: _longestText(ctx, font.string, label),
        h: label.length * font.lineHeight
    };
}
function determineLimits(angle, pos, size, min, max) {
    if (angle === min || angle === max) {
        return {
            start: pos - size / 2,
            end: pos + size / 2
        };
    } else if (angle < min || angle > max) {
        return {
            start: pos - size,
            end: pos
        };
    }
    return {
        start: pos,
        end: pos + size
    };
}
 function fitWithPointLabels(scale) {
    const orig = {
        l: scale.left + scale._padding.left,
        r: scale.right - scale._padding.right,
        t: scale.top + scale._padding.top,
        b: scale.bottom - scale._padding.bottom
    };
    const limits = Object.assign({}, orig);
    const labelSizes = [];
    const padding = [];
    const valueCount = scale._pointLabels.length;
    const pointLabelOpts = scale.options.pointLabels;
    const additionalAngle = pointLabelOpts.centerPointLabels ? PI / valueCount : 0;
    for(let i = 0; i < valueCount; i++){
        const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i));
        padding[i] = opts.padding;
        const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle);
        const plFont = toFont(opts.font);
        const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]);
        labelSizes[i] = textSize;
        const angleRadians = _normalizeAngle(scale.getIndexAngle(i) + additionalAngle);
        const angle = Math.round(toDegrees(angleRadians));
        const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
        const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
        updateLimits(limits, orig, angleRadians, hLimits, vLimits);
    }
    scale.setCenterPoint(orig.l - limits.l, limits.r - orig.r, orig.t - limits.t, limits.b - orig.b);
    scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);
}
function updateLimits(limits, orig, angle, hLimits, vLimits) {
    const sin = Math.abs(Math.sin(angle));
    const cos = Math.abs(Math.cos(angle));
    let x = 0;
    let y = 0;
    if (hLimits.start < orig.l) {
        x = (orig.l - hLimits.start) / sin;
        limits.l = Math.min(limits.l, orig.l - x);
    } else if (hLimits.end > orig.r) {
        x = (hLimits.end - orig.r) / sin;
        limits.r = Math.max(limits.r, orig.r + x);
    }
    if (vLimits.start < orig.t) {
        y = (orig.t - vLimits.start) / cos;
        limits.t = Math.min(limits.t, orig.t - y);
    } else if (vLimits.end > orig.b) {
        y = (vLimits.end - orig.b) / cos;
        limits.b = Math.max(limits.b, orig.b + y);
    }
}
function createPointLabelItem(scale, index, itemOpts) {
    const outerDistance = scale.drawingArea;
    const { extra , additionalAngle , padding , size  } = itemOpts;
    const pointLabelPosition = scale.getPointPosition(index, outerDistance + extra + padding, additionalAngle);
    const angle = Math.round(toDegrees(_normalizeAngle(pointLabelPosition.angle + HALF_PI)));
    const y = yForAngle(pointLabelPosition.y, size.h, angle);
    const textAlign = getTextAlignForAngle(angle);
    const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);
    return {
        visible: true,
        x: pointLabelPosition.x,
        y,
        textAlign,
        left,
        top: y,
        right: left + size.w,
        bottom: y + size.h
    };
}
function isNotOverlapped(item, area) {
    if (!area) {
        return true;
    }
    const { left , top , right , bottom  } = item;
    const apexesInArea = _isPointInArea({
        x: left,
        y: top
    }, area) || _isPointInArea({
        x: left,
        y: bottom
    }, area) || _isPointInArea({
        x: right,
        y: top
    }, area) || _isPointInArea({
        x: right,
        y: bottom
    }, area);
    return !apexesInArea;
}
function buildPointLabelItems(scale, labelSizes, padding) {
    const items = [];
    const valueCount = scale._pointLabels.length;
    const opts = scale.options;
    const { centerPointLabels , display  } = opts.pointLabels;
    const itemOpts = {
        extra: getTickBackdropHeight(opts) / 2,
        additionalAngle: centerPointLabels ? PI / valueCount : 0
    };
    let area;
    for(let i = 0; i < valueCount; i++){
        itemOpts.padding = padding[i];
        itemOpts.size = labelSizes[i];
        const item = createPointLabelItem(scale, i, itemOpts);
        items.push(item);
        if (display === 'auto') {
            item.visible = isNotOverlapped(item, area);
            if (item.visible) {
                area = item;
            }
        }
    }
    return items;
}
function getTextAlignForAngle(angle) {
    if (angle === 0 || angle === 180) {
        return 'center';
    } else if (angle < 180) {
        return 'left';
    }
    return 'right';
}
function leftForTextAlign(x, w, align) {
    if (align === 'right') {
        x -= w;
    } else if (align === 'center') {
        x -= w / 2;
    }
    return x;
}
function yForAngle(y, h, angle) {
    if (angle === 90 || angle === 270) {
        y -= h / 2;
    } else if (angle > 270 || angle < 90) {
        y -= h;
    }
    return y;
}
function drawPointLabelBox(ctx, opts, item) {
    const { left , top , right , bottom  } = item;
    const { backdropColor  } = opts;
    if (!isNullOrUndef(backdropColor)) {
        const borderRadius = toTRBLCorners(opts.borderRadius);
        const padding = toPadding(opts.backdropPadding);
        ctx.fillStyle = backdropColor;
        const backdropLeft = left - padding.left;
        const backdropTop = top - padding.top;
        const backdropWidth = right - left + padding.width;
        const backdropHeight = bottom - top + padding.height;
        if (Object.values(borderRadius).some((v)=>v !== 0)) {
            ctx.beginPath();
            addRoundedRectPath(ctx, {
                x: backdropLeft,
                y: backdropTop,
                w: backdropWidth,
                h: backdropHeight,
                radius: borderRadius
            });
            ctx.fill();
        } else {
            ctx.fillRect(backdropLeft, backdropTop, backdropWidth, backdropHeight);
        }
    }
}
function drawPointLabels(scale, labelCount) {
    const { ctx , options: { pointLabels  }  } = scale;
    for(let i = labelCount - 1; i >= 0; i--){
        const item = scale._pointLabelItems[i];
        if (!item.visible) {
            continue;
        }
        const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i));
        drawPointLabelBox(ctx, optsAtIndex, item);
        const plFont = toFont(optsAtIndex.font);
        const { x , y , textAlign  } = item;
        renderText(ctx, scale._pointLabels[i], x, y + plFont.lineHeight / 2, plFont, {
            color: optsAtIndex.color,
            textAlign: textAlign,
            textBaseline: 'middle'
        });
    }
}
function pathRadiusLine(scale, radius, circular, labelCount) {
    const { ctx  } = scale;
    if (circular) {
        ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);
    } else {
        let pointPosition = scale.getPointPosition(0, radius);
        ctx.moveTo(pointPosition.x, pointPosition.y);
        for(let i = 1; i < labelCount; i++){
            pointPosition = scale.getPointPosition(i, radius);
            ctx.lineTo(pointPosition.x, pointPosition.y);
        }
    }
}
function drawRadiusLine(scale, gridLineOpts, radius, labelCount, borderOpts) {
    const ctx = scale.ctx;
    const circular = gridLineOpts.circular;
    const { color , lineWidth  } = gridLineOpts;
    if (!circular && !labelCount || !color || !lineWidth || radius < 0) {
        return;
    }
    ctx.save();
    ctx.strokeStyle = color;
    ctx.lineWidth = lineWidth;
    ctx.setLineDash(borderOpts.dash || []);
    ctx.lineDashOffset = borderOpts.dashOffset;
    ctx.beginPath();
    pathRadiusLine(scale, radius, circular, labelCount);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
}
function createPointLabelContext(parent, index, label) {
    return createContext(parent, {
        label,
        index,
        type: 'pointLabel'
    });
}
class RadialLinearScale extends LinearScaleBase {
    static id = 'radialLinear';
 static defaults = {
        display: true,
        animate: true,
        position: 'chartArea',
        angleLines: {
            display: true,
            lineWidth: 1,
            borderDash: [],
            borderDashOffset: 0.0
        },
        grid: {
            circular: false
        },
        startAngle: 0,
        ticks: {
            showLabelBackdrop: true,
            callback: Ticks.formatters.numeric
        },
        pointLabels: {
            backdropColor: undefined,
            backdropPadding: 2,
            display: true,
            font: {
                size: 10
            },
            callback (label) {
                return label;
            },
            padding: 5,
            centerPointLabels: false
        }
    };
    static defaultRoutes = {
        'angleLines.color': 'borderColor',
        'pointLabels.color': 'color',
        'ticks.color': 'color'
    };
    static descriptors = {
        angleLines: {
            _fallback: 'grid'
        }
    };
    constructor(cfg){
        super(cfg);
         this.xCenter = undefined;
         this.yCenter = undefined;
         this.drawingArea = undefined;
         this._pointLabels = [];
        this._pointLabelItems = [];
    }
    setDimensions() {
        const padding = this._padding = toPadding(getTickBackdropHeight(this.options) / 2);
        const w = this.width = this.maxWidth - padding.width;
        const h = this.height = this.maxHeight - padding.height;
        this.xCenter = Math.floor(this.left + w / 2 + padding.left);
        this.yCenter = Math.floor(this.top + h / 2 + padding.top);
        this.drawingArea = Math.floor(Math.min(w, h) / 2);
    }
    determineDataLimits() {
        const { min , max  } = this.getMinMax(false);
        this.min = isNumberFinite(min) && !isNaN(min) ? min : 0;
        this.max = isNumberFinite(max) && !isNaN(max) ? max : 0;
        this.handleTickRangeOptions();
    }
 computeTickLimit() {
        return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
    }
    generateTickLabels(ticks) {
        LinearScaleBase.prototype.generateTickLabels.call(this, ticks);
        this._pointLabels = this.getLabels().map((value, index)=>{
            const label = callback(this.options.pointLabels.callback, [
                value,
                index
            ], this);
            return label || label === 0 ? label : '';
        }).filter((v, i)=>this.chart.getDataVisibility(i));
    }
    fit() {
        const opts = this.options;
        if (opts.display && opts.pointLabels.display) {
            fitWithPointLabels(this);
        } else {
            this.setCenterPoint(0, 0, 0, 0);
        }
    }
    setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
        this.xCenter += Math.floor((leftMovement - rightMovement) / 2);
        this.yCenter += Math.floor((topMovement - bottomMovement) / 2);
        this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement));
    }
    getIndexAngle(index) {
        const angleMultiplier = TAU / (this._pointLabels.length || 1);
        const startAngle = this.options.startAngle || 0;
        return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));
    }
    getDistanceFromCenterForValue(value) {
        if (isNullOrUndef(value)) {
            return NaN;
        }
        const scalingFactor = this.drawingArea / (this.max - this.min);
        if (this.options.reverse) {
            return (this.max - value) * scalingFactor;
        }
        return (value - this.min) * scalingFactor;
    }
    getValueForDistanceFromCenter(distance) {
        if (isNullOrUndef(distance)) {
            return NaN;
        }
        const scaledDistance = distance / (this.drawingArea / (this.max - this.min));
        return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance;
    }
    getPointLabelContext(index) {
        const pointLabels = this._pointLabels || [];
        if (index >= 0 && index < pointLabels.length) {
            const pointLabel = pointLabels[index];
            return createPointLabelContext(this.getContext(), index, pointLabel);
        }
    }
    getPointPosition(index, distanceFromCenter, additionalAngle = 0) {
        const angle = this.getIndexAngle(index) - HALF_PI + additionalAngle;
        return {
            x: Math.cos(angle) * distanceFromCenter + this.xCenter,
            y: Math.sin(angle) * distanceFromCenter + this.yCenter,
            angle
        };
    }
    getPointPositionForValue(index, value) {
        return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
    }
    getBasePosition(index) {
        return this.getPointPositionForValue(index || 0, this.getBaseValue());
    }
    getPointLabelPosition(index) {
        const { left , top , right , bottom  } = this._pointLabelItems[index];
        return {
            left,
            top,
            right,
            bottom
        };
    }
 drawBackground() {
        const { backgroundColor , grid: { circular  }  } = this.options;
        if (backgroundColor) {
            const ctx = this.ctx;
            ctx.save();
            ctx.beginPath();
            pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length);
            ctx.closePath();
            ctx.fillStyle = backgroundColor;
            ctx.fill();
            ctx.restore();
        }
    }
 drawGrid() {
        const ctx = this.ctx;
        const opts = this.options;
        const { angleLines , grid , border  } = opts;
        const labelCount = this._pointLabels.length;
        let i, offset, position;
        if (opts.pointLabels.display) {
            drawPointLabels(this, labelCount);
        }
        if (grid.display) {
            this.ticks.forEach((tick, index)=>{
                if (index !== 0 || index === 0 && this.min < 0) {
                    offset = this.getDistanceFromCenterForValue(tick.value);
                    const context = this.getContext(index);
                    const optsAtIndex = grid.setContext(context);
                    const optsAtIndexBorder = border.setContext(context);
                    drawRadiusLine(this, optsAtIndex, offset, labelCount, optsAtIndexBorder);
                }
            });
        }
        if (angleLines.display) {
            ctx.save();
            for(i = labelCount - 1; i >= 0; i--){
                const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i));
                const { color , lineWidth  } = optsAtIndex;
                if (!lineWidth || !color) {
                    continue;
                }
                ctx.lineWidth = lineWidth;
                ctx.strokeStyle = color;
                ctx.setLineDash(optsAtIndex.borderDash);
                ctx.lineDashOffset = optsAtIndex.borderDashOffset;
                offset = this.getDistanceFromCenterForValue(opts.reverse ? this.min : this.max);
                position = this.getPointPosition(i, offset);
                ctx.beginPath();
                ctx.moveTo(this.xCenter, this.yCenter);
                ctx.lineTo(position.x, position.y);
                ctx.stroke();
            }
            ctx.restore();
        }
    }
 drawBorder() {}
 drawLabels() {
        const ctx = this.ctx;
        const opts = this.options;
        const tickOpts = opts.ticks;
        if (!tickOpts.display) {
            return;
        }
        const startAngle = this.getIndexAngle(0);
        let offset, width;
        ctx.save();
        ctx.translate(this.xCenter, this.yCenter);
        ctx.rotate(startAngle);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        this.ticks.forEach((tick, index)=>{
            if (index === 0 && this.min >= 0 && !opts.reverse) {
                return;
            }
            const optsAtIndex = tickOpts.setContext(this.getContext(index));
            const tickFont = toFont(optsAtIndex.font);
            offset = this.getDistanceFromCenterForValue(this.ticks[index].value);
            if (optsAtIndex.showLabelBackdrop) {
                ctx.font = tickFont.string;
                width = ctx.measureText(tick.label).width;
                ctx.fillStyle = optsAtIndex.backdropColor;
                const padding = toPadding(optsAtIndex.backdropPadding);
                ctx.fillRect(-width / 2 - padding.left, -offset - tickFont.size / 2 - padding.top, width + padding.width, tickFont.size + padding.height);
            }
            renderText(ctx, tick.label, 0, -offset, tickFont, {
                color: optsAtIndex.color,
                strokeColor: optsAtIndex.textStrokeColor,
                strokeWidth: optsAtIndex.textStrokeWidth
            });
        });
        ctx.restore();
    }
 drawTitle() {}
}

const INTERVALS = {
    millisecond: {
        common: true,
        size: 1,
        steps: 1000
    },
    second: {
        common: true,
        size: 1000,
        steps: 60
    },
    minute: {
        common: true,
        size: 60000,
        steps: 60
    },
    hour: {
        common: true,
        size: 3600000,
        steps: 24
    },
    day: {
        common: true,
        size: 86400000,
        steps: 30
    },
    week: {
        common: false,
        size: 604800000,
        steps: 4
    },
    month: {
        common: true,
        size: 2.628e9,
        steps: 12
    },
    quarter: {
        common: false,
        size: 7.884e9,
        steps: 4
    },
    year: {
        common: true,
        size: 3.154e10
    }
};
 const UNITS =  /* #__PURE__ */ Object.keys(INTERVALS);
 function sorter(a, b) {
    return a - b;
}
 function parse(scale, input) {
    if (isNullOrUndef(input)) {
        return null;
    }
    const adapter = scale._adapter;
    const { parser , round , isoWeekday  } = scale._parseOpts;
    let value = input;
    if (typeof parser === 'function') {
        value = parser(value);
    }
    if (!isNumberFinite(value)) {
        value = typeof parser === 'string' ? adapter.parse(value, parser) : adapter.parse(value);
    }
    if (value === null) {
        return null;
    }
    if (round) {
        value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true) ? adapter.startOf(value, 'isoWeek', isoWeekday) : adapter.startOf(value, round);
    }
    return +value;
}
 function determineUnitForAutoTicks(minUnit, min, max, capacity) {
    const ilen = UNITS.length;
    for(let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i){
        const interval = INTERVALS[UNITS[i]];
        const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;
        if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
            return UNITS[i];
        }
    }
    return UNITS[ilen - 1];
}
 function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
    for(let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--){
        const unit = UNITS[i];
        if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
            return unit;
        }
    }
    return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
}
 function determineMajorUnit(unit) {
    for(let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i){
        if (INTERVALS[UNITS[i]].common) {
            return UNITS[i];
        }
    }
}
 function addTick(ticks, time, timestamps) {
    if (!timestamps) {
        ticks[time] = true;
    } else if (timestamps.length) {
        const { lo , hi  } = _lookup(timestamps, time);
        const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];
        ticks[timestamp] = true;
    }
}
 function setMajorTicks(scale, ticks, map, majorUnit) {
    const adapter = scale._adapter;
    const first = +adapter.startOf(ticks[0].value, majorUnit);
    const last = ticks[ticks.length - 1].value;
    let major, index;
    for(major = first; major <= last; major = +adapter.add(major, 1, majorUnit)){
        index = map[major];
        if (index >= 0) {
            ticks[index].major = true;
        }
    }
    return ticks;
}
 function ticksFromTimestamps(scale, values, majorUnit) {
    const ticks = [];
     const map = {};
    const ilen = values.length;
    let i, value;
    for(i = 0; i < ilen; ++i){
        value = values[i];
        map[value] = i;
        ticks.push({
            value,
            major: false
        });
    }
    return ilen === 0 || !majorUnit ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
}
class TimeScale extends Scale {
    static id = 'time';
 static defaults = {
 bounds: 'data',
        adapters: {},
        time: {
            parser: false,
            unit: false,
            round: false,
            isoWeekday: false,
            minUnit: 'millisecond',
            displayFormats: {}
        },
        ticks: {
 source: 'auto',
            callback: false,
            major: {
                enabled: false
            }
        }
    };
 constructor(props){
        super(props);
         this._cache = {
            data: [],
            labels: [],
            all: []
        };
         this._unit = 'day';
         this._majorUnit = undefined;
        this._offsets = {};
        this._normalized = false;
        this._parseOpts = undefined;
    }
    init(scaleOpts, opts = {}) {
        const time = scaleOpts.time || (scaleOpts.time = {});
         const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);
        adapter.init(opts);
        mergeIf(time.displayFormats, adapter.formats());
        this._parseOpts = {
            parser: time.parser,
            round: time.round,
            isoWeekday: time.isoWeekday
        };
        super.init(scaleOpts);
        this._normalized = opts.normalized;
    }
 parse(raw, index) {
        if (raw === undefined) {
            return null;
        }
        return parse(this, raw);
    }
    beforeLayout() {
        super.beforeLayout();
        this._cache = {
            data: [],
            labels: [],
            all: []
        };
    }
    determineDataLimits() {
        const options = this.options;
        const adapter = this._adapter;
        const unit = options.time.unit || 'day';
        let { min , max , minDefined , maxDefined  } = this.getUserBounds();
 function _applyBounds(bounds) {
            if (!minDefined && !isNaN(bounds.min)) {
                min = Math.min(min, bounds.min);
            }
            if (!maxDefined && !isNaN(bounds.max)) {
                max = Math.max(max, bounds.max);
            }
        }
        if (!minDefined || !maxDefined) {
            _applyBounds(this._getLabelBounds());
            if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {
                _applyBounds(this.getMinMax(false));
            }
        }
        min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);
        max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;
        this.min = Math.min(min, max - 1);
        this.max = Math.max(min + 1, max);
    }
 _getLabelBounds() {
        const arr = this.getLabelTimestamps();
        let min = Number.POSITIVE_INFINITY;
        let max = Number.NEGATIVE_INFINITY;
        if (arr.length) {
            min = arr[0];
            max = arr[arr.length - 1];
        }
        return {
            min,
            max
        };
    }
 buildTicks() {
        const options = this.options;
        const timeOpts = options.time;
        const tickOpts = options.ticks;
        const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate();
        if (options.bounds === 'ticks' && timestamps.length) {
            this.min = this._userMin || timestamps[0];
            this.max = this._userMax || timestamps[timestamps.length - 1];
        }
        const min = this.min;
        const max = this.max;
        const ticks = _filterBetween(timestamps, min, max);
        this._unit = timeOpts.unit || (tickOpts.autoSkip ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min)) : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max));
        this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined : determineMajorUnit(this._unit);
        this.initOffsets(timestamps);
        if (options.reverse) {
            ticks.reverse();
        }
        return ticksFromTimestamps(this, ticks, this._majorUnit);
    }
    afterAutoSkip() {
        if (this.options.offsetAfterAutoskip) {
            this.initOffsets(this.ticks.map((tick)=>+tick.value));
        }
    }
 initOffsets(timestamps = []) {
        let start = 0;
        let end = 0;
        let first, last;
        if (this.options.offset && timestamps.length) {
            first = this.getDecimalForValue(timestamps[0]);
            if (timestamps.length === 1) {
                start = 1 - first;
            } else {
                start = (this.getDecimalForValue(timestamps[1]) - first) / 2;
            }
            last = this.getDecimalForValue(timestamps[timestamps.length - 1]);
            if (timestamps.length === 1) {
                end = last;
            } else {
                end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;
            }
        }
        const limit = timestamps.length < 3 ? 0.5 : 0.25;
        start = _limitValue(start, 0, limit);
        end = _limitValue(end, 0, limit);
        this._offsets = {
            start,
            end,
            factor: 1 / (start + 1 + end)
        };
    }
 _generate() {
        const adapter = this._adapter;
        const min = this.min;
        const max = this.max;
        const options = this.options;
        const timeOpts = options.time;
        const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min));
        const stepSize = valueOrDefault(options.ticks.stepSize, 1);
        const weekday = minor === 'week' ? timeOpts.isoWeekday : false;
        const hasWeekday = isNumber(weekday) || weekday === true;
        const ticks = {};
        let first = min;
        let time, count;
        if (hasWeekday) {
            first = +adapter.startOf(first, 'isoWeek', weekday);
        }
        first = +adapter.startOf(first, hasWeekday ? 'day' : minor);
        if (adapter.diff(max, min, minor) > 100000 * stepSize) {
            throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);
        }
        const timestamps = options.ticks.source === 'data' && this.getDataTimestamps();
        for(time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++){
            addTick(ticks, time, timestamps);
        }
        if (time === max || options.bounds === 'ticks' || count === 1) {
            addTick(ticks, time, timestamps);
        }
        return Object.keys(ticks).sort(sorter).map((x)=>+x);
    }
 getLabelForValue(value) {
        const adapter = this._adapter;
        const timeOpts = this.options.time;
        if (timeOpts.tooltipFormat) {
            return adapter.format(value, timeOpts.tooltipFormat);
        }
        return adapter.format(value, timeOpts.displayFormats.datetime);
    }
 format(value, format) {
        const options = this.options;
        const formats = options.time.displayFormats;
        const unit = this._unit;
        const fmt = format || formats[unit];
        return this._adapter.format(value, fmt);
    }
 _tickFormatFunction(time, index, ticks, format) {
        const options = this.options;
        const formatter = options.ticks.callback;
        if (formatter) {
            return callback(formatter, [
                time,
                index,
                ticks
            ], this);
        }
        const formats = options.time.displayFormats;
        const unit = this._unit;
        const majorUnit = this._majorUnit;
        const minorFormat = unit && formats[unit];
        const majorFormat = majorUnit && formats[majorUnit];
        const tick = ticks[index];
        const major = majorUnit && majorFormat && tick && tick.major;
        return this._adapter.format(time, format || (major ? majorFormat : minorFormat));
    }
 generateTickLabels(ticks) {
        let i, ilen, tick;
        for(i = 0, ilen = ticks.length; i < ilen; ++i){
            tick = ticks[i];
            tick.label = this._tickFormatFunction(tick.value, i, ticks);
        }
    }
 getDecimalForValue(value) {
        return value === null ? NaN : (value - this.min) / (this.max - this.min);
    }
 getPixelForValue(value) {
        const offsets = this._offsets;
        const pos = this.getDecimalForValue(value);
        return this.getPixelForDecimal((offsets.start + pos) * offsets.factor);
    }
 getValueForPixel(pixel) {
        const offsets = this._offsets;
        const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
        return this.min + pos * (this.max - this.min);
    }
 _getLabelSize(label) {
        const ticksOpts = this.options.ticks;
        const tickLabelWidth = this.ctx.measureText(label).width;
        const angle = toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
        const cosRotation = Math.cos(angle);
        const sinRotation = Math.sin(angle);
        const tickFontSize = this._resolveTickFontOptions(0).size;
        return {
            w: tickLabelWidth * cosRotation + tickFontSize * sinRotation,
            h: tickLabelWidth * sinRotation + tickFontSize * cosRotation
        };
    }
 _getLabelCapacity(exampleTime) {
        const timeOpts = this.options.time;
        const displayFormats = timeOpts.displayFormats;
        const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
        const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [
            exampleTime
        ], this._majorUnit), format);
        const size = this._getLabelSize(exampleLabel);
        const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1;
        return capacity > 0 ? capacity : 1;
    }
 getDataTimestamps() {
        let timestamps = this._cache.data || [];
        let i, ilen;
        if (timestamps.length) {
            return timestamps;
        }
        const metas = this.getMatchingVisibleMetas();
        if (this._normalized && metas.length) {
            return this._cache.data = metas[0].controller.getAllParsedValues(this);
        }
        for(i = 0, ilen = metas.length; i < ilen; ++i){
            timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this));
        }
        return this._cache.data = this.normalize(timestamps);
    }
 getLabelTimestamps() {
        const timestamps = this._cache.labels || [];
        let i, ilen;
        if (timestamps.length) {
            return timestamps;
        }
        const labels = this.getLabels();
        for(i = 0, ilen = labels.length; i < ilen; ++i){
            timestamps.push(parse(this, labels[i]));
        }
        return this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps);
    }
 normalize(values) {
        return _arrayUnique(values.sort(sorter));
    }
}

function interpolate(table, val, reverse) {
    let lo = 0;
    let hi = table.length - 1;
    let prevSource, nextSource, prevTarget, nextTarget;
    if (reverse) {
        if (val >= table[lo].pos && val <= table[hi].pos) {
            ({ lo , hi  } = _lookupByKey(table, 'pos', val));
        }
        ({ pos: prevSource , time: prevTarget  } = table[lo]);
        ({ pos: nextSource , time: nextTarget  } = table[hi]);
    } else {
        if (val >= table[lo].time && val <= table[hi].time) {
            ({ lo , hi  } = _lookupByKey(table, 'time', val));
        }
        ({ time: prevSource , pos: prevTarget  } = table[lo]);
        ({ time: nextSource , pos: nextTarget  } = table[hi]);
    }
    const span = nextSource - prevSource;
    return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
}
class TimeSeriesScale extends TimeScale {
    static id = 'timeseries';
 static defaults = TimeScale.defaults;
 constructor(props){
        super(props);
         this._table = [];
         this._minPos = undefined;
         this._tableRange = undefined;
    }
 initOffsets() {
        const timestamps = this._getTimestampsForTable();
        const table = this._table = this.buildLookupTable(timestamps);
        this._minPos = interpolate(table, this.min);
        this._tableRange = interpolate(table, this.max) - this._minPos;
        super.initOffsets(timestamps);
    }
 buildLookupTable(timestamps) {
        const { min , max  } = this;
        const items = [];
        const table = [];
        let i, ilen, prev, curr, next;
        for(i = 0, ilen = timestamps.length; i < ilen; ++i){
            curr = timestamps[i];
            if (curr >= min && curr <= max) {
                items.push(curr);
            }
        }
        if (items.length < 2) {
            return [
                {
                    time: min,
                    pos: 0
                },
                {
                    time: max,
                    pos: 1
                }
            ];
        }
        for(i = 0, ilen = items.length; i < ilen; ++i){
            next = items[i + 1];
            prev = items[i - 1];
            curr = items[i];
            if (Math.round((next + prev) / 2) !== curr) {
                table.push({
                    time: curr,
                    pos: i / (ilen - 1)
                });
            }
        }
        return table;
    }
 _generate() {
        const min = this.min;
        const max = this.max;
        let timestamps = super.getDataTimestamps();
        if (!timestamps.includes(min) || !timestamps.length) {
            timestamps.splice(0, 0, min);
        }
        if (!timestamps.includes(max) || timestamps.length === 1) {
            timestamps.push(max);
        }
        return timestamps.sort((a, b)=>a - b);
    }
 _getTimestampsForTable() {
        let timestamps = this._cache.all || [];
        if (timestamps.length) {
            return timestamps;
        }
        const data = this.getDataTimestamps();
        const label = this.getLabelTimestamps();
        if (data.length && label.length) {
            timestamps = this.normalize(data.concat(label));
        } else {
            timestamps = data.length ? data : label;
        }
        timestamps = this._cache.all = timestamps;
        return timestamps;
    }
 getDecimalForValue(value) {
        return (interpolate(this._table, value) - this._minPos) / this._tableRange;
    }
 getValueForPixel(pixel) {
        const offsets = this._offsets;
        const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
        return interpolate(this._table, decimal * this._tableRange + this._minPos, true);
    }
}

var scales = /*#__PURE__*/Object.freeze({
__proto__: null,
CategoryScale: CategoryScale,
LinearScale: LinearScale,
LogarithmicScale: LogarithmicScale,
RadialLinearScale: RadialLinearScale,
TimeScale: TimeScale,
TimeSeriesScale: TimeSeriesScale
});

const registerables = [
    controllers,
    elements,
    plugins,
    scales
];

const CommonProps = {
    data: {
        type: Object,
        required: true
    },
    options: {
        type: Object,
        default: ()=>({})
    },
    plugins: {
        type: Array,
        default: ()=>[]
    },
    datasetIdKey: {
        type: String,
        default: "label"
    },
    updateMode: {
        type: String,
        default: undefined
    }
};
const A11yProps = {
    ariaLabel: {
        type: String
    },
    ariaDescribedby: {
        type: String
    }
};
const Props = {
    type: {
        type: String,
        required: true
    },
    destroyDelay: {
        type: Number,
        default: 0 // No delay by default
    },
    ...CommonProps,
    ...A11yProps
};

const compatProps = version$2[0] === "2" ? (internals, props)=>Object.assign(internals, {
        attrs: props
    }) : (internals, props)=>Object.assign(internals, props);
function toRawIfProxy(obj) {
    return isProxy(obj) ? toRaw(obj) : obj;
}
function cloneProxy(obj) {
    let src = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : obj;
    return isProxy(src) ? new Proxy(obj, {}) : obj;
}
function setOptions(chart, nextOptions) {
    const options = chart.options;
    if (options && nextOptions) {
        Object.assign(options, nextOptions);
    }
}
function setLabels(currentData, nextLabels) {
    currentData.labels = nextLabels;
}
function setDatasets(currentData, nextDatasets, datasetIdKey) {
    const addedDatasets = [];
    currentData.datasets = nextDatasets.map((nextDataset)=>{
        // given the new set, find it's current match
        const currentDataset = currentData.datasets.find((dataset)=>dataset[datasetIdKey] === nextDataset[datasetIdKey]);
        // There is no original to update, so simply add new one
        if (!currentDataset || !nextDataset.data || addedDatasets.includes(currentDataset)) {
            return {
                ...nextDataset
            };
        }
        addedDatasets.push(currentDataset);
        Object.assign(currentDataset, nextDataset);
        return currentDataset;
    });
}
function cloneData(data, datasetIdKey) {
    const nextData = {
        labels: [],
        datasets: []
    };
    setLabels(nextData, data.labels);
    setDatasets(nextData, data.datasets, datasetIdKey);
    return nextData;
}
/**
 * Get dataset from mouse click event
 * @param chart - Chart.js instance
 * @param event - Mouse click event
 * @returns Dataset
 */ function getDatasetAtEvent(chart, event) {
    return chart.getElementsAtEventForMode(event, "dataset", {
        intersect: true
    }, false);
}
/**
 * Get single dataset element from mouse click event
 * @param chart - Chart.js instance
 * @param event - Mouse click event
 * @returns Dataset
 */ function getElementAtEvent(chart, event) {
    return chart.getElementsAtEventForMode(event, "nearest", {
        intersect: true
    }, false);
}
/**
 * Get all dataset elements from mouse click event
 * @param chart - Chart.js instance
 * @param event - Mouse click event
 * @returns Dataset
 */ function getElementsAtEvent(chart, event) {
    return chart.getElementsAtEventForMode(event, "index", {
        intersect: true
    }, false);
}

const Chart = defineComponent({
    props: Props,
    setup (props, param) {
        let { expose , slots  } = param;
        const canvasRef = ref(null);
        const chartRef = shallowRef(null);
        expose({
            chart: chartRef
        });
        const renderChart = ()=>{
            if (!canvasRef.value) return;
            const { type , data , options , plugins , datasetIdKey  } = props;
            const clonedData = cloneData(data, datasetIdKey);
            const proxiedData = cloneProxy(clonedData, data);
            chartRef.value = new Chart$1(canvasRef.value, {
                type,
                data: proxiedData,
                options: {
                    ...options
                },
                plugins
            });
        };
        const destroyChart = ()=>{
            const chart = toRaw(chartRef.value);
            if (chart) {
                if (props.destroyDelay > 0) {
                    setTimeout(()=>{
                        chart.destroy();
                        chartRef.value = null;
                    }, props.destroyDelay);
                } else {
                    chart.destroy();
                    chartRef.value = null;
                }
            }
        };
        const update = (chart)=>{
            chart.update(props.updateMode);
        };
        onMounted(renderChart);
        onUnmounted(destroyChart);
        watch([
            ()=>props.options,
            ()=>props.data
        ], (param, param1)=>{
            let [nextOptionsProxy, nextDataProxy] = param, [prevOptionsProxy, prevDataProxy] = param1;
            const chart = toRaw(chartRef.value);
            if (!chart) {
                return;
            }
            let shouldUpdate = false;
            if (nextOptionsProxy) {
                const nextOptions = toRawIfProxy(nextOptionsProxy);
                const prevOptions = toRawIfProxy(prevOptionsProxy);
                if (nextOptions && nextOptions !== prevOptions) {
                    setOptions(chart, nextOptions);
                    shouldUpdate = true;
                }
            }
            if (nextDataProxy) {
                const nextLabels = toRawIfProxy(nextDataProxy.labels);
                const prevLabels = toRawIfProxy(prevDataProxy.labels);
                const nextDatasets = toRawIfProxy(nextDataProxy.datasets);
                const prevDatasets = toRawIfProxy(prevDataProxy.datasets);
                if (nextLabels !== prevLabels) {
                    setLabels(chart.config.data, nextLabels);
                    shouldUpdate = true;
                }
                if (nextDatasets && nextDatasets !== prevDatasets) {
                    setDatasets(chart.config.data, nextDatasets, props.datasetIdKey);
                    shouldUpdate = true;
                }
            }
            if (shouldUpdate) {
                nextTick(()=>{
                    update(chart);
                });
            }
        }, {
            deep: true
        });
        return ()=>{
            return h("canvas", {
                role: "img",
                "aria-label": props.ariaLabel,
                "aria-describedby": props.ariaDescribedby,
                ref: canvasRef
            }, [
                h("p", {}, [
                    slots.default ? slots.default() : ""
                ])
            ]);
        };
    }
});

function createTypedChart(type, registerables) {
    Chart$1.register(registerables);
    return defineComponent({
        props: CommonProps,
        setup (props, param) {
            let { expose  } = param;
            const ref = shallowRef(null);
            const reforwardRef = (chartRef)=>{
                ref.value = chartRef?.chart;
            };
            expose({
                chart: ref
            });
            return ()=>{
                return h(Chart, compatProps({
                    ref: reforwardRef
                }, {
                    type,
                    ...props
                }));
            };
        }
    });
}
const Bar = /* #__PURE__ */ createTypedChart("bar", BarController);
const Doughnut = /* #__PURE__ */ createTypedChart("doughnut", DoughnutController);
const Line = /* #__PURE__ */ createTypedChart("line", LineController);
const Pie = /* #__PURE__ */ createTypedChart("pie", PieController);
const PolarArea = /* #__PURE__ */ createTypedChart("polarArea", PolarAreaController);
const Radar = /* #__PURE__ */ createTypedChart("radar", RadarController);
const Bubble = /* #__PURE__ */ createTypedChart("bubble", BubbleController);
const Scatter = /* #__PURE__ */ createTypedChart("scatter", ScatterController);

const _sfc_main$1r = {
  __name: 'SmallCustomerActivityChart',
  props: {
  transactions: {
    type: Array,
    required: true
  },
  dates: {
    type: Object,
    required: true,
    default: () => ({
      dateFrom: new Date(new Date().setHours(0, 0, 0, 0)), // Start of the day (Today at 00:00:00)
      dateTo: new Date(new Date().setHours(23, 59, 59, 999)), // End of the day (Today at 23:59:59)
    })
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;
Chart$1.register(plugin_title, plugin_tooltip, plugin_legend, CategoryScale, LinearScale, BarElement, PointElement, LineElement, plugin_colors);

const parseTransactions = () => {
  console.log('Parsing transactions for chart data...', props.transactions.length, 'transactions found.');
  const labels = [];
  const data = [];
  props.transactions.forEach(transaction => {
    const formattedDate = transaction.date.split(' ')[0]; // Format date to YYYY-MM-DD
    if (!labels.includes(formattedDate)) {
      labels.push(formattedDate);
      data.push(0); // Initialize with 0 for the new date
    }
    const index = labels.indexOf(formattedDate);
    data[index] += transaction.amount; // Assuming transaction has an 'amount' field
  });
  // Sort the labels and data arrays based on the labels
  const sortedIndices = labels.map((label, index) => index).sort((a, b) => new Date(labels[a]) - new Date(labels[b]));
  labels.sort((a, b) => new Date(a) - new Date(b));
  data.sort((a, b) => new Date(labels[sortedIndices[data.indexOf(a)]]) - new Date(labels[sortedIndices[data.indexOf(b)]]));
  // Update the parsedList with the sorted labels and data
  parsedList.value.labels = labels;
  parsedList.value.datasets[0].data = data;
};

/** Define the data */
const options = {
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    y: {
      beginAtZero: true
    }
  }
};
const parsedList = ref({
  labels: [],
  datasets: [
    {
      label: 'Omsætning',
      backgroundColor: '#f87979',
      data: []
    }
  ]
});

// Function to parse purchases and update the chart data
watch(() => props.transactions, (newTransactions) => {
  if (newTransactions && newTransactions.length > 0) {
    parseTransactions();
  }
}, { immediate: true });
// Initial call to parse transactions
parseTransactions();

const __returned__ = { props, parseTransactions, options, parsedList, ref, watch, SessionUser, TemplateColors: Colors, get ChartJS() { return Chart$1 }, get Title() { return plugin_title }, get Tooltip() { return plugin_tooltip }, get Legend() { return plugin_legend }, get BarElement() { return BarElement }, get CategoryScale() { return CategoryScale }, get LinearScale() { return LinearScale }, get Colors() { return plugin_colors }, get PointElement() { return PointElement }, get LineElement() { return LineElement }, get Bar() { return Bar }, get Line() { return Line } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$L = { class: "w-full h-96" };

function _sfc_render$S(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$L, [
    createVNode($setup["Line"], {
      data: $setup.parsedList,
      options: $setup.options
    }, null, 8 /* PROPS */, ["data"])
  ]))
}
const SmallCustomerActivityChart = /*#__PURE__*/_export_sfc(_sfc_main$1r, [['render',_sfc_render$S],['__file',"SmallCustomerActivityChart.vue"]]);

const _sfc_main$1q = {
  __name: 'StatisticsIncomeCard',
  props: {
  name: {
    type: String,
    required: true
  },
  icon: {
    type: String,
    required: true
  },
  color: {
    type: String,
    default: 'black',
    enum: ['black', 'info', 'success', 'warning', 'danger'],
  },
  fontStyle: {
    type: String,
    default: 'normal',
    enum: ['normal', 'italic', 'oblique', 'strikethrough'],
  },
  endpoint: {
    type: String,
    required: false,
  },
  forceDisplay: {
    type: Object,
    default: () => ({
      start_date: null,
      end_date: null,
      value: null,
      error: null,
      card_class: 'card',
    })
  },
  loading: {
    type: Boolean,
    default: false
  }
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;
//const props = defineProps(['name', 'icon', 'color', 'endpoint']);

const value = ref(null);
const start_date = ref(null);
const end_date = ref(null);
const error = ref(null);

const getDaysBetweenDates = (startDate, endDate) => {
  const start = new Date(startDate);
  const end = new Date(endDate);
  const diffTime = Math.abs(end - start);
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
};

const fetchValue = async (endpoint) => {
  const response = await authenticatedRequest(endpoint).catch((error) => {
    console.error(error);
    error.value = error;
  });
  // Check if the data structure is correct
  try {
    if (parseInt(response.data.data.total) === undefined || !response.data.data.start || !response.data.data.end) {
      throw new Error('Data structure is incorrect')
    }
  } catch (e) {
    console.error(e);
    error.value = e;
    return
  }
  console.log(response.data.data);
  value.value = response.data.data.total;
  start_date.value = response.data.data.start;
  end_date.value = response.data.data.end;
  return response.data
};

const renderCurrency = (value) => {
  return new Intl.NumberFormat('da-DK', { style: 'currency', currency: 'DKK' }).format(value)
};

onMounted(() => {
  if (props.loading) {
    return
  }
  if (props.forceDisplay && props.forceDisplay.value !== null) {
    value.value = props.forceDisplay.value;
    start_date.value = props.forceDisplay.start_date;
    end_date.value = props.forceDisplay.end_date;
    error.value = props.forceDisplay.error || null;
    return
  }
  fetchValue(props.endpoint);
});

watch(() => props.forceDisplay, (newValue) => {
  if (newValue && newValue.value !== null) {
    value.value = newValue.value;
    start_date.value = newValue.start_date;
    end_date.value = newValue.end_date;
    error.value = newValue.error || null;
  }
}, { immediate: true });

const fontStyleClass = computed(() => {
  switch (props.fontStyle.toLowerCase()) {
    case 'italic':
      return 'is-italic'
    case 'oblique':
      return 'is-oblique'
    case 'strikethrough':
      return 'has-text-decoration-line-through'
    default:
      return ''
  }
});

const cardClass = ref(props.forceDisplay.card_class || 'card');
// Color class nuances (title, subtitle, icon)
const colorClassNuances = computed(() => {
  return {
    title: [`has-text-${props.color}`, 'is-size-5', 'has-text-weight-bold'],
    subtitle: [`has-text-${props.color}-light`, 'is-size-6', 'has-text-weight-semibold', fontStyleClass.value],
    icon: [`has-text-${props.color}`, 'is-size-4'],
    footer: [`has-text-${props.color}`, 'is-size-7', 'has-text-weight-semibold'],
    footerIcon: [`has-text-${props.color}`, 'is-size-7'],
  }
});

const __returned__ = { props, value, start_date, end_date, error, getDaysBetweenDates, fetchValue, renderCurrency, fontStyleClass, cardClass, colorClassNuances, computed, onMounted, watch, ref, authenticatedRequest };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$K = { class: "card-content" };
const _hoisted_2$B = { class: "media" };
const _hoisted_3$x = { class: "media-left" };
const _hoisted_4$x = { class: "image is-48x48" };
const _hoisted_5$w = {
  key: 1,
  class: "fas fa-exclamation-triangle has-text-warning"
};
const _hoisted_6$v = {
  key: 2,
  class: "fas fa-spinner fa-spin"
};
const _hoisted_7$t = { class: "media-content" };
const _hoisted_8$t = { class: "card-footer" };
const _hoisted_9$r = { class: "card-footer-item" };
const _hoisted_10$q = {
  key: 0,
  class: "icon"
};
const _hoisted_11$m = { key: 2 };
const _hoisted_12$l = { class: "icon" };
const _hoisted_13$j = { key: 3 };
const _hoisted_14$h = { class: "icon" };

function _sfc_render$R(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", {
    class: normalizeClass($setup.cardClass)
  }, [
    createBaseVNode("div", _hoisted_1$K, [
      createBaseVNode("div", _hoisted_2$B, [
        createBaseVNode("div", _hoisted_3$x, [
          createBaseVNode("figure", _hoisted_4$x, [
            ($setup.value !== null && !$setup.props.loading)
              ? (openBlock(), createElementBlock("i", {
                  key: 0,
                  class: normalizeClass([$props.icon, $setup.colorClassNuances.icon])
                }, null, 2 /* CLASS */))
              : ($setup.error)
                ? (openBlock(), createElementBlock("i", _hoisted_5$w))
                : (openBlock(), createElementBlock("i", _hoisted_6$v))
          ])
        ]),
        createBaseVNode("div", _hoisted_7$t, [
          createBaseVNode("p", {
            class: normalizeClass(["title is-5", $setup.colorClassNuances.title])
          }, toDisplayString($props.name), 3 /* TEXT, CLASS */),
          ($setup.value !== null && !$setup.props.loading)
            ? (openBlock(), createElementBlock("p", {
                key: 0,
                class: normalizeClass(["subtitle is-6", $setup.colorClassNuances.subtitle])
              }, toDisplayString($setup.renderCurrency($setup.value)), 3 /* TEXT, CLASS */))
            : ($setup.error)
              ? (openBlock(), createElementBlock("p", {
                  key: 1,
                  class: normalizeClass(["subtitle is-6", $setup.colorClassNuances.subtitle])
                }, toDisplayString($setup.error), 3 /* TEXT, CLASS */))
              : (openBlock(), createElementBlock("p", {
                  key: 2,
                  class: normalizeClass(["subtitle is-6", $setup.colorClassNuances.subtitle])
                }, toDisplayString(_ctx.$t('common.loading')), 3 /* TEXT, CLASS */))
        ])
      ])
    ]),
    createBaseVNode("footer", _hoisted_8$t, [
      createBaseVNode("p", _hoisted_9$r, [
        createBaseVNode("span", null, [
          ($setup.start_date && $setup.end_date)
            ? (openBlock(), createElementBlock("span", _hoisted_10$q, [
                createBaseVNode("i", {
                  class: normalizeClass(["fas fa-calendar-day", $setup.colorClassNuances.footerIcon])
                }, null, 2 /* CLASS */)
              ]))
            : createCommentVNode("v-if", true),
          ($setup.start_date && $setup.end_date)
            ? (openBlock(), createElementBlock("span", {
                key: 1,
                class: normalizeClass($setup.colorClassNuances.footer)
              }, toDisplayString($setup.start_date) + " - " + toDisplayString($setup.end_date) + " (" + toDisplayString($setup.getDaysBetweenDates($setup.start_date, $setup.end_date) === 0 ? '1 ' + _ctx.$t('statistics.day') : $setup.getDaysBetweenDates($setup.start_date, $setup.end_date) + ' ' + _ctx.$t('statistics.days')) + ") ", 3 /* TEXT, CLASS */))
            : ($setup.error)
              ? (openBlock(), createElementBlock("span", _hoisted_11$m, [
                  createBaseVNode("span", _hoisted_12$l, [
                    createBaseVNode("i", {
                      class: normalizeClass(["fas fa-exclamation-triangle has-text-warning", $setup.colorClassNuances.footerIcon])
                    }, null, 2 /* CLASS */)
                  ]),
                  createBaseVNode("span", null, toDisplayString(_ctx.$t('common.error')), 1 /* TEXT */)
                ]))
              : (openBlock(), createElementBlock("span", _hoisted_13$j, [
                  createBaseVNode("span", _hoisted_14$h, [
                    createBaseVNode("i", {
                      class: normalizeClass(["fas fa-spinner fa-spin", $setup.colorClassNuances.footerIcon])
                    }, null, 2 /* CLASS */)
                  ]),
                  createBaseVNode("span", null, toDisplayString(_ctx.$t('common.loading')), 1 /* TEXT */)
                ]))
        ])
      ])
    ])
  ], 2 /* CLASS */))
}
const StatisticsIncomeCard = /*#__PURE__*/_export_sfc(_sfc_main$1q, [['render',_sfc_render$R],['__scopeId',"data-v-f51d6c69"],['__file',"StatisticsIncomeCard.vue"]]);

const _sfc_main$1p = /* @__PURE__ */ defineComponent({
  __name: "WhiteBoxCard",
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    toggleable: {
      type: Boolean,
      default: false
    },
    defaultOpen: {
      type: Boolean,
      default: false
    },
    hideHeader: {
      type: Boolean,
      default: false
    },
    forceState: {
      type: Boolean,
      default: null
    },
    forceStateFooter: {
      type: Boolean,
      default: false
    },
    footerTestId: {
      type: String,
      default: ""
    },
    hasSelectedStyle: {
      type: Boolean,
      default: false
    },
    hasSelectionStyle: {
      type: Boolean,
      default: false
    },
    hasHoverEffect: {
      type: Boolean,
      default: false
    },
    isPlaceholder: {
      type: Boolean,
      default: false
    },
    hasBorder: {
      type: Boolean,
      default: false
    },
    headerTestId: {
      type: String,
      default: ""
    }
  },
  emits: ["toggle"],
  setup(__props, { expose: __expose, emit: __emit }) {
    __expose();
    const props = __props;
    const emit = __emit;
    const isOpen = ref(props.defaultOpen);
    onMounted(() => {
      if (props.toggleable) {
        isOpen.value = props.defaultOpen;
      }
    });
    const toggle = () => {
      if (!props.toggleable) return;
      isOpen.value = !isOpen.value;
      emit("toggle", isOpen.value);
    };
    watch(() => props.forceState, (newVal) => {
      if (newVal !== null) {
        isOpen.value = newVal;
      }
    });
    const __returned__ = { props, emit, isOpen, toggle, WhiteBox };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$J = { class: "card is-radiusless" };
const _hoisted_2$A = {
  key: 0,
  class: "is-overlay"
};
const _hoisted_3$w = ["data-testid"];
const _hoisted_4$w = {
  key: 2,
  class: "card-content"
};
const _hoisted_5$v = ["data-testid"];
function _sfc_render$Q(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createBlock($setup["WhiteBox"], {
    class: normalizeClass(["p-0", { "is-white-box-loading": $setup.props.loading, "is-selected": $setup.props.hasSelectedStyle, "is-selection-style": $setup.props.hasSelectionStyle, "has-custom-hover-effect": $setup.props.hasHoverEffect, "is-placeholder": $setup.props.isPlaceholder, "has-custom-border": $setup.props.hasBorder }])
  }, {
    default: withCtx(() => [
      createBaseVNode("div", _hoisted_1$J, [
        $setup.props.loading ? (openBlock(), createElementBlock("div", _hoisted_2$A, [
          createCommentVNode(" Loading spinner "),
          _cache[0] || (_cache[0] = createBaseVNode(
            "div",
            { class: "loading-spinner is-flex is-justify-content-center is-align-items-center is-hcentered" },
            [
              createBaseVNode("span", { class: "icon is-large" }, [
                createBaseVNode("i", { class: "fas fa-spinner fa-spin" })
              ])
            ],
            -1
            /* CACHED */
          ))
        ])) : createCommentVNode("v-if", true),
        createCommentVNode(" Default slot for header "),
        _ctx.$slots.header && !$setup.props.hideHeader ? (openBlock(), createElementBlock("div", {
          key: 1,
          class: normalizeClass(["card-header is-radiusless", { "is-clickable": $setup.props.toggleable }]),
          onClick: $setup.toggle,
          "data-testid": $setup.props.headerTestId || void 0
        }, [
          renderSlot(_ctx.$slots, "header", {}, void 0, true)
        ], 10, _hoisted_3$w)) : createCommentVNode("v-if", true),
        createCommentVNode(" Default slot for any content "),
        renderSlot(_ctx.$slots, "default", {}, void 0, true),
        createCommentVNode(" Slot for content "),
        $setup.isOpen ? (openBlock(), createElementBlock("div", _hoisted_4$w, [
          renderSlot(_ctx.$slots, "content", {}, void 0, true)
        ])) : createCommentVNode("v-if", true),
        createCommentVNode(" Slot for footer "),
        ($setup.isOpen || $setup.props.forceStateFooter) && _ctx.$slots.footer ? (openBlock(), createElementBlock("div", {
          key: 3,
          class: "card-footer",
          "data-testid": $setup.props.footerTestId || void 0
        }, [
          renderSlot(_ctx.$slots, "footer", {}, void 0, true)
        ], 8, _hoisted_5$v)) : createCommentVNode("v-if", true)
      ])
    ]),
    _: 3
    /* FORWARDED */
  }, 8, ["class"]);
}
const WhiteBoxCard = /* @__PURE__ */ _export_sfc(_sfc_main$1p, [["render", _sfc_render$Q], ["__scopeId", "data-v-7b645a96"], ["__file", "WhiteBoxCard.vue"]]);

// Define the departments
const departments = ref([]);
const isLoading = ref(true);
const timeBookingDepartments = ref([]);
const timeBookingDepartmentsIsLoading = ref(false);

// Get the departments from the API
const getDepartments = async () => {
  isLoading.value = true;
  const request = await authenticatedRequest("/departments", "get");
  departments.value = sortByDepartmentPriorityOrder(request.data.data || []);
  isLoading.value = false;
};

// Check if a department exists by ID
const departmentExists = (id) => {
  return departments.value.find((department) => department.id === id) !== undefined;
};

// Get the department name by ID
const getDepartmentName = (id) => {
  // Check if the departments have been loaded
  if (departments.value.length === 0) {
    // Return the id if the departments have not been loaded (This will be replaced by the department name when the departments are loaded)
    return id;
  }
  const department = departments.value.find((department) => department.id === id);
  // Check if the department exists in the departments array
  if (department === undefined) {
    return "";
  }
  // Return the department name
  return department.name;
};

// Get the department description by ID
const getDepartmentDescription = (id) => {
  if (departments.value.length === 0) {
    return "";
  }

  const department = departments.value.find((department) => department.id === id);
  return department ? department.description : "";
};

const getDepartmentsGuest = async (queryParams = {}) => {
  isLoading.value = true;
  try {
    const queryString = new URLSearchParams(queryParams).toString();
    const request = await unauthenticatedRequest$1("/guest/departments" + (queryString ? `?${queryString}` : ""), "get");
    departments.value = sortByDepartmentPriorityOrder(request.data.data || []);
    return departments.value;
  } finally {
    isLoading.value = false;
  }
};

const getTimeBookingDepartments = async (queryParams = {}) => {
  timeBookingDepartmentsIsLoading.value = true;
  try {
    const queryString = new URLSearchParams(queryParams).toString();
    const request = await unauthenticatedRequest$1(
      "/department/timebookings/departments/public" + (queryString ? `?${queryString}` : ""),
      "get"
    );
    timeBookingDepartments.value = sortByDepartmentPriorityOrder(request.data.data || []);
    return timeBookingDepartments.value;
  } finally {
    timeBookingDepartmentsIsLoading.value = false;
  }
};

const _sfc_main$1o = {};
const departmentTabs = /*#__PURE__*/_export_sfc(_sfc_main$1o, [['__file',"departmentTabs.vue"]]);

const AUTO_EXPORT_TABLE_ATTR = 'data-auto-excel-export-attached';
const AUTO_EXPORT_BUTTON_ATTR = 'data-auto-excel-export-button';

const isElementVisible = (element) => {
  if (!element) {
    return false;
  }

  if (element.hidden) {
    return false;
  }

  if (typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') {
    return true;
  }

  const style = window.getComputedStyle(element);
  return style.display !== 'none' && style.visibility !== 'hidden';
};

const extractVisibleRowsFromTable = (tableElement) => {
  if (!tableElement) {
    return [];
  }

  const headerCells = [...tableElement.querySelectorAll('thead th')];
  const headerLabels = headerCells.map((headerCell, index) => {
    const label = String(headerCell.textContent || '').trim();
    return label || `Column ${index + 1}`;
  });

  const bodyRows = tableElement.querySelectorAll('tbody tr');
  const fallbackRows = tableElement.querySelectorAll('tr');
  const rows = (bodyRows.length ? [...bodyRows] : [...fallbackRows])
    .filter((row) => isElementVisible(row));

  return rows
    .map((row) => {
      const cells = [...row.querySelectorAll('th, td')];
      if (!cells.length) {
        return null;
      }

      const rowObject = {};
      cells.forEach((cell, index) => {
        const key = headerLabels[index] || `Column ${index + 1}`;
        rowObject[key] = String(cell.textContent || '').trim();
      });
      return rowObject;
    })
    .filter((row) => row && Object.keys(row).length > 0);
};

const buildDomExportFilename = (tableElement, tableIndex) => {
  const currentPathname = typeof window !== 'undefined' && window.location
    ? window.location.pathname
    : 'table';
  const pathSegment = String(currentPathname || 'table')
    .replace(/^\//, '')
    .replace(/[\\/]+/g, '-')
    .replace(/[^a-zA-Z0-9-_]+/g, '-')
    .toLowerCase() || 'table';
  const tableLabel = tableElement.getAttribute('data-export-name')
    || tableElement.id
    || `table-${tableIndex + 1}`;
  const safeLabel = String(tableLabel).replace(/[^a-zA-Z0-9-_]+/g, '-').toLowerCase();
  return `${pathSegment}-${safeLabel}-${new Date().toISOString().slice(0, 10)}.xlsx`;
};

const getScopedExportRoot = (tableElement) => {
  return tableElement.closest('[data-auto-excel-export-scope]') || tableElement.parentElement || document;
};

const findInlineTarget = (tableElement) => {
  const scopedRoot = getScopedExportRoot(tableElement);
  const explicitTarget = tableElement.getAttribute('data-auto-excel-export-target');

  if (explicitTarget) {
    return scopedRoot.querySelector(`[data-auto-excel-export-actions="${explicitTarget}"]`);
  }

  return tableElement.parentElement?.querySelector('[data-auto-excel-export-actions="1"]') || null;
};

const createAutoExportButton = (tableElement, tableIndex, options = {}) => {
  const inline = options.inline === true;
  const wrapper = document.createElement('div');
  wrapper.className = inline ? 'auto-excel-export-inline' : 'mb-2 has-text-right';
  wrapper.setAttribute(AUTO_EXPORT_BUTTON_ATTR, '1');

  const button = document.createElement('button');
  button.type = 'button';
  button.className = 'button is-dark is-small';
  button.textContent = i18n.global.t('pagination.download_excel');
  button.addEventListener('click', () => {
    const rows = extractVisibleRowsFromTable(tableElement);
    exportRowsToExcel(rows, {
      filename: buildDomExportFilename(tableElement, tableIndex),
      sheetName: tableElement.getAttribute('data-export-sheet') || 'Table',
    });
  });

  wrapper.appendChild(button);
  return wrapper;
};

const ensureAutoTableExportButtons = (root = document) => {
  if (!root || typeof root.querySelectorAll !== 'function') {
    return;
  }

    const tables = [...root.querySelectorAll('table.table')].filter((table) => {
    if (table.closest('.b-table')) {
      return false;
    }
    if (table.closest('[data-disable-auto-excel-export="1"]')) {
      return false;
    }
    return true;
  });

  tables.forEach((tableElement, index) => {
    if (tableElement.hasAttribute(AUTO_EXPORT_TABLE_ATTR)) {
      return;
    }

    const inlineTarget = findInlineTarget(tableElement);
    const useInlineTarget = Boolean(inlineTarget);
    const button = createAutoExportButton(tableElement, index, { inline: useInlineTarget });

    if (useInlineTarget) {
      inlineTarget.appendChild(button);
    } else {
      tableElement.parentNode?.insertBefore(button, tableElement);
    }

    tableElement.setAttribute(AUTO_EXPORT_TABLE_ATTR, '1');
  });
};

const initializeAutoTableExports = () => {
  if (typeof window === 'undefined' || typeof document === 'undefined' || !document.body) {
    return () => {};
  }
  if (typeof MutationObserver === 'undefined') {
    ensureAutoTableExportButtons(document);
    return () => {};
  }

  let scheduled = false;
  const run = () => {
    scheduled = false;
    ensureAutoTableExportButtons(document);
  };
  const schedule = () => {
    if (scheduled) {
      return;
    }
    scheduled = true;
    window.requestAnimationFrame(run);
  };

  schedule();
  const observer = new MutationObserver(schedule);
  observer.observe(document.body, {
    childList: true,
    subtree: true,
  });

  window.addEventListener('load', schedule);
  window.addEventListener('popstate', schedule);
  window.addEventListener('hashchange', schedule);

  return () => {
    observer.disconnect();
    window.removeEventListener('load', schedule);
    window.removeEventListener('popstate', schedule);
    window.removeEventListener('hashchange', schedule);
  };
};

const toFiniteNumber$1 = (value) => {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : 0;
};

const isPlainObject$1 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);

const getMap = (value) => (isPlainObject$1(value) ? value : {});

const hasEntries = (value) => Object.keys(getMap(value)).length > 0;

const getCollectiveResults = (distribution = {}) => {
  return distribution?.collective_results || distribution?.includes?.collective_results || {};
};

const getBookedDepartment75Groups = (distribution = {}) => {
  const customers = Array.isArray(distribution?.customers)
    ? distribution.customers
    : (Array.isArray(distribution?.data) ? distribution.data : []);

  return customers.flatMap((customer = {}) => {
    const meta = customer?.meta?.booked_department_75 || customer?.booked_department_75 || {};
    return Array.isArray(meta?.booked_groups) ? meta.booked_groups : [];
  });
};

const matchesSourceCategory = (group = {}, sourceCategory = null) => {
  if (!sourceCategory) {
    return true;
  }

  return String(group?.source_category || "") === String(sourceCategory);
};

const getMapValue = (map, department = {}) => {
  const safeMap = getMap(map);
  const keys = [
    department?.id,
    department?.id !== undefined && department?.id !== null ? String(department.id) : null,
    department?.name,
  ].filter((key) => key !== null && key !== undefined && key !== "");

  for (const key of keys) {
    if (Object.prototype.hasOwnProperty.call(safeMap, key)) {
      return toFiniteNumber$1(safeMap[key]);
    }
  }

  return 0;
};

const getFirstMappedDepartmentAmount = (department, maps = []) => {
  for (const map of maps) {
    if (!hasEntries(map)) {
      continue;
    }

    const amount = getMapValue(map, department);
    if (amount !== 0) {
      return amount;
    }
  }

  return 0;
};

const sumMapValues = (map) => Object.values(getMap(map)).reduce((sum, value) => sum + toFiniteNumber$1(value), 0);

const getFixedPricingOriginalDepartmentAmount = (department, distribution = {}) => {
  return getFirstMappedDepartmentAmount(department, [
    distribution?.total_department_totals_parsed,
    distribution?.total_department_totals,
  ]);
};

const getFixedPricingActualDepartmentAmount = (department, distribution = {}) => {
  return getFirstMappedDepartmentAmount(department, [
    distribution?.total_department_totals_relative_parsed,
    distribution?.total_department_totals_relative,
  ]);
};

const getVehicleSubscriptionDepartmentAmount = (department, distribution = {}) => {
  return getFirstMappedDepartmentAmount(department, [
    distribution?.subscription_price_department_distribution_parsed,
    distribution?.subscription_price_department_distribution,
  ]);
};

const getDepartmentBasisMap = (distribution = {}) => {
  if (hasEntries(distribution?.subscription_price_department_distribution)) {
    return distribution.subscription_price_department_distribution;
  }

  if (hasEntries(distribution?.total_department_totals)) {
    return distribution.total_department_totals;
  }

  if (hasEntries(distribution?.subscription_price_department_distribution_parsed)) {
    return distribution.subscription_price_department_distribution_parsed;
  }

  if (hasEntries(distribution?.total_department_totals_parsed)) {
    return distribution.total_department_totals_parsed;
  }

  return {};
};

const getDepartmentBasisAmount = (department, distribution = {}) => {
  return getMapValue(getDepartmentBasisMap(distribution), department);
};

const getDistributionBasisTotal = (distribution = {}) => {
  const subscriptionTotal = toFiniteNumber$1(distribution?.total_subscription_price);
  if (
    subscriptionTotal > 0
    && (
      hasEntries(distribution?.subscription_price_department_distribution)
      || hasEntries(distribution?.subscription_price_department_distribution_parsed)
    )
  ) {
    return subscriptionTotal;
  }

  const fixedOriginalTotal = toFiniteNumber$1(distribution?.total_original_price);
  if (
    fixedOriginalTotal > 0
    && (
      hasEntries(distribution?.total_department_totals)
      || hasEntries(distribution?.total_department_totals_parsed)
    )
  ) {
    return fixedOriginalTotal;
  }

  return sumMapValues(getDepartmentBasisMap(distribution));
};

const getPercentageOfTotal = (value, total) => {
  const safeTotal = toFiniteNumber$1(total);
  if (safeTotal === 0) {
    return 0;
  }

  return Math.round((toFiniteNumber$1(value) / safeTotal) * 100);
};

const getDepartmentRelativeBookedAmount = (department, distribution = {}, bookedAmount = 0) => {
  const basisTotal = getDistributionBasisTotal(distribution);
  if (basisTotal === 0) {
    return 0;
  }

  return Math.round((getDepartmentBasisAmount(department, distribution) / basisTotal) * toFiniteNumber$1(bookedAmount));
};

const getTotalRelativeBookedAmount = (distribution = {}, bookedAmount = 0) => {
  const basisTotal = getDistributionBasisTotal(distribution);
  if (basisTotal === 0) {
    return 0;
  }

  return Math.round((sumMapValues(getDepartmentBasisMap(distribution)) / basisTotal) * toFiniteNumber$1(bookedAmount));
};

const getBookedDepartment75SourceDistributionMap = (distribution = {}, sourceCategory = null) => {
  const groups = getBookedDepartment75Groups(distribution);
  if (groups.length === 0 && !sourceCategory) {
    return getMap(getCollectiveResults(distribution)?.department_distribution);
  }

  return groups.reduce((totals, group = {}) => {
    if (!matchesSourceCategory(group, sourceCategory)) {
      return totals;
    }

    Object.entries(getMap(group?.department_distribution)).forEach(([departmentId, amount]) => {
      totals[departmentId] = toFiniteNumber$1(totals[departmentId]) + toFiniteNumber$1(amount);
    });

    return totals;
  }, {});
};

const getBookedDepartment75SourceDepartmentAmount = (department, distribution = {}, sourceCategory = null) => {
  return getMapValue(getBookedDepartment75SourceDistributionMap(distribution, sourceCategory), department);
};

const getBookedDepartment75SourceBookedTotal = (distribution = {}, sourceCategory = null) => {
  const groups = getBookedDepartment75Groups(distribution);
  if (groups.length === 0 && !sourceCategory) {
    return toFiniteNumber$1(getCollectiveResults(distribution)?.booked_net_amount);
  }

  return groups.reduce((sum, group = {}) => {
    if (!matchesSourceCategory(group, sourceCategory)) {
      return sum;
    }

    return sum + toFiniteNumber$1(group?.booked_net_amount);
  }, 0);
};

const getBookedDepartment75SourceDistributedTotal = (distribution = {}, sourceCategory = null) => {
  const groups = getBookedDepartment75Groups(distribution);
  if (groups.length === 0 && !sourceCategory) {
    return toFiniteNumber$1(getCollectiveResults(distribution)?.distributed_net_amount);
  }

  return sumMapValues(getBookedDepartment75SourceDistributionMap(distribution, sourceCategory));
};

const FIXED_PRICING_SOURCE_CATEGORY = "fixed_pricing";
const WASH_SUBSCRIPTIONS_SOURCE_CATEGORY = "wash_subscriptions";
const _sfc_main$1n = /* @__PURE__ */ defineComponent({
  __name: "InvoicingBillingPeriodStatistics",
  setup(__props, { expose: __expose }) {
    __expose();
    const BOOKED_DEPARTMENT_75_VIEWS = ["all", "fixed_pricing", "vehicle_subscriptions"];
    const getResponsePayload = (response = {}) => {
      return response?.data?.data ?? response?.data ?? response ?? {};
    };
    const fixed_pricing_department_distribution = ref([]);
    const fetchFixedPricingDistribution = async () => {
      SessionUser.request(
        "/superuser/invoicing/period/distribution/fixed-pricing",
        "GET",
        {
          dateFrom: dates.computed.formattedStartDate.value,
          dateTo: dates.computed.formattedEndDate.value
        }
      ).then((response) => {
        if (response.data && response.data.includes.collective_fixed_pricing_results) {
          fixed_pricing_department_distribution.value = response.data.includes.collective_fixed_pricing_results;
        } else {
          console.error("Unexpected response structure:", response);
        }
      }).catch((error) => {
        console.error("Error fetching fixed pricing distribution:", error);
      });
    };
    const clearFixedPricingDistribution = () => {
      fixed_pricing_department_distribution.value = [];
    };
    const bookedDepartment75Distribution = ref(null);
    const bookedDepartment75DistributionLoaded = ref(false);
    const bookedDepartment75DistributionFailed = ref(false);
    const fetchBookedDepartment75Distribution = async () => {
      bookedDepartment75DistributionLoaded.value = false;
      bookedDepartment75DistributionFailed.value = false;
      SessionUser.request(
        "/superuser/invoicing/period/distribution/v2/booked-department-75",
        "GET",
        {
          dateFrom: dates.computed.formattedStartDate.value,
          dateTo: dates.computed.formattedEndDate.value
        }
      ).then((response) => {
        bookedDepartment75Distribution.value = getResponsePayload(response);
        bookedDepartment75DistributionLoaded.value = true;
      }).catch((error) => {
        console.error("Error fetching booked department 75 distribution:", error);
        bookedDepartment75Distribution.value = null;
        bookedDepartment75DistributionLoaded.value = false;
        bookedDepartment75DistributionFailed.value = true;
      });
    };
    const clearBookedDepartment75Distribution = () => {
      bookedDepartment75Distribution.value = null;
      bookedDepartment75DistributionLoaded.value = false;
      bookedDepartment75DistributionFailed.value = false;
    };
    watch(
      () => view.variables.currentView.value,
      (newView) => {
        if (["all", "fixed_pricing"].includes(newView)) {
          fetchFixedPricingDistribution();
        }
      },
      { immediate: true }
    );
    watch(
      () => view.variables.currentView.value,
      (newView) => {
        if (BOOKED_DEPARTMENT_75_VIEWS.includes(newView)) {
          fetchBookedDepartment75Distribution();
        } else {
          clearBookedDepartment75Distribution();
        }
      },
      { immediate: true }
    );
    watch(
      () => [dates.variables.start.value, dates.variables.end.value],
      ([newStart, newEnd]) => {
        if (["all", "fixed_pricing"].includes(view.variables.currentView.value)) {
          clearFixedPricingDistribution();
          fetchFixedPricingDistribution();
        }
      }
    );
    watch(
      () => [dates.variables.start.value, dates.variables.end.value],
      ([newStart, newEnd]) => {
        if (BOOKED_DEPARTMENT_75_VIEWS.includes(view.variables.currentView.value)) {
          clearBookedDepartment75Distribution();
          fetchBookedDepartment75Distribution();
        }
      }
    );
    const vehicleSubscriptionDistribution = ref(null);
    const fetchVehicleSubscriptionDistribution = async () => {
      SessionUser.request(
        "/superuser/invoicing/period/distribution/wash-subscriptions",
        "GET",
        {
          dateFrom: dates.computed.formattedStartDate.value,
          dateTo: dates.computed.formattedEndDate.value
        }
      ).then((response) => {
        if (response.data && response.data.includes.collective_subscription_results) {
          vehicleSubscriptionDistribution.value = response.data.includes.collective_subscription_results;
        } else {
          console.error("Unexpected response structure:", response);
        }
      }).catch((error) => {
        console.error("Error fetching vehicle subscription distribution:", error);
      });
    };
    const clearVehicleSubscriptionDistribution = () => {
      vehicleSubscriptionDistribution.value = null;
    };
    watch(
      () => view.variables.currentView.value,
      (newView) => {
        if (["all", "vehicle_subscriptions"].includes(newView)) {
          fetchVehicleSubscriptionDistribution();
        } else {
          clearVehicleSubscriptionDistribution();
        }
      },
      { immediate: true }
    );
    watch(
      () => [dates.variables.start.value, dates.variables.end.value],
      ([newStart, newEnd]) => {
        if (["all", "vehicle_subscriptions"].includes(view.variables.currentView.value)) {
          clearVehicleSubscriptionDistribution();
          fetchVehicleSubscriptionDistribution();
        }
      }
    );
    const department75_total = ref(null);
    const calculate_department75_total = () => {
      if (fixed_pricing_department_distribution.value?.total_fixed_price !== void 0 && vehicleSubscriptionDistribution.value?.total_subscription_price !== void 0) {
        return fixed_pricing_department_distribution.value?.total_fixed_price + vehicleSubscriptionDistribution.value?.total_subscription_price;
      }
      return null;
    };
    watch(
      () => [fixed_pricing_department_distribution.value, vehicleSubscriptionDistribution.value],
      () => {
        department75_total.value = calculate_department75_total();
      }
    );
    const getDepartmentRelativeBookedAmount$1 = (department, distribution, bookedAmount = null) => {
      return getDepartmentRelativeBookedAmount(
        department,
        distribution,
        bookedAmount ?? view.computed.currentViewTotalNetAmountBooked.value ?? 0
      );
    };
    const useBookedDepartment75Distribution = computed(() => {
      return bookedDepartment75DistributionLoaded.value && !bookedDepartment75DistributionFailed.value && bookedDepartment75Distribution.value !== null;
    });
    const getCurrentViewFallbackBookedTotal = (sourceCategory) => {
      if (sourceCategory === FIXED_PRICING_SOURCE_CATEGORY && view.functions.isCurrentView("fixed_pricing")) {
        return view.computed.currentViewTotalNetAmountBooked.value || 0;
      }
      if (sourceCategory === WASH_SUBSCRIPTIONS_SOURCE_CATEGORY && view.functions.isCurrentView("vehicle_subscriptions")) {
        return view.computed.currentViewTotalNetAmountBooked.value || 0;
      }
      return 0;
    };
    const getFixedPricingBookedAmount = (department) => {
      if (useBookedDepartment75Distribution.value) {
        return getBookedDepartment75SourceDepartmentAmount(
          department,
          bookedDepartment75Distribution.value,
          FIXED_PRICING_SOURCE_CATEGORY
        );
      }
      return getDepartmentRelativeBookedAmount$1(
        department,
        fixed_pricing_department_distribution.value,
        getCurrentViewFallbackBookedTotal(FIXED_PRICING_SOURCE_CATEGORY)
      );
    };
    const getFixedPricingBookedTotal = () => {
      if (useBookedDepartment75Distribution.value) {
        return getBookedDepartment75SourceBookedTotal(
          bookedDepartment75Distribution.value,
          FIXED_PRICING_SOURCE_CATEGORY
        );
      }
      return getCurrentViewFallbackBookedTotal(FIXED_PRICING_SOURCE_CATEGORY);
    };
    const getFixedPricingDistributedTotal = () => {
      if (useBookedDepartment75Distribution.value) {
        return getBookedDepartment75SourceDistributedTotal(
          bookedDepartment75Distribution.value,
          FIXED_PRICING_SOURCE_CATEGORY
        );
      }
      return getTotalRelativeBookedAmount(
        fixed_pricing_department_distribution.value,
        getCurrentViewFallbackBookedTotal(FIXED_PRICING_SOURCE_CATEGORY)
      );
    };
    const getFixedPricingBookedPercentage = (department) => {
      return getPercentageOfTotal(getFixedPricingBookedAmount(department), getFixedPricingBookedTotal());
    };
    const getVehicleSubscriptionBookedAmount = (department) => {
      if (useBookedDepartment75Distribution.value) {
        return getBookedDepartment75SourceDepartmentAmount(
          department,
          bookedDepartment75Distribution.value,
          WASH_SUBSCRIPTIONS_SOURCE_CATEGORY
        );
      }
      return getDepartmentRelativeBookedAmount$1(
        department,
        vehicleSubscriptionDistribution.value,
        getCurrentViewFallbackBookedTotal(WASH_SUBSCRIPTIONS_SOURCE_CATEGORY)
      );
    };
    const getVehicleSubscriptionBookedTotal = () => {
      if (useBookedDepartment75Distribution.value) {
        return getBookedDepartment75SourceBookedTotal(
          bookedDepartment75Distribution.value,
          WASH_SUBSCRIPTIONS_SOURCE_CATEGORY
        );
      }
      return getCurrentViewFallbackBookedTotal(WASH_SUBSCRIPTIONS_SOURCE_CATEGORY);
    };
    const getVehicleSubscriptionDistributedTotal = () => {
      if (useBookedDepartment75Distribution.value) {
        return getBookedDepartment75SourceDistributedTotal(
          bookedDepartment75Distribution.value,
          WASH_SUBSCRIPTIONS_SOURCE_CATEGORY
        );
      }
      return getTotalRelativeBookedAmount(
        vehicleSubscriptionDistribution.value,
        getCurrentViewFallbackBookedTotal(WASH_SUBSCRIPTIONS_SOURCE_CATEGORY)
      );
    };
    const getFixedPricingOriginalAmount = (department) => {
      return getFixedPricingOriginalDepartmentAmount(department, fixed_pricing_department_distribution.value);
    };
    const getFixedPricingActualAmount = (department) => {
      return getFixedPricingActualDepartmentAmount(department, fixed_pricing_department_distribution.value);
    };
    const getVehicleSubscriptionAmount = (department) => {
      return getVehicleSubscriptionDepartmentAmount(department, vehicleSubscriptionDistribution.value);
    };
    const department75CombinedRows = computed(() => {
      return (departments.value || []).map((department) => {
        const fixedPricingOriginalAmount = getFixedPricingOriginalAmount(department);
        const fixedPricingActualAmount = getFixedPricingActualAmount(department);
        const vehicleSubscriptionAmount = getVehicleSubscriptionAmount(department);
        const fixedPricingBookedAmount = getFixedPricingBookedAmount(department);
        const vehicleSubscriptionBookedAmount = getVehicleSubscriptionBookedAmount(department);
        return {
          department,
          fixedPricingOriginalAmount,
          fixedPricingActualAmount,
          fixedPricingPaymentPercentage: getPercentageOfTotal(fixedPricingActualAmount, fixedPricingOriginalAmount),
          vehicleSubscriptionAmount,
          calculatedDepartment75Amount: fixedPricingActualAmount + vehicleSubscriptionAmount,
          fixedPricingBookedAmount,
          fixedPricingBookedPercentage: getPercentageOfTotal(fixedPricingBookedAmount, getFixedPricingBookedTotal()),
          vehicleSubscriptionBookedAmount,
          bookedAmount: fixedPricingBookedAmount + vehicleSubscriptionBookedAmount,
          hasFixedPricingValues: fixedPricingOriginalAmount !== 0 || fixedPricingActualAmount !== 0 || fixedPricingBookedAmount !== 0,
          hasVehicleSubscriptionValues: vehicleSubscriptionAmount !== 0 || vehicleSubscriptionBookedAmount !== 0,
          hasAnyValues: fixedPricingOriginalAmount !== 0 || fixedPricingActualAmount !== 0 || vehicleSubscriptionAmount !== 0 || fixedPricingBookedAmount !== 0 || vehicleSubscriptionBookedAmount !== 0
        };
      });
    });
    const department75CombinedTotals = computed(() => {
      const fixedPricingOriginalAmount = toFiniteNumber$1(fixed_pricing_department_distribution.value?.total_original_price);
      const fixedPricingActualAmount = toFiniteNumber$1(fixed_pricing_department_distribution.value?.total_fixed_price);
      const vehicleSubscriptionAmount = toFiniteNumber$1(vehicleSubscriptionDistribution.value?.total_subscription_price);
      const fixedPricingBookedAmount = getFixedPricingBookedTotal();
      const vehicleSubscriptionBookedAmount = getVehicleSubscriptionBookedTotal();
      const fixedPricingDistributedAmount = getFixedPricingDistributedTotal();
      const vehicleSubscriptionDistributedAmount = getVehicleSubscriptionDistributedTotal();
      return {
        fixedPricingOriginalAmount,
        fixedPricingActualAmount,
        fixedPricingPaymentPercentage: getPercentageOfTotal(fixedPricingActualAmount, fixedPricingOriginalAmount),
        vehicleSubscriptionAmount,
        calculatedDepartment75Amount: fixedPricingActualAmount + vehicleSubscriptionAmount,
        fixedPricingBookedAmount,
        fixedPricingDistributedAmount,
        vehicleSubscriptionBookedAmount,
        vehicleSubscriptionDistributedAmount,
        bookedAmount: fixedPricingBookedAmount + vehicleSubscriptionBookedAmount,
        distributedAmount: fixedPricingDistributedAmount + vehicleSubscriptionDistributedAmount
      };
    });
    const hasDepartment75CombinedBasis = computed(() => {
      return fixed_pricing_department_distribution.value?.total_fixed_price !== void 0 || vehicleSubscriptionDistribution.value?.total_subscription_price !== void 0;
    });
    const isDepartment75CombinedFullyLoaded = computed(() => {
      return fixed_pricing_department_distribution.value?.total_fixed_price !== void 0 && vehicleSubscriptionDistribution.value?.total_subscription_price !== void 0;
    });
    const department75Table = ref(null);
    const downloadExcel = () => {
      if (!department75Table.value) return;
      const rows = extractVisibleRowsFromTable(department75Table.value);
      exportRowsToExcel(rows, {
        filename: `invoicing-period-department-75-${dates.computed.formattedStartDate.value}-${dates.computed.formattedEndDate.value}.xlsx`,
        sheetName: "Department 75 Distribution"
      });
    };
    const formatCurrencyAmount = (amount) => {
      return SessionUser.functions.currency.toLocal(toFiniteNumber$1(amount));
    };
    const formatCurrencyAmountOrDash = (amount) => {
      const safeAmount = toFiniteNumber$1(amount);
      return safeAmount === 0 ? "-" : formatCurrencyAmount(safeAmount);
    };
    const __returned__ = { FIXED_PRICING_SOURCE_CATEGORY, WASH_SUBSCRIPTIONS_SOURCE_CATEGORY, BOOKED_DEPARTMENT_75_VIEWS, getResponsePayload, fixed_pricing_department_distribution, fetchFixedPricingDistribution, clearFixedPricingDistribution, bookedDepartment75Distribution, bookedDepartment75DistributionLoaded, bookedDepartment75DistributionFailed, fetchBookedDepartment75Distribution, clearBookedDepartment75Distribution, vehicleSubscriptionDistribution, fetchVehicleSubscriptionDistribution, clearVehicleSubscriptionDistribution, department75_total, calculate_department75_total, getDepartmentRelativeBookedAmount: getDepartmentRelativeBookedAmount$1, useBookedDepartment75Distribution, getCurrentViewFallbackBookedTotal, getFixedPricingBookedAmount, getFixedPricingBookedTotal, getFixedPricingDistributedTotal, getFixedPricingBookedPercentage, getVehicleSubscriptionBookedAmount, getVehicleSubscriptionBookedTotal, getVehicleSubscriptionDistributedTotal, getFixedPricingOriginalAmount, getFixedPricingActualAmount, getVehicleSubscriptionAmount, department75CombinedRows, department75CombinedTotals, hasDepartment75CombinedBasis, isDepartment75CombinedFullyLoaded, department75Table, downloadExcel, formatCurrencyAmount, formatCurrencyAmountOrDash, StatisticsIncomeCard, WhiteBoxCard, dates, view, get BTooltip() {
      return Tooltip$1;
    }, get getPercentageOfTotal() {
      return getPercentageOfTotal;
    } };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$I = {
  class: "columns is-multiline is-mobile",
  "data-testid": "invoicing-period-statistics"
};
const _hoisted_2$z = {
  class: "column is-one-third",
  "data-testid": "invoicing-period-stat-total"
};
const _hoisted_3$v = {
  class: "column is-one-third",
  "data-testid": "invoicing-period-stat-booked"
};
const _hoisted_4$v = {
  class: "column is-one-third",
  "data-testid": "invoicing-period-stat-not-booked"
};
const _hoisted_5$u = { class: "column is-one-third" };
const _hoisted_6$u = { class: "column is-one-third" };
const _hoisted_7$s = { class: "column is-one-third" };
const _hoisted_8$s = { class: "column is-full invoicing-period-department-75-column" };
const _hoisted_9$q = {
  class: "table-container invoicing-period-distribution-table-container invoicing-period-distribution-table-container--combined mb-0",
  "data-testid": "department-75-combined-distribution-table-container",
  "data-disable-auto-excel-export": "1"
};
const _hoisted_10$p = {
  class: "table is-fullwidth is-striped is-hoverable is-bordered is-narrow invoicing-period-distribution-table invoicing-period-distribution-table--combined",
  "data-testid": "department-75-combined-distribution-table",
  ref: "department75Table"
};
const _hoisted_11$l = { class: "is-size-7" };
const _hoisted_12$k = { class: "is-size-7" };
const _hoisted_13$i = { class: "is-size-7" };
const _hoisted_14$g = { key: 1 };
const _hoisted_15$g = { class: "mt-0 has-text-right" };
const _hoisted_16$g = {
  key: 0,
  class: "columns is-mobile is-multiline is-gapless mb-0",
  "data-testid": "department-75-combined-loading-status"
};
const _hoisted_17$e = {
  key: 0,
  class: "column"
};
const _hoisted_18$e = { class: "icon is-small" };
const _hoisted_19$c = {
  key: 1,
  class: "column"
};
const _hoisted_20$b = { class: "icon is-small" };
const _hoisted_21$b = {
  key: 2,
  class: "column"
};
const _hoisted_22$b = { class: "icon is-small" };
const _hoisted_23$b = {
  key: 3,
  class: "column"
};
const _hoisted_24$b = { class: "icon is-small" };
const _hoisted_25$b = { class: "column is-one-third" };
const _hoisted_26$b = { class: "column is-one-third" };
const _hoisted_27$a = { class: "column is-one-third" };
const _hoisted_28$a = { class: "column is-full" };
const _hoisted_29$9 = { class: "table-container invoicing-period-distribution-table-container" };
const _hoisted_30$9 = { class: "table is-fullwidth is-striped is-hoverable is-bordered is-narrow invoicing-period-distribution-table" };
const _hoisted_31$9 = { key: 0 };
const _hoisted_32$9 = { class: "has-text-strikethrough" };
const _hoisted_33$9 = { key: 1 };
const _hoisted_34$9 = { class: "column is-one-third" };
const _hoisted_35$9 = { class: "column is-full" };
const _hoisted_36$8 = { class: "table-container invoicing-period-distribution-table-container" };
const _hoisted_37$8 = { class: "table is-fullwidth is-striped is-hoverable is-bordered is-narrow invoicing-period-distribution-table" };
const _hoisted_38$8 = { key: 0 };
const _hoisted_39$8 = { key: 1 };
function _sfc_render$P(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock(
    Fragment,
    null,
    [
      createCommentVNode(" Booked, not booked and total income "),
      createBaseVNode("div", _hoisted_1$I, [
        createBaseVNode("div", _hoisted_2$z, [
          createVNode($setup["WhiteBoxCard"], {
            "has-selection-style": true,
            "has-hover-effect": true,
            "has-border": true
          }, {
            default: withCtx(() => [
              createCommentVNode(" Income total "),
              createVNode($setup["StatisticsIncomeCard"], {
                "force-display": {
                  value: $setup.view.computed.currentViewTotalNetAmount.value,
                  start_date: $setup.dates.computed.formattedStartDate.value,
                  end_date: $setup.dates.computed.formattedEndDate.value,
                  error: null
                },
                icon: "fas fa-money-bill-wave",
                name: "I alt"
              }, null, 8, ["force-display"])
            ]),
            _: 1
            /* STABLE */
          })
        ]),
        createBaseVNode("div", _hoisted_3$v, [
          createVNode($setup["WhiteBoxCard"], {
            "has-selection-style": true,
            "has-hover-effect": true,
            "has-border": true
          }, {
            default: withCtx(() => [
              createCommentVNode(" Income booked "),
              createVNode($setup["StatisticsIncomeCard"], {
                "force-display": {
                  value: $setup.view.computed.currentViewTotalNetAmountBooked.value,
                  start_date: $setup.dates.computed.formattedStartDate.value,
                  end_date: $setup.dates.computed.formattedEndDate.value,
                  error: null
                },
                icon: "fas fa-money-bill-wave",
                name: "Bogført",
                color: "has-text-success",
                "font-style": "oblique"
              }, null, 8, ["force-display"])
            ]),
            _: 1
            /* STABLE */
          })
        ]),
        createBaseVNode("div", _hoisted_4$v, [
          createVNode($setup["WhiteBoxCard"], {
            "has-selection-style": true,
            "has-hover-effect": true,
            "has-border": true
          }, {
            default: withCtx(() => [
              createCommentVNode(" Income not booked "),
              createVNode($setup["StatisticsIncomeCard"], {
                "force-display": {
                  value: $setup.view.computed.currentViewTotalNetAmountNotBooked.value,
                  start_date: $setup.dates.computed.formattedStartDate.value,
                  end_date: $setup.dates.computed.formattedEndDate.value,
                  error: null
                },
                icon: "fas fa-money-bill-wave",
                name: "Ikke bogført",
                color: $setup.view.computed.currentViewTotalNetAmountNotBooked.value > 0 ? "danger" : "black",
                "font-style": "oblique"
              }, null, 8, ["force-display", "color"])
            ]),
            _: 1
            /* STABLE */
          })
        ]),
        createCommentVNode(" If an entire month is selected, show overall distribution "),
        $setup.dates.computed.isEntireMonth.value && $setup.view.functions.isCurrentView("all") ? (openBlock(), createElementBlock(
          Fragment,
          { key: 0 },
          [
            createCommentVNode(" Divider "),
            _cache[16] || (_cache[16] = createBaseVNode(
              "div",
              { class: "column is-full" },
              [
                createBaseVNode("div", { class: "divider" }, [
                  createBaseVNode("div", { class: "divider-text has-text-weight-bold" }, " Heraf afdeling 75 ")
                ])
              ],
              -1
              /* CACHED */
            )),
            createCommentVNode(" Department 75 "),
            createBaseVNode("div", _hoisted_5$u, [
              createVNode($setup["WhiteBoxCard"], {
                "has-selection-style": true,
                "has-hover-effect": true,
                "has-border": true
              }, {
                default: withCtx(() => [
                  createVNode($setup["StatisticsIncomeCard"], {
                    "force-display": {
                      value: $setup.department75CombinedTotals.calculatedDepartment75Amount || 0,
                      start_date: $setup.dates.computed.formattedStartDate.value,
                      end_date: $setup.dates.computed.formattedEndDate.value,
                      error: null
                    },
                    loading: !$setup.hasDepartment75CombinedBasis,
                    icon: "fas fa-money-bill-wave",
                    name: "Afdeling 75",
                    color: "black",
                    "font-style": "normal"
                  }, null, 8, ["force-display", "loading"])
                ]),
                _: 1
                /* STABLE */
              })
            ]),
            createCommentVNode(" Wash subscriptions "),
            createBaseVNode("div", _hoisted_6$u, [
              createVNode($setup["WhiteBoxCard"], {
                "has-selection-style": true,
                "has-hover-effect": true,
                "has-border": true
              }, {
                default: withCtx(() => [
                  createVNode($setup["StatisticsIncomeCard"], {
                    "force-display": {
                      value: $setup.vehicleSubscriptionDistribution?.total_subscription_price || 0,
                      start_date: $setup.dates.computed.formattedStartDate.value,
                      end_date: $setup.dates.computed.formattedEndDate.value,
                      error: null
                    },
                    loading: $setup.vehicleSubscriptionDistribution?.total_subscription_price === void 0,
                    icon: "fas fa-money-bill-wave",
                    name: "Vaske-aftale",
                    color: "black",
                    "font-style": "oblique"
                  }, null, 8, ["force-display", "loading"])
                ]),
                _: 1
                /* STABLE */
              })
            ]),
            createCommentVNode(" Fixed pricing "),
            createBaseVNode("div", _hoisted_7$s, [
              createVNode($setup["WhiteBoxCard"], {
                "has-selection-style": true,
                "has-hover-effect": true,
                "has-border": true
              }, {
                default: withCtx(() => [
                  createVNode($setup["StatisticsIncomeCard"], {
                    "force-display": {
                      value: $setup.fixed_pricing_department_distribution?.total_fixed_price || 0,
                      start_date: $setup.dates.computed.formattedStartDate.value,
                      end_date: $setup.dates.computed.formattedEndDate.value,
                      error: null
                    },
                    loading: $setup.fixed_pricing_department_distribution?.total_fixed_price === void 0,
                    icon: "fas fa-money-bill-wave",
                    name: "Fast-pris",
                    color: "black",
                    "font-style": "oblique"
                  }, null, 8, ["force-display", "loading"])
                ]),
                _: 1
                /* STABLE */
              })
            ]),
            createCommentVNode(" Combined Department 75 distribution "),
            createBaseVNode("div", _hoisted_8$s, [
              createVNode($setup["WhiteBoxCard"], {
                "has-selection-style": true,
                "has-hover-effect": true,
                "has-border": true
              }, {
                default: withCtx(() => [
                  createBaseVNode("div", _hoisted_9$q, [
                    createBaseVNode(
                      "table",
                      _hoisted_10$p,
                      [
                        createBaseVNode("thead", null, [
                          createBaseVNode("tr", null, [
                            _cache[2] || (_cache[2] = createBaseVNode(
                              "th",
                              null,
                              "Afdeling",
                              -1
                              /* CACHED */
                            )),
                            _cache[3] || (_cache[3] = createBaseVNode(
                              "th",
                              null,
                              "Fastprisaftaler før pris",
                              -1
                              /* CACHED */
                            )),
                            _cache[4] || (_cache[4] = createBaseVNode(
                              "th",
                              null,
                              "Fastprisaftaler faktisk pris",
                              -1
                              /* CACHED */
                            )),
                            _cache[5] || (_cache[5] = createBaseVNode(
                              "th",
                              null,
                              "Vaskeabonnement",
                              -1
                              /* CACHED */
                            )),
                            _cache[6] || (_cache[6] = createBaseVNode(
                              "th",
                              null,
                              "Afdeling 75 beregnet",
                              -1
                              /* CACHED */
                            )),
                            _cache[7] || (_cache[7] = createBaseVNode(
                              "th",
                              null,
                              "Fastprisaftaler bogført",
                              -1
                              /* CACHED */
                            )),
                            _cache[8] || (_cache[8] = createBaseVNode(
                              "th",
                              null,
                              "Vaskeabonnement bogført",
                              -1
                              /* CACHED */
                            )),
                            createBaseVNode("th", null, [
                              _cache[1] || (_cache[1] = createTextVNode(
                                "Bogført i alt ",
                                -1
                                /* CACHED */
                              )),
                              createVNode($setup["BTooltip"], {
                                label: "Bogførte beløb hentes fra e-conomic afdeling 75 og opdeles efter bogførte fastprisaftale- og vaskeabonnement-linjer.",
                                type: "is-info"
                              }, {
                                default: withCtx(() => [..._cache[0] || (_cache[0] = [
                                  createTextVNode(
                                    "?",
                                    -1
                                    /* CACHED */
                                  )
                                ])]),
                                _: 1
                                /* STABLE */
                              })
                            ])
                          ])
                        ]),
                        createBaseVNode("tbody", null, [
                          $setup.hasDepartment75CombinedBasis ? (openBlock(), createElementBlock(
                            Fragment,
                            { key: 0 },
                            [
                              (openBlock(true), createElementBlock(
                                Fragment,
                                null,
                                renderList($setup.department75CombinedRows, (row) => {
                                  return openBlock(), createElementBlock("tr", {
                                    key: `department-75-combined-${row.department.id || row.department.name}`
                                  }, [
                                    createBaseVNode(
                                      "td",
                                      null,
                                      toDisplayString(row.department.name),
                                      1
                                      /* TEXT */
                                    ),
                                    createBaseVNode(
                                      "td",
                                      null,
                                      toDisplayString($setup.formatCurrencyAmountOrDash(row.fixedPricingOriginalAmount)),
                                      1
                                      /* TEXT */
                                    ),
                                    createBaseVNode(
                                      "td",
                                      null,
                                      toDisplayString($setup.formatCurrencyAmountOrDash(row.fixedPricingActualAmount)),
                                      1
                                      /* TEXT */
                                    ),
                                    createBaseVNode(
                                      "td",
                                      null,
                                      toDisplayString($setup.formatCurrencyAmountOrDash(row.vehicleSubscriptionAmount)),
                                      1
                                      /* TEXT */
                                    ),
                                    createBaseVNode(
                                      "td",
                                      null,
                                      toDisplayString($setup.formatCurrencyAmountOrDash(row.calculatedDepartment75Amount)),
                                      1
                                      /* TEXT */
                                    ),
                                    createBaseVNode(
                                      "td",
                                      null,
                                      toDisplayString($setup.formatCurrencyAmountOrDash(row.fixedPricingBookedAmount)),
                                      1
                                      /* TEXT */
                                    ),
                                    createBaseVNode(
                                      "td",
                                      null,
                                      toDisplayString($setup.formatCurrencyAmountOrDash(row.vehicleSubscriptionBookedAmount)),
                                      1
                                      /* TEXT */
                                    ),
                                    createBaseVNode(
                                      "td",
                                      null,
                                      toDisplayString($setup.formatCurrencyAmountOrDash(row.bookedAmount)),
                                      1
                                      /* TEXT */
                                    )
                                  ]);
                                }),
                                128
                                /* KEYED_FRAGMENT */
                              )),
                              createBaseVNode("tr", null, [
                                _cache[9] || (_cache[9] = createBaseVNode(
                                  "td",
                                  null,
                                  [
                                    createBaseVNode("strong", null, "Total")
                                  ],
                                  -1
                                  /* CACHED */
                                )),
                                createBaseVNode("td", null, [
                                  createBaseVNode(
                                    "strong",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.fixedPricingOriginalAmount)),
                                    1
                                    /* TEXT */
                                  )
                                ]),
                                createBaseVNode("td", null, [
                                  createBaseVNode(
                                    "strong",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.fixedPricingActualAmount)),
                                    1
                                    /* TEXT */
                                  )
                                ]),
                                createBaseVNode("td", null, [
                                  createBaseVNode(
                                    "strong",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.vehicleSubscriptionAmount)),
                                    1
                                    /* TEXT */
                                  )
                                ]),
                                createBaseVNode("td", null, [
                                  createBaseVNode(
                                    "strong",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.calculatedDepartment75Amount)),
                                    1
                                    /* TEXT */
                                  )
                                ]),
                                createBaseVNode("td", null, [
                                  createBaseVNode(
                                    "strong",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.fixedPricingBookedAmount)),
                                    1
                                    /* TEXT */
                                  ),
                                  createBaseVNode(
                                    "span",
                                    _hoisted_11$l,
                                    " (Fordelt: " + toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.fixedPricingDistributedAmount)) + ")",
                                    1
                                    /* TEXT */
                                  )
                                ]),
                                createBaseVNode("td", null, [
                                  createBaseVNode(
                                    "strong",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.vehicleSubscriptionBookedAmount)),
                                    1
                                    /* TEXT */
                                  ),
                                  createBaseVNode(
                                    "span",
                                    _hoisted_12$k,
                                    " (Fordelt: " + toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.vehicleSubscriptionDistributedAmount)) + ")",
                                    1
                                    /* TEXT */
                                  )
                                ]),
                                createBaseVNode("td", null, [
                                  createBaseVNode(
                                    "strong",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.bookedAmount)),
                                    1
                                    /* TEXT */
                                  ),
                                  createBaseVNode(
                                    "span",
                                    _hoisted_13$i,
                                    " (Fordelt: " + toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.distributedAmount)) + ")",
                                    1
                                    /* TEXT */
                                  )
                                ])
                              ])
                            ],
                            64
                            /* STABLE_FRAGMENT */
                          )) : (openBlock(), createElementBlock("tr", _hoisted_14$g, [..._cache[10] || (_cache[10] = [
                            createBaseVNode(
                              "td",
                              {
                                colspan: "8",
                                class: "has-text-centered"
                              },
                              [
                                createBaseVNode("span", { class: "icon is-large" }, [
                                  createBaseVNode("i", { class: "fas fa-spinner fa-spin fa-2x" })
                                ]),
                                createBaseVNode("p", null, "Henter afdeling 75 fordeling data...")
                              ],
                              -1
                              /* CACHED */
                            )
                          ])]))
                        ])
                      ],
                      512
                      /* NEED_PATCH */
                    )
                  ]),
                  createBaseVNode("div", _hoisted_15$g, [
                    createCommentVNode(" If any of the department 75 data is not fully loaded, show the loading status buttons "),
                    !$setup.isDepartment75CombinedFullyLoaded ? (openBlock(), createElementBlock("div", _hoisted_16$g, [
                      createCommentVNode(" Loading state: 1. Fixed pricing distribution loading "),
                      !$setup.fixed_pricing_department_distribution || $setup.fixed_pricing_department_distribution?.total_fixed_price === void 0 ? (openBlock(), createElementBlock("div", _hoisted_17$e, [
                        createBaseVNode(
                          "button",
                          {
                            class: normalizeClass(["button is-text is-small is-fullwidth no-underline", { "is-active": $setup.fixed_pricing_department_distribution?.total_fixed_price === void 0 }])
                          },
                          [
                            createCommentVNode(" [Label] [Icon pulled right] "),
                            createBaseVNode("span", _hoisted_18$e, [
                              createBaseVNode(
                                "i",
                                {
                                  class: normalizeClass(["fas", $setup.fixed_pricing_department_distribution?.total_fixed_price === void 0 ? "fa-spinner fa-spin" : "fa-check-circle"])
                                },
                                null,
                                2
                                /* CLASS */
                              )
                            ]),
                            _cache[11] || (_cache[11] = createBaseVNode(
                              "span",
                              null,
                              "Fast-pris aftaler",
                              -1
                              /* CACHED */
                            ))
                          ],
                          2
                          /* CLASS */
                        )
                      ])) : createCommentVNode("v-if", true),
                      createCommentVNode(" Loading state: 2. Vehicle subscription distribution loading "),
                      !$setup.vehicleSubscriptionDistribution || $setup.vehicleSubscriptionDistribution?.total_subscription_price === void 0 ? (openBlock(), createElementBlock("div", _hoisted_19$c, [
                        createBaseVNode(
                          "button",
                          {
                            class: normalizeClass(["button is-text is-small is-fullwidth no-underline", { "is-active": $setup.vehicleSubscriptionDistribution?.total_subscription_price === void 0 }])
                          },
                          [
                            createCommentVNode(" [Label] [Icon pulled right] "),
                            createBaseVNode("span", _hoisted_20$b, [
                              createBaseVNode(
                                "i",
                                {
                                  class: normalizeClass(["fas", $setup.vehicleSubscriptionDistribution?.total_subscription_price === void 0 ? "fa-spinner fa-spin" : "fa-check-circle"])
                                },
                                null,
                                2
                                /* CLASS */
                              )
                            ]),
                            _cache[12] || (_cache[12] = createBaseVNode(
                              "span",
                              null,
                              "Vaskeabonnementer",
                              -1
                              /* CACHED */
                            ))
                          ],
                          2
                          /* CLASS */
                        )
                      ])) : createCommentVNode("v-if", true),
                      createCommentVNode(" Loading state: 3. Booked department 75 distribution loading "),
                      !$setup.bookedDepartment75DistributionLoaded || $setup.bookedDepartment75DistributionFailed ? (openBlock(), createElementBlock("div", _hoisted_21$b, [
                        createBaseVNode(
                          "button",
                          {
                            class: normalizeClass(["button is-text is-small is-fullwidth no-underline", { "is-active": !$setup.bookedDepartment75DistributionLoaded || $setup.bookedDepartment75DistributionFailed }])
                          },
                          [
                            createCommentVNode(" [Label] [Icon pulled right] "),
                            createBaseVNode("span", _hoisted_22$b, [
                              createBaseVNode(
                                "i",
                                {
                                  class: normalizeClass(["fas", !$setup.bookedDepartment75DistributionLoaded ? "fa-spinner fa-spin" : $setup.bookedDepartment75DistributionFailed ? "fa-exclamation-triangle" : "fa-check-circle"])
                                },
                                null,
                                2
                                /* CLASS */
                              )
                            ]),
                            _cache[13] || (_cache[13] = createBaseVNode(
                              "span",
                              null,
                              "Afdeling 75 (bogført)",
                              -1
                              /* CACHED */
                            ))
                          ],
                          2
                          /* CLASS */
                        )
                      ])) : createCommentVNode("v-if", true),
                      createCommentVNode(" Loading state: 4. Overall combined data loading (based on the three above) "),
                      !$setup.isDepartment75CombinedFullyLoaded ? (openBlock(), createElementBlock("div", _hoisted_23$b, [
                        createBaseVNode(
                          "button",
                          {
                            class: normalizeClass(["button is-text is-small is-fullwidth no-underline", { "is-active": !$setup.isDepartment75CombinedFullyLoaded }])
                          },
                          [
                            createCommentVNode(" [Label] [Icon pulled right] "),
                            createBaseVNode("span", _hoisted_24$b, [
                              createBaseVNode(
                                "i",
                                {
                                  class: normalizeClass(["fas", !$setup.isDepartment75CombinedFullyLoaded ? "fa-spinner fa-spin" : "fa-check-circle"])
                                },
                                null,
                                2
                                /* CLASS */
                              )
                            ]),
                            _cache[14] || (_cache[14] = createBaseVNode(
                              "span",
                              null,
                              "Afdeling 75 (samlet)",
                              -1
                              /* CACHED */
                            ))
                          ],
                          2
                          /* CLASS */
                        )
                      ])) : createCommentVNode("v-if", true)
                    ])) : createCommentVNode("v-if", true),
                    $setup.isDepartment75CombinedFullyLoaded ? (openBlock(), createElementBlock("button", {
                      key: 1,
                      class: "button is-text is-small is-fullwidth no-underline",
                      onClick: $setup.downloadExcel
                    }, [..._cache[15] || (_cache[15] = [
                      createBaseVNode(
                        "span",
                        { class: "icon is-small" },
                        [
                          createBaseVNode("i", { class: "fas fa-file-excel" })
                        ],
                        -1
                        /* CACHED */
                      ),
                      createBaseVNode(
                        "span",
                        null,
                        "Download Excel",
                        -1
                        /* CACHED */
                      )
                    ])])) : createCommentVNode("v-if", true)
                  ])
                ]),
                _: 1
                /* STABLE */
              })
            ])
          ],
          64
          /* STABLE_FRAGMENT */
        )) : createCommentVNode("v-if", true),
        $setup.view.functions.isCurrentView("fixed_pricing") ? (openBlock(), createElementBlock(
          Fragment,
          { key: 1 },
          [
            createCommentVNode(" Divider "),
            _cache[26] || (_cache[26] = createBaseVNode(
              "div",
              { class: "column is-full" },
              [
                createBaseVNode("div", { class: "divider" }, [
                  createBaseVNode("div", { class: "divider-text has-text-weight-bold" }, " Afdeling 75 - Fast-pris fordeling ")
                ])
              ],
              -1
              /* CACHED */
            )),
            createCommentVNode(" Total fixed price "),
            createBaseVNode("div", _hoisted_25$b, [
              createVNode($setup["WhiteBoxCard"], {
                "has-selection-style": true,
                "has-hover-effect": true,
                "has-border": true
              }, {
                default: withCtx(() => [
                  createVNode($setup["StatisticsIncomeCard"], {
                    "force-display": {
                      value: $setup.fixed_pricing_department_distribution?.total_fixed_price || 0,
                      start_date: $setup.dates.computed.formattedStartDate.value,
                      end_date: $setup.dates.computed.formattedEndDate.value,
                      error: null
                    },
                    loading: $setup.fixed_pricing_department_distribution?.total_fixed_price === void 0,
                    icon: "fas fa-money-bill-wave",
                    name: "Faktisk pris",
                    color: "black"
                  }, null, 8, ["force-display", "loading"])
                ]),
                _: 1
                /* STABLE */
              })
            ]),
            createCommentVNode(" Total original price "),
            createBaseVNode("div", _hoisted_26$b, [
              createVNode($setup["WhiteBoxCard"], {
                "has-selection-style": true,
                "has-hover-effect": true,
                "has-border": true
              }, {
                default: withCtx(() => [
                  createVNode($setup["StatisticsIncomeCard"], {
                    "force-display": {
                      value: $setup.fixed_pricing_department_distribution?.total_original_price || 0,
                      start_date: $setup.dates.computed.formattedStartDate.value,
                      end_date: $setup.dates.computed.formattedEndDate.value,
                      error: null
                    },
                    loading: $setup.fixed_pricing_department_distribution?.total_original_price === void 0,
                    icon: "fas fa-money-bill-wave",
                    name: "Før pris",
                    color: "black",
                    "font-style": "oblique"
                  }, null, 8, ["force-display", "loading"])
                ]),
                _: 1
                /* STABLE */
              })
            ]),
            createCommentVNode(" Total loss/gain between original and fixed price "),
            createBaseVNode("div", _hoisted_27$a, [
              createVNode($setup["WhiteBoxCard"], {
                "has-selection-style": true,
                "has-hover-effect": true,
                "has-border": true
              }, {
                default: withCtx(() => [
                  createVNode($setup["StatisticsIncomeCard"], {
                    "force-display": {
                      value: ($setup.fixed_pricing_department_distribution?.total_fixed_price || 0) - ($setup.fixed_pricing_department_distribution?.total_original_price || 0),
                      start_date: $setup.dates.computed.formattedStartDate.value,
                      end_date: $setup.dates.computed.formattedEndDate.value,
                      error: null
                    },
                    loading: $setup.fixed_pricing_department_distribution?.total_fixed_price === void 0 || $setup.fixed_pricing_department_distribution?.total_original_price === void 0,
                    icon: ($setup.fixed_pricing_department_distribution?.total_fixed_price || 0) - ($setup.fixed_pricing_department_distribution?.total_original_price || 0) >= 0 ? "fas fa-arrow-up" : "fas fa-arrow-down",
                    name: "Difference",
                    color: ($setup.fixed_pricing_department_distribution?.total_fixed_price || 0) - ($setup.fixed_pricing_department_distribution?.total_original_price || 0) >= 0 ? "black" : "danger",
                    "font-style": "oblique"
                  }, null, 8, ["force-display", "loading", "icon", "color"])
                ]),
                _: 1
                /* STABLE */
              })
            ]),
            createCommentVNode(" Fixed pricing distribution "),
            createBaseVNode("div", _hoisted_28$a, [
              createVNode($setup["WhiteBoxCard"], {
                "has-selection-style": true,
                "has-hover-effect": true,
                "has-border": true
              }, {
                default: withCtx(() => [
                  createCommentVNode(" Distribution for each department "),
                  createBaseVNode("div", _hoisted_29$9, [
                    createBaseVNode("table", _hoisted_30$9, [
                      createBaseVNode("thead", null, [
                        createBaseVNode("tr", null, [
                          _cache[19] || (_cache[19] = createBaseVNode(
                            "th",
                            null,
                            "Afdeling",
                            -1
                            /* CACHED */
                          )),
                          _cache[20] || (_cache[20] = createBaseVNode(
                            "th",
                            null,
                            "Original pris",
                            -1
                            /* CACHED */
                          )),
                          _cache[21] || (_cache[21] = createBaseVNode(
                            "th",
                            null,
                            "Faktisk pris",
                            -1
                            /* CACHED */
                          )),
                          _cache[22] || (_cache[22] = createBaseVNode(
                            "th",
                            null,
                            "Procent betalt ud fra original pris",
                            -1
                            /* CACHED */
                          )),
                          _cache[23] || (_cache[23] = createBaseVNode(
                            "th",
                            null,
                            "Procent tilsvarende bogført beløb",
                            -1
                            /* CACHED */
                          )),
                          createBaseVNode("th", null, [
                            _cache[18] || (_cache[18] = createTextVNode(
                              "Bogført beløb ",
                              -1
                              /* CACHED */
                            )),
                            createVNode($setup["BTooltip"], {
                              label: "Hentes fra e-conomic afdeling 75 og fordeles efter de bogførte fastprisaftale-linjer.",
                              type: "is-info"
                            }, {
                              default: withCtx(() => [..._cache[17] || (_cache[17] = [
                                createTextVNode(
                                  "?",
                                  -1
                                  /* CACHED */
                                )
                              ])]),
                              _: 1
                              /* STABLE */
                            })
                          ])
                        ])
                      ]),
                      createBaseVNode("tbody", null, [
                        $setup.fixed_pricing_department_distribution && ($setup.fixed_pricing_department_distribution.total_department_totals_parsed || $setup.fixed_pricing_department_distribution.total_department_totals_relative_parsed) ? (openBlock(), createElementBlock(
                          Fragment,
                          { key: 0 },
                          [
                            (openBlock(true), createElementBlock(
                              Fragment,
                              null,
                              renderList($setup.department75CombinedRows, (row) => {
                                return openBlock(), createElementBlock("tr", {
                                  key: `fixed-pricing-${row.department.id || row.department.name}`
                                }, [
                                  createBaseVNode(
                                    "td",
                                    null,
                                    toDisplayString(row.department.name),
                                    1
                                    /* TEXT */
                                  ),
                                  createBaseVNode(
                                    "td",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmountOrDash(row.fixedPricingOriginalAmount)),
                                    1
                                    /* TEXT */
                                  ),
                                  createBaseVNode(
                                    "td",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmountOrDash(row.fixedPricingActualAmount)),
                                    1
                                    /* TEXT */
                                  ),
                                  createBaseVNode(
                                    "td",
                                    null,
                                    toDisplayString(row.hasFixedPricingValues ? `${row.fixedPricingPaymentPercentage}%` : "-"),
                                    1
                                    /* TEXT */
                                  ),
                                  createBaseVNode(
                                    "td",
                                    null,
                                    toDisplayString(row.hasFixedPricingValues ? `${row.fixedPricingBookedPercentage}%` : "-"),
                                    1
                                    /* TEXT */
                                  ),
                                  createBaseVNode(
                                    "td",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmountOrDash(row.fixedPricingBookedAmount)),
                                    1
                                    /* TEXT */
                                  )
                                ]);
                              }),
                              128
                              /* KEYED_FRAGMENT */
                            )),
                            createCommentVNode(" Total row "),
                            $setup.fixed_pricing_department_distribution && $setup.fixed_pricing_department_distribution.total_original_price !== void 0 && $setup.fixed_pricing_department_distribution.total_fixed_price !== void 0 ? (openBlock(), createElementBlock("tr", _hoisted_31$9, [
                              _cache[24] || (_cache[24] = createBaseVNode(
                                "td",
                                null,
                                [
                                  createBaseVNode("strong", null, "Total")
                                ],
                                -1
                                /* CACHED */
                              )),
                              createBaseVNode("td", null, [
                                createBaseVNode(
                                  "strong",
                                  _hoisted_32$9,
                                  toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.fixedPricingOriginalAmount)),
                                  1
                                  /* TEXT */
                                )
                              ]),
                              createBaseVNode("td", null, [
                                createBaseVNode(
                                  "strong",
                                  null,
                                  toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.fixedPricingActualAmount)),
                                  1
                                  /* TEXT */
                                )
                              ]),
                              createBaseVNode("td", null, [
                                createBaseVNode(
                                  "strong",
                                  null,
                                  toDisplayString($setup.department75CombinedTotals.fixedPricingPaymentPercentage) + "%",
                                  1
                                  /* TEXT */
                                )
                              ]),
                              createBaseVNode("td", null, [
                                createBaseVNode(
                                  "strong",
                                  null,
                                  toDisplayString($setup.getPercentageOfTotal($setup.department75CombinedTotals.fixedPricingDistributedAmount, $setup.department75CombinedTotals.fixedPricingBookedAmount)) + "%",
                                  1
                                  /* TEXT */
                                )
                              ]),
                              createBaseVNode("td", null, [
                                createBaseVNode(
                                  "strong",
                                  null,
                                  toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.fixedPricingBookedAmount)) + " (Distributed: " + toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.fixedPricingDistributedAmount)) + ")",
                                  1
                                  /* TEXT */
                                )
                              ])
                            ])) : createCommentVNode("v-if", true)
                          ],
                          64
                          /* STABLE_FRAGMENT */
                        )) : (openBlock(), createElementBlock("tr", _hoisted_33$9, [..._cache[25] || (_cache[25] = [
                          createBaseVNode(
                            "td",
                            {
                              colspan: "6",
                              class: "has-text-centered"
                            },
                            [
                              createBaseVNode("span", { class: "icon is-large" }, [
                                createBaseVNode("i", { class: "fas fa-spinner fa-spin fa-2x" })
                              ]),
                              createBaseVNode("p", null, "Henter fordeling data...")
                            ],
                            -1
                            /* CACHED */
                          )
                        ])]))
                      ])
                    ])
                  ])
                ]),
                _: 1
                /* STABLE */
              })
            ])
          ],
          64
          /* STABLE_FRAGMENT */
        )) : createCommentVNode("v-if", true),
        createCommentVNode(" Vehicle subscription distribution view "),
        $setup.view.functions.isCurrentView("vehicle_subscriptions") ? (openBlock(), createElementBlock(
          Fragment,
          { key: 2 },
          [
            createCommentVNode(" Divider "),
            _cache[35] || (_cache[35] = createBaseVNode(
              "div",
              { class: "column is-full" },
              [
                createBaseVNode("div", { class: "divider" }, [
                  createBaseVNode("div", { class: "divider-text has-text-weight-bold" }, " Abonnementsfordeling ")
                ])
              ],
              -1
              /* CACHED */
            )),
            createCommentVNode(" Total vehicle subscription price "),
            createBaseVNode("div", _hoisted_34$9, [
              createVNode($setup["WhiteBoxCard"], {
                "has-selection-style": true,
                "has-hover-effect": true,
                "has-border": true
              }, {
                default: withCtx(() => [
                  createVNode($setup["StatisticsIncomeCard"], {
                    "force-display": {
                      value: $setup.vehicleSubscriptionDistribution?.total_subscription_price || 0,
                      start_date: $setup.dates.computed.formattedStartDate.value,
                      end_date: $setup.dates.computed.formattedEndDate.value,
                      error: null
                    },
                    loading: $setup.vehicleSubscriptionDistribution?.total_subscription_price === void 0,
                    icon: "fas fa-money-bill-wave",
                    name: "Total"
                  }, null, 8, ["force-display", "loading"])
                ]),
                _: 1
                /* STABLE */
              })
            ]),
            createCommentVNode(" Subscription price distribution for each department "),
            createBaseVNode("div", _hoisted_35$9, [
              createVNode($setup["WhiteBoxCard"], {
                "has-selection-style": true,
                "has-hover-effect": true,
                "has-border": true
              }, {
                default: withCtx(() => [
                  createBaseVNode("div", _hoisted_36$8, [
                    createBaseVNode("table", _hoisted_37$8, [
                      createBaseVNode("thead", null, [
                        createBaseVNode("tr", null, [
                          _cache[29] || (_cache[29] = createBaseVNode(
                            "th",
                            null,
                            "Afdeling",
                            -1
                            /* CACHED */
                          )),
                          _cache[30] || (_cache[30] = createBaseVNode(
                            "th",
                            null,
                            "Abonnementspris",
                            -1
                            /* CACHED */
                          )),
                          _cache[31] || (_cache[31] = createBaseVNode(
                            "th",
                            null,
                            "Procent af total abonnementspris",
                            -1
                            /* CACHED */
                          )),
                          createBaseVNode("th", null, [
                            _cache[28] || (_cache[28] = createTextVNode(
                              "Bogført beløb ",
                              -1
                              /* CACHED */
                            )),
                            createVNode($setup["BTooltip"], {
                              label: "Hentes fra e-conomic afdeling 75 og fordeles efter de bogførte vaskeabonnement-linjer.",
                              type: "is-info"
                            }, {
                              default: withCtx(() => [..._cache[27] || (_cache[27] = [
                                createTextVNode(
                                  "?",
                                  -1
                                  /* CACHED */
                                )
                              ])]),
                              _: 1
                              /* STABLE */
                            })
                          ])
                        ])
                      ]),
                      createBaseVNode("tbody", null, [
                        $setup.vehicleSubscriptionDistribution && $setup.vehicleSubscriptionDistribution.subscription_price_department_distribution_parsed ? (openBlock(), createElementBlock(
                          Fragment,
                          { key: 0 },
                          [
                            (openBlock(true), createElementBlock(
                              Fragment,
                              null,
                              renderList($setup.department75CombinedRows, (row) => {
                                return openBlock(), createElementBlock("tr", {
                                  key: `vehicle-subscription-${row.department.id || row.department.name}`
                                }, [
                                  createBaseVNode(
                                    "td",
                                    null,
                                    toDisplayString(row.department.name),
                                    1
                                    /* TEXT */
                                  ),
                                  createBaseVNode(
                                    "td",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmountOrDash(row.vehicleSubscriptionAmount)),
                                    1
                                    /* TEXT */
                                  ),
                                  createBaseVNode(
                                    "td",
                                    null,
                                    toDisplayString(row.hasVehicleSubscriptionValues ? `${$setup.getPercentageOfTotal(row.vehicleSubscriptionAmount, $setup.department75CombinedTotals.vehicleSubscriptionAmount)}%` : "-"),
                                    1
                                    /* TEXT */
                                  ),
                                  createBaseVNode(
                                    "td",
                                    null,
                                    toDisplayString($setup.formatCurrencyAmountOrDash(row.vehicleSubscriptionBookedAmount)),
                                    1
                                    /* TEXT */
                                  )
                                ]);
                              }),
                              128
                              /* KEYED_FRAGMENT */
                            )),
                            createCommentVNode(" Total row "),
                            $setup.vehicleSubscriptionDistribution && $setup.vehicleSubscriptionDistribution.total_subscription_price !== void 0 ? (openBlock(), createElementBlock("tr", _hoisted_38$8, [
                              _cache[32] || (_cache[32] = createBaseVNode(
                                "td",
                                null,
                                [
                                  createBaseVNode("strong", null, "Total")
                                ],
                                -1
                                /* CACHED */
                              )),
                              createBaseVNode("td", null, [
                                createBaseVNode(
                                  "strong",
                                  null,
                                  toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.vehicleSubscriptionAmount)),
                                  1
                                  /* TEXT */
                                )
                              ]),
                              _cache[33] || (_cache[33] = createBaseVNode(
                                "td",
                                null,
                                [
                                  createBaseVNode("strong", null, "100%")
                                ],
                                -1
                                /* CACHED */
                              )),
                              createBaseVNode("td", null, [
                                createBaseVNode(
                                  "strong",
                                  null,
                                  toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.vehicleSubscriptionBookedAmount)) + " (Distributed: " + toDisplayString($setup.formatCurrencyAmount($setup.department75CombinedTotals.vehicleSubscriptionDistributedAmount)) + ")",
                                  1
                                  /* TEXT */
                                )
                              ])
                            ])) : createCommentVNode("v-if", true)
                          ],
                          64
                          /* STABLE_FRAGMENT */
                        )) : (openBlock(), createElementBlock("tr", _hoisted_39$8, [..._cache[34] || (_cache[34] = [
                          createBaseVNode(
                            "td",
                            {
                              colspan: "4",
                              class: "has-text-centered"
                            },
                            [
                              createBaseVNode("span", { class: "icon is-large" }, [
                                createBaseVNode("i", { class: "fas fa-spinner fa-spin fa-2x" })
                              ]),
                              createBaseVNode("p", null, "Henter abonnementsfordeling data...")
                            ],
                            -1
                            /* CACHED */
                          )
                        ])]))
                      ])
                    ])
                  ])
                ]),
                _: 1
                /* STABLE */
              })
            ])
          ],
          64
          /* STABLE_FRAGMENT */
        )) : createCommentVNode("v-if", true)
      ])
    ],
    2112
    /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
  );
}
const InvoicingBillingPeriodStatistics = /* @__PURE__ */ _export_sfc(_sfc_main$1n, [["render", _sfc_render$P], ["__scopeId", "data-v-fc2b1821"], ["__file", "InvoicingBillingPeriodStatistics.vue"]]);

const _sfc_main$1m = /* @__PURE__ */ defineComponent({
  __name: "InvoicingBillingPeriodFilters",
  emits: {
    "filter-changed": (filters) => true
  },
  setup(__props, { expose: __expose, emit: __emit }) {
    __expose();
    const displayRequiresAction = ref(true);
    const displayBooked = ref(true);
    const displayStatistics = ref(false);
    const isCustomerVisible = (customer) => {
      if (!displayRequiresAction.value && customer.requires_action) {
        return false;
      }
      return !(!displayBooked.value && customer.requires_action === false && customer.transactions.every((t) => t.booked === true));
    };
    const emits = __emit;
    const emitFilters = () => {
      emits("filter-changed", {
        displayRequiresAction: displayRequiresAction.value,
        displayBooked: displayBooked.value,
        displayStatistics: displayStatistics.value,
        isCustomerVisible
      });
    };
    watch([displayRequiresAction, displayBooked, displayStatistics], () => {
      emitFilters();
    });
    emitFilters();
    const __returned__ = { displayRequiresAction, displayBooked, displayStatistics, isCustomerVisible, emits, emitFilters, ColorIndicator, SessionUser };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$H = { class: "columns is-mobile" };
const _hoisted_2$y = { class: "column" };
const _hoisted_3$u = { class: "tags" };
const _hoisted_4$u = { class: "tag" };
const _hoisted_5$t = { class: "tag" };
const _hoisted_6$t = { class: "tag" };
function _sfc_render$O(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock(
    Fragment,
    null,
    [
      createCommentVNode(" Filters for customer visibility "),
      createBaseVNode("div", _hoisted_1$H, [
        createBaseVNode("div", _hoisted_2$y, [
          createBaseVNode("div", _hoisted_3$u, [
            createBaseVNode("span", _hoisted_4$u, [
              createVNode($setup["ColorIndicator"], {
                color_class: $setup.displayRequiresAction ? "has-text-success" : "has-text-danger",
                dropdown_content: {
                  title: $setup.SessionUser.objects.global.language.show + " " + $setup.SessionUser.objects.global.language.requires_action.toLowerCase(),
                  buttons_title: "",
                  buttons: [],
                  content: [
                    {
                      text: $setup.SessionUser.objects.global.language.select,
                      action: () => {
                        $setup.displayRequiresAction = !$setup.displayRequiresAction;
                      },
                      icon: $setup.displayRequiresAction ? "fas fa-eye-slash" : "fas fa-eye",
                      classes: ["has-text-dark"],
                      button: true,
                      button_text: $setup.displayRequiresAction ? $setup.SessionUser.objects.global.language.hide : $setup.SessionUser.objects.global.language.show,
                      button_classes: ["has-text-dark"],
                      disabled: false,
                      v_centered: true
                    }
                  ]
                },
                label: {
                  text: $setup.SessionUser.objects.global.language.requires_action,
                  classes: [],
                  max_length: 30
                },
                is_loading: false
              }, null, 8, ["color_class", "dropdown_content", "label"])
            ]),
            createBaseVNode("span", _hoisted_5$t, [
              createVNode($setup["ColorIndicator"], {
                color_class: $setup.displayBooked ? "has-text-success" : "has-text-danger",
                dropdown_content: {
                  title: $setup.SessionUser.objects.global.language.show + " " + $setup.SessionUser.objects.global.language.booked.toLowerCase(),
                  buttons_title: "",
                  buttons: [],
                  content: [
                    {
                      text: $setup.SessionUser.objects.global.language.select,
                      action: () => {
                        $setup.displayBooked = !$setup.displayBooked;
                      },
                      icon: $setup.displayBooked ? "fas fa-eye-slash" : "fas fa-eye",
                      classes: ["has-text-dark"],
                      button: true,
                      button_text: $setup.displayBooked ? $setup.SessionUser.objects.global.language.hide : $setup.SessionUser.objects.global.language.show,
                      button_classes: ["has-text-dark"],
                      disabled: false,
                      v_centered: true
                    }
                  ]
                },
                label: {
                  text: $setup.SessionUser.objects.global.language.booked,
                  classes: [],
                  max_length: 30
                },
                is_loading: false
              }, null, 8, ["color_class", "dropdown_content", "label"])
            ]),
            createBaseVNode("span", _hoisted_6$t, [
              createVNode($setup["ColorIndicator"], {
                color_class: $setup.displayStatistics ? "has-text-success" : "has-text-danger",
                dropdown_content: {
                  title: $setup.SessionUser.objects.global.language.show + " " + $setup.SessionUser.objects.global.language.statistics.toLowerCase(),
                  buttons_title: "",
                  buttons: [],
                  content: [
                    {
                      text: $setup.SessionUser.objects.global.language.select,
                      action: () => {
                        $setup.displayStatistics = !$setup.displayStatistics;
                      },
                      icon: $setup.displayStatistics ? "fas fa-eye-slash" : "fas fa-eye",
                      classes: ["has-text-dark"],
                      button: true,
                      button_text: $setup.displayStatistics ? $setup.SessionUser.objects.global.language.hide : $setup.SessionUser.objects.global.language.show,
                      button_classes: ["has-text-dark"],
                      disabled: false,
                      v_centered: true
                    }
                  ]
                },
                label: {
                  text: $setup.SessionUser.objects.global.language.statistics,
                  classes: [],
                  max_length: 30
                },
                is_loading: false
              }, null, 8, ["color_class", "dropdown_content", "label"])
            ])
          ])
        ])
      ])
    ],
    2112
    /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
  );
}
const InvoicingBillingPeriodFilters = /* @__PURE__ */ _export_sfc(_sfc_main$1m, [["render", _sfc_render$O], ["__file", "InvoicingBillingPeriodFilters.vue"]]);

const _sfc_main$1l = /* @__PURE__ */ defineComponent({
  __name: "InvoicingBillingPeriodCustomerAttributes",
  props: {
    customer: {
      type: Object,
      required: true
    },
    isExpanded: {
      type: Boolean,
      default: false
    }
  },
  setup(__props, { expose: __expose }) {
    __expose();
    const props = __props;
    const sharedTypes = computed(() => view.variables.sharedVariables.value?.types ?? {});
    const view_keys = computed(() => {
      return Object.keys(sharedTypes.value);
    });
    const list_views_with_customer = computed(() => {
      return view_keys.value.filter((view_key) => {
        if (view_key === "all") return false;
        const view_type = sharedTypes.value[view_key];
        return view_type && view_type.some((v) => v.customer_number === props.customer.customer_number);
      });
    });
    const attributeCount = computed(() => list_views_with_customer.value.length);
    const attributeFontSize = computed(() => {
      if (attributeCount.value <= 1) return "0.75rem";
      if (attributeCount.value === 2) return "0.75rem";
      if (attributeCount.value === 3) return "0.72rem";
      return "0.65rem";
    });
    const attributeStackStyle = computed(() => ({
      "--customer-attribute-count": String(Math.max(attributeCount.value, 1)),
      "--customer-attribute-font-size": attributeFontSize.value
    }));
    const getAttributeTestId = (viewKey) => {
      return `invoicing-period-customer-attribute-${props.customer.customer_number}-${viewKey}`;
    };
    const __returned__ = { props, sharedTypes, view_keys, list_views_with_customer, attributeCount, attributeFontSize, attributeStackStyle, getAttributeTestId, view, ColorIndicator };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$G = ["data-testid"];
function _sfc_render$N(_ctx, _cache, $props, $setup, $data, $options) {
  return $setup.attributeCount > 0 ? (openBlock(), createElementBlock("div", {
    key: 0,
    class: "customer-attribute-stack",
    style: normalizeStyle($setup.attributeStackStyle),
    "data-testid": `invoicing-period-customer-attributes-${$props.customer.customer_number}`
  }, [
    (openBlock(true), createElementBlock(
      Fragment,
      null,
      renderList($setup.list_views_with_customer, (view_key) => {
        return openBlock(), createBlock($setup["ColorIndicator"], {
          key: view_key,
          visibility: { icon: false, dropdown: false },
          label: { text: $setup.view.computed.getViewFriendlyName(view_key), classes: [], max_length: 20 },
          is_button_hover_effect: true,
          class: "customer-attribute-text is-text is-not-clickable",
          "data-testid": $setup.getAttributeTestId(view_key),
          title: $setup.view.computed.getViewFriendlyName(view_key)
        }, null, 8, ["label", "data-testid", "title"]);
      }),
      128
      /* KEYED_FRAGMENT */
    ))
  ], 12, _hoisted_1$G)) : createCommentVNode("v-if", true);
}
const InvoicingBillingPeriodCustomerAttributes = /* @__PURE__ */ _export_sfc(_sfc_main$1l, [["render", _sfc_render$N], ["__scopeId", "data-v-21776a59"], ["__file", "InvoicingBillingPeriodCustomerAttributes.vue"]]);

var top = 'top';
var bottom = 'bottom';
var right = 'right';
var left = 'left';
var auto = 'auto';
var basePlacements = [top, bottom, right, left];
var start = 'start';
var end = 'end';
var clippingParents = 'clippingParents';
var viewport = 'viewport';
var popper$1 = 'popper';
var reference = 'reference';
var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
  return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {
  return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []); // modifiers that need to read the DOM

var beforeRead = 'beforeRead';
var read = 'read';
var afterRead = 'afterRead'; // pure-logic modifiers

var beforeMain = 'beforeMain';
var main = 'main';
var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)

var beforeWrite = 'beforeWrite';
var write = 'write';
var afterWrite = 'afterWrite';
var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];

function getNodeName(element) {
  return element ? (element.nodeName || '').toLowerCase() : null;
}

function getWindow(node) {
  if (node == null) {
    return window;
  }

  if (node.toString() !== '[object Window]') {
    var ownerDocument = node.ownerDocument;
    return ownerDocument ? ownerDocument.defaultView || window : window;
  }

  return node;
}

function isElement(node) {
  var OwnElement = getWindow(node).Element;
  return node instanceof OwnElement || node instanceof Element;
}

function isHTMLElement(node) {
  var OwnElement = getWindow(node).HTMLElement;
  return node instanceof OwnElement || node instanceof HTMLElement;
}

function isShadowRoot(node) {
  // IE 11 has no ShadowRoot
  if (typeof ShadowRoot === 'undefined') {
    return false;
  }

  var OwnElement = getWindow(node).ShadowRoot;
  return node instanceof OwnElement || node instanceof ShadowRoot;
}

// and applies them to the HTMLElements such as popper and arrow

function applyStyles(_ref) {
  var state = _ref.state;
  Object.keys(state.elements).forEach(function (name) {
    var style = state.styles[name] || {};
    var attributes = state.attributes[name] || {};
    var element = state.elements[name]; // arrow is optional + virtual elements

    if (!isHTMLElement(element) || !getNodeName(element)) {
      return;
    } // Flow doesn't support to extend this property, but it's the most
    // effective way to apply styles to an HTMLElement
    // $FlowFixMe[cannot-write]


    Object.assign(element.style, style);
    Object.keys(attributes).forEach(function (name) {
      var value = attributes[name];

      if (value === false) {
        element.removeAttribute(name);
      } else {
        element.setAttribute(name, value === true ? '' : value);
      }
    });
  });
}

function effect$2(_ref2) {
  var state = _ref2.state;
  var initialStyles = {
    popper: {
      position: state.options.strategy,
      left: '0',
      top: '0',
      margin: '0'
    },
    arrow: {
      position: 'absolute'
    },
    reference: {}
  };
  Object.assign(state.elements.popper.style, initialStyles.popper);
  state.styles = initialStyles;

  if (state.elements.arrow) {
    Object.assign(state.elements.arrow.style, initialStyles.arrow);
  }

  return function () {
    Object.keys(state.elements).forEach(function (name) {
      var element = state.elements[name];
      var attributes = state.attributes[name] || {};
      var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them

      var style = styleProperties.reduce(function (style, property) {
        style[property] = '';
        return style;
      }, {}); // arrow is optional + virtual elements

      if (!isHTMLElement(element) || !getNodeName(element)) {
        return;
      }

      Object.assign(element.style, style);
      Object.keys(attributes).forEach(function (attribute) {
        element.removeAttribute(attribute);
      });
    });
  };
} // eslint-disable-next-line import/no-unused-modules


const applyStyles$1 = {
  name: 'applyStyles',
  enabled: true,
  phase: 'write',
  fn: applyStyles,
  effect: effect$2,
  requires: ['computeStyles']
};

function getBasePlacement(placement) {
  return placement.split('-')[0];
}

var max = Math.max;
var min = Math.min;
var round = Math.round;

function getUAString() {
  var uaData = navigator.userAgentData;

  if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {
    return uaData.brands.map(function (item) {
      return item.brand + "/" + item.version;
    }).join(' ');
  }

  return navigator.userAgent;
}

function isLayoutViewport() {
  return !/^((?!chrome|android).)*safari/i.test(getUAString());
}

function getBoundingClientRect(element, includeScale, isFixedStrategy) {
  if (includeScale === void 0) {
    includeScale = false;
  }

  if (isFixedStrategy === void 0) {
    isFixedStrategy = false;
  }

  var clientRect = element.getBoundingClientRect();
  var scaleX = 1;
  var scaleY = 1;

  if (includeScale && isHTMLElement(element)) {
    scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;
    scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;
  }

  var _ref = isElement(element) ? getWindow(element) : window,
      visualViewport = _ref.visualViewport;

  var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
  var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
  var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
  var width = clientRect.width / scaleX;
  var height = clientRect.height / scaleY;
  return {
    width: width,
    height: height,
    top: y,
    right: x + width,
    bottom: y + height,
    left: x,
    x: x,
    y: y
  };
}

// means it doesn't take into account transforms.

function getLayoutRect(element) {
  var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.
  // Fixes https://github.com/popperjs/popper-core/issues/1223

  var width = element.offsetWidth;
  var height = element.offsetHeight;

  if (Math.abs(clientRect.width - width) <= 1) {
    width = clientRect.width;
  }

  if (Math.abs(clientRect.height - height) <= 1) {
    height = clientRect.height;
  }

  return {
    x: element.offsetLeft,
    y: element.offsetTop,
    width: width,
    height: height
  };
}

function contains(parent, child) {
  var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method

  if (parent.contains(child)) {
    return true;
  } // then fallback to custom implementation with Shadow DOM support
  else if (rootNode && isShadowRoot(rootNode)) {
      var next = child;

      do {
        if (next && parent.isSameNode(next)) {
          return true;
        } // $FlowFixMe[prop-missing]: need a better way to handle this...


        next = next.parentNode || next.host;
      } while (next);
    } // Give up, the result is false


  return false;
}

function getComputedStyle$1(element) {
  return getWindow(element).getComputedStyle(element);
}

function isTableElement(element) {
  return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
}

function getDocumentElement(element) {
  // $FlowFixMe[incompatible-return]: assume body is always available
  return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]
  element.document) || window.document).documentElement;
}

function getParentNode(element) {
  if (getNodeName(element) === 'html') {
    return element;
  }

  return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle
    // $FlowFixMe[incompatible-return]
    // $FlowFixMe[prop-missing]
    element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
    element.parentNode || ( // DOM Element detected
    isShadowRoot(element) ? element.host : null) || // ShadowRoot detected
    // $FlowFixMe[incompatible-call]: HTMLElement is a Node
    getDocumentElement(element) // fallback

  );
}

function getTrueOffsetParent(element) {
  if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837
  getComputedStyle$1(element).position === 'fixed') {
    return null;
  }

  return element.offsetParent;
} // `.offsetParent` reports `null` for fixed elements, while absolute elements
// return the containing block


function getContainingBlock(element) {
  var isFirefox = /firefox/i.test(getUAString());
  var isIE = /Trident/i.test(getUAString());

  if (isIE && isHTMLElement(element)) {
    // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport
    var elementCss = getComputedStyle$1(element);

    if (elementCss.position === 'fixed') {
      return null;
    }
  }

  var currentNode = getParentNode(element);

  if (isShadowRoot(currentNode)) {
    currentNode = currentNode.host;
  }

  while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {
    var css = getComputedStyle$1(currentNode); // This is non-exhaustive but covers the most common CSS properties that
    // create a containing block.
    // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block

    if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {
      return currentNode;
    } else {
      currentNode = currentNode.parentNode;
    }
  }

  return null;
} // Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.


function getOffsetParent(element) {
  var window = getWindow(element);
  var offsetParent = getTrueOffsetParent(element);

  while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') {
    offsetParent = getTrueOffsetParent(offsetParent);
  }

  if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static')) {
    return window;
  }

  return offsetParent || getContainingBlock(element) || window;
}

function getMainAxisFromPlacement(placement) {
  return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';
}

function within(min$1, value, max$1) {
  return max(min$1, min(value, max$1));
}
function withinMaxClamp(min, value, max) {
  var v = within(min, value, max);
  return v > max ? max : v;
}

function getFreshSideObject() {
  return {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  };
}

function mergePaddingObject(paddingObject) {
  return Object.assign({}, getFreshSideObject(), paddingObject);
}

function expandToHashMap(value, keys) {
  return keys.reduce(function (hashMap, key) {
    hashMap[key] = value;
    return hashMap;
  }, {});
}

var toPaddingObject = function toPaddingObject(padding, state) {
  padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {
    placement: state.placement
  })) : padding;
  return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
};

function arrow(_ref) {
  var _state$modifiersData$;

  var state = _ref.state,
      name = _ref.name,
      options = _ref.options;
  var arrowElement = state.elements.arrow;
  var popperOffsets = state.modifiersData.popperOffsets;
  var basePlacement = getBasePlacement(state.placement);
  var axis = getMainAxisFromPlacement(basePlacement);
  var isVertical = [left, right].indexOf(basePlacement) >= 0;
  var len = isVertical ? 'height' : 'width';

  if (!arrowElement || !popperOffsets) {
    return;
  }

  var paddingObject = toPaddingObject(options.padding, state);
  var arrowRect = getLayoutRect(arrowElement);
  var minProp = axis === 'y' ? top : left;
  var maxProp = axis === 'y' ? bottom : right;
  var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
  var startDiff = popperOffsets[axis] - state.rects.reference[axis];
  var arrowOffsetParent = getOffsetParent(arrowElement);
  var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
  var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
  // outside of the popper bounds

  var min = paddingObject[minProp];
  var max = clientSize - arrowRect[len] - paddingObject[maxProp];
  var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
  var offset = within(min, center, max); // Prevents breaking syntax highlighting...

  var axisProp = axis;
  state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
}

function effect$1(_ref2) {
  var state = _ref2.state,
      options = _ref2.options;
  var _options$element = options.element,
      arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;

  if (arrowElement == null) {
    return;
  } // CSS selector


  if (typeof arrowElement === 'string') {
    arrowElement = state.elements.popper.querySelector(arrowElement);

    if (!arrowElement) {
      return;
    }
  }

  if (!contains(state.elements.popper, arrowElement)) {
    return;
  }

  state.elements.arrow = arrowElement;
} // eslint-disable-next-line import/no-unused-modules


const arrow$1 = {
  name: 'arrow',
  enabled: true,
  phase: 'main',
  fn: arrow,
  effect: effect$1,
  requires: ['popperOffsets'],
  requiresIfExists: ['preventOverflow']
};

function getVariation(placement) {
  return placement.split('-')[1];
}

var unsetSides = {
  top: 'auto',
  right: 'auto',
  bottom: 'auto',
  left: 'auto'
}; // Round the offsets to the nearest suitable subpixel based on the DPR.
// Zooming can change the DPR, but it seems to report a value that will
// cleanly divide the values into the appropriate subpixels.

function roundOffsetsByDPR(_ref, win) {
  var x = _ref.x,
      y = _ref.y;
  var dpr = win.devicePixelRatio || 1;
  return {
    x: round(x * dpr) / dpr || 0,
    y: round(y * dpr) / dpr || 0
  };
}

function mapToStyles(_ref2) {
  var _Object$assign2;

  var popper = _ref2.popper,
      popperRect = _ref2.popperRect,
      placement = _ref2.placement,
      variation = _ref2.variation,
      offsets = _ref2.offsets,
      position = _ref2.position,
      gpuAcceleration = _ref2.gpuAcceleration,
      adaptive = _ref2.adaptive,
      roundOffsets = _ref2.roundOffsets,
      isFixed = _ref2.isFixed;
  var _offsets$x = offsets.x,
      x = _offsets$x === void 0 ? 0 : _offsets$x,
      _offsets$y = offsets.y,
      y = _offsets$y === void 0 ? 0 : _offsets$y;

  var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({
    x: x,
    y: y
  }) : {
    x: x,
    y: y
  };

  x = _ref3.x;
  y = _ref3.y;
  var hasX = offsets.hasOwnProperty('x');
  var hasY = offsets.hasOwnProperty('y');
  var sideX = left;
  var sideY = top;
  var win = window;

  if (adaptive) {
    var offsetParent = getOffsetParent(popper);
    var heightProp = 'clientHeight';
    var widthProp = 'clientWidth';

    if (offsetParent === getWindow(popper)) {
      offsetParent = getDocumentElement(popper);

      if (getComputedStyle$1(offsetParent).position !== 'static' && position === 'absolute') {
        heightProp = 'scrollHeight';
        widthProp = 'scrollWidth';
      }
    } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it


    offsetParent = offsetParent;

    if (placement === top || (placement === left || placement === right) && variation === end) {
      sideY = bottom;
      var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]
      offsetParent[heightProp];
      y -= offsetY - popperRect.height;
      y *= gpuAcceleration ? 1 : -1;
    }

    if (placement === left || (placement === top || placement === bottom) && variation === end) {
      sideX = right;
      var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]
      offsetParent[widthProp];
      x -= offsetX - popperRect.width;
      x *= gpuAcceleration ? 1 : -1;
    }
  }

  var commonStyles = Object.assign({
    position: position
  }, adaptive && unsetSides);

  var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
    x: x,
    y: y
  }, getWindow(popper)) : {
    x: x,
    y: y
  };

  x = _ref4.x;
  y = _ref4.y;

  if (gpuAcceleration) {
    var _Object$assign;

    return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
  }

  return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
}

function computeStyles(_ref5) {
  var state = _ref5.state,
      options = _ref5.options;
  var _options$gpuAccelerat = options.gpuAcceleration,
      gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
      _options$adaptive = options.adaptive,
      adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
      _options$roundOffsets = options.roundOffsets,
      roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
  var commonStyles = {
    placement: getBasePlacement(state.placement),
    variation: getVariation(state.placement),
    popper: state.elements.popper,
    popperRect: state.rects.popper,
    gpuAcceleration: gpuAcceleration,
    isFixed: state.options.strategy === 'fixed'
  };

  if (state.modifiersData.popperOffsets != null) {
    state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.popperOffsets,
      position: state.options.strategy,
      adaptive: adaptive,
      roundOffsets: roundOffsets
    })));
  }

  if (state.modifiersData.arrow != null) {
    state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.arrow,
      position: 'absolute',
      adaptive: false,
      roundOffsets: roundOffsets
    })));
  }

  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    'data-popper-placement': state.placement
  });
} // eslint-disable-next-line import/no-unused-modules


const computeStyles$1 = {
  name: 'computeStyles',
  enabled: true,
  phase: 'beforeWrite',
  fn: computeStyles,
  data: {}
};

var passive = {
  passive: true
};

function effect(_ref) {
  var state = _ref.state,
      instance = _ref.instance,
      options = _ref.options;
  var _options$scroll = options.scroll,
      scroll = _options$scroll === void 0 ? true : _options$scroll,
      _options$resize = options.resize,
      resize = _options$resize === void 0 ? true : _options$resize;
  var window = getWindow(state.elements.popper);
  var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);

  if (scroll) {
    scrollParents.forEach(function (scrollParent) {
      scrollParent.addEventListener('scroll', instance.update, passive);
    });
  }

  if (resize) {
    window.addEventListener('resize', instance.update, passive);
  }

  return function () {
    if (scroll) {
      scrollParents.forEach(function (scrollParent) {
        scrollParent.removeEventListener('scroll', instance.update, passive);
      });
    }

    if (resize) {
      window.removeEventListener('resize', instance.update, passive);
    }
  };
} // eslint-disable-next-line import/no-unused-modules


const eventListeners = {
  name: 'eventListeners',
  enabled: true,
  phase: 'write',
  fn: function fn() {},
  effect: effect,
  data: {}
};

var hash$1 = {
  left: 'right',
  right: 'left',
  bottom: 'top',
  top: 'bottom'
};
function getOppositePlacement(placement) {
  return placement.replace(/left|right|bottom|top/g, function (matched) {
    return hash$1[matched];
  });
}

var hash = {
  start: 'end',
  end: 'start'
};
function getOppositeVariationPlacement(placement) {
  return placement.replace(/start|end/g, function (matched) {
    return hash[matched];
  });
}

function getWindowScroll(node) {
  var win = getWindow(node);
  var scrollLeft = win.pageXOffset;
  var scrollTop = win.pageYOffset;
  return {
    scrollLeft: scrollLeft,
    scrollTop: scrollTop
  };
}

function getWindowScrollBarX(element) {
  // If <html> has a CSS width greater than the viewport, then this will be
  // incorrect for RTL.
  // Popper 1 is broken in this case and never had a bug report so let's assume
  // it's not an issue. I don't think anyone ever specifies width on <html>
  // anyway.
  // Browsers where the left scrollbar doesn't cause an issue report `0` for
  // this (e.g. Edge 2019, IE11, Safari)
  return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}

function getViewportRect(element, strategy) {
  var win = getWindow(element);
  var html = getDocumentElement(element);
  var visualViewport = win.visualViewport;
  var width = html.clientWidth;
  var height = html.clientHeight;
  var x = 0;
  var y = 0;

  if (visualViewport) {
    width = visualViewport.width;
    height = visualViewport.height;
    var layoutViewport = isLayoutViewport();

    if (layoutViewport || !layoutViewport && strategy === 'fixed') {
      x = visualViewport.offsetLeft;
      y = visualViewport.offsetTop;
    }
  }

  return {
    width: width,
    height: height,
    x: x + getWindowScrollBarX(element),
    y: y
  };
}

// of the `<html>` and `<body>` rect bounds if horizontally scrollable

function getDocumentRect(element) {
  var _element$ownerDocumen;

  var html = getDocumentElement(element);
  var winScroll = getWindowScroll(element);
  var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
  var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
  var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
  var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
  var y = -winScroll.scrollTop;

  if (getComputedStyle$1(body || html).direction === 'rtl') {
    x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
  }

  return {
    width: width,
    height: height,
    x: x,
    y: y
  };
}

function isScrollParent(element) {
  // Firefox wants us to check `-x` and `-y` variations as well
  var _getComputedStyle = getComputedStyle$1(element),
      overflow = _getComputedStyle.overflow,
      overflowX = _getComputedStyle.overflowX,
      overflowY = _getComputedStyle.overflowY;

  return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}

function getScrollParent(node) {
  if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
    // $FlowFixMe[incompatible-return]: assume body is always available
    return node.ownerDocument.body;
  }

  if (isHTMLElement(node) && isScrollParent(node)) {
    return node;
  }

  return getScrollParent(getParentNode(node));
}

/*
given a DOM element, return the list of all scroll parents, up the list of ancesors
until we get to the top window object. This list is what we attach scroll listeners
to, because if any of these parent elements scroll, we'll need to re-calculate the
reference element's position.
*/

function listScrollParents(element, list) {
  var _element$ownerDocumen;

  if (list === void 0) {
    list = [];
  }

  var scrollParent = getScrollParent(element);
  var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
  var win = getWindow(scrollParent);
  var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
  var updatedList = list.concat(target);
  return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
  updatedList.concat(listScrollParents(getParentNode(target)));
}

function rectToClientRect(rect) {
  return Object.assign({}, rect, {
    left: rect.x,
    top: rect.y,
    right: rect.x + rect.width,
    bottom: rect.y + rect.height
  });
}

function getInnerBoundingClientRect(element, strategy) {
  var rect = getBoundingClientRect(element, false, strategy === 'fixed');
  rect.top = rect.top + element.clientTop;
  rect.left = rect.left + element.clientLeft;
  rect.bottom = rect.top + element.clientHeight;
  rect.right = rect.left + element.clientWidth;
  rect.width = element.clientWidth;
  rect.height = element.clientHeight;
  rect.x = rect.left;
  rect.y = rect.top;
  return rect;
}

function getClientRectFromMixedType(element, clippingParent, strategy) {
  return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
} // A "clipping parent" is an overflowable container with the characteristic of
// clipping (or hiding) overflowing elements with a position different from
// `initial`


function getClippingParents(element) {
  var clippingParents = listScrollParents(getParentNode(element));
  var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle$1(element).position) >= 0;
  var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;

  if (!isElement(clipperElement)) {
    return [];
  } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414


  return clippingParents.filter(function (clippingParent) {
    return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';
  });
} // Gets the maximum area that the element is visible in due to any number of
// clipping parents


function getClippingRect(element, boundary, rootBoundary, strategy) {
  var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
  var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
  var firstClippingParent = clippingParents[0];
  var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
    var rect = getClientRectFromMixedType(element, clippingParent, 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;
  }, getClientRectFromMixedType(element, firstClippingParent, strategy));
  clippingRect.width = clippingRect.right - clippingRect.left;
  clippingRect.height = clippingRect.bottom - clippingRect.top;
  clippingRect.x = clippingRect.left;
  clippingRect.y = clippingRect.top;
  return clippingRect;
}

function computeOffsets(_ref) {
  var reference = _ref.reference,
      element = _ref.element,
      placement = _ref.placement;
  var basePlacement = placement ? getBasePlacement(placement) : null;
  var variation = placement ? getVariation(placement) : null;
  var commonX = reference.x + reference.width / 2 - element.width / 2;
  var commonY = reference.y + reference.height / 2 - element.height / 2;
  var offsets;

  switch (basePlacement) {
    case top:
      offsets = {
        x: commonX,
        y: reference.y - element.height
      };
      break;

    case bottom:
      offsets = {
        x: commonX,
        y: reference.y + reference.height
      };
      break;

    case right:
      offsets = {
        x: reference.x + reference.width,
        y: commonY
      };
      break;

    case left:
      offsets = {
        x: reference.x - element.width,
        y: commonY
      };
      break;

    default:
      offsets = {
        x: reference.x,
        y: reference.y
      };
  }

  var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;

  if (mainAxis != null) {
    var len = mainAxis === 'y' ? 'height' : 'width';

    switch (variation) {
      case start:
        offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
        break;

      case end:
        offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
        break;

      default:
    }
  }

  return offsets;
}

function detectOverflow(state, options) {
  if (options === void 0) {
    options = {};
  }

  var _options = options,
      _options$placement = _options.placement,
      placement = _options$placement === void 0 ? state.placement : _options$placement,
      _options$strategy = _options.strategy,
      strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,
      _options$boundary = _options.boundary,
      boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,
      _options$rootBoundary = _options.rootBoundary,
      rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,
      _options$elementConte = _options.elementContext,
      elementContext = _options$elementConte === void 0 ? popper$1 : _options$elementConte,
      _options$altBoundary = _options.altBoundary,
      altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,
      _options$padding = _options.padding,
      padding = _options$padding === void 0 ? 0 : _options$padding;
  var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
  var altContext = elementContext === popper$1 ? reference : popper$1;
  var popperRect = state.rects.popper;
  var element = state.elements[altBoundary ? altContext : elementContext];
  var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);
  var referenceClientRect = getBoundingClientRect(state.elements.reference);
  var popperOffsets = computeOffsets({
    reference: referenceClientRect,
    element: popperRect,
    strategy: 'absolute',
    placement: placement
  });
  var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));
  var elementClientRect = elementContext === popper$1 ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect
  // 0 or negative = within the clipping rect

  var overflowOffsets = {
    top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
    bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
    left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
    right: elementClientRect.right - clippingClientRect.right + paddingObject.right
  };
  var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element

  if (elementContext === popper$1 && offsetData) {
    var offset = offsetData[placement];
    Object.keys(overflowOffsets).forEach(function (key) {
      var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
      var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';
      overflowOffsets[key] += offset[axis] * multiply;
    });
  }

  return overflowOffsets;
}

function computeAutoPlacement(state, options) {
  if (options === void 0) {
    options = {};
  }

  var _options = options,
      placement = _options.placement,
      boundary = _options.boundary,
      rootBoundary = _options.rootBoundary,
      padding = _options.padding,
      flipVariations = _options.flipVariations,
      _options$allowedAutoP = _options.allowedAutoPlacements,
      allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
  var variation = getVariation(placement);
  var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {
    return getVariation(placement) === variation;
  }) : basePlacements;
  var allowedPlacements = placements$1.filter(function (placement) {
    return allowedAutoPlacements.indexOf(placement) >= 0;
  });

  if (allowedPlacements.length === 0) {
    allowedPlacements = placements$1;
  } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...


  var overflows = allowedPlacements.reduce(function (acc, placement) {
    acc[placement] = detectOverflow(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      padding: padding
    })[getBasePlacement(placement)];
    return acc;
  }, {});
  return Object.keys(overflows).sort(function (a, b) {
    return overflows[a] - overflows[b];
  });
}

function getExpandedFallbackPlacements(placement) {
  if (getBasePlacement(placement) === auto) {
    return [];
  }

  var oppositePlacement = getOppositePlacement(placement);
  return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}

function flip(_ref) {
  var state = _ref.state,
      options = _ref.options,
      name = _ref.name;

  if (state.modifiersData[name]._skip) {
    return;
  }

  var _options$mainAxis = options.mainAxis,
      checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
      _options$altAxis = options.altAxis,
      checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
      specifiedFallbackPlacements = options.fallbackPlacements,
      padding = options.padding,
      boundary = options.boundary,
      rootBoundary = options.rootBoundary,
      altBoundary = options.altBoundary,
      _options$flipVariatio = options.flipVariations,
      flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
      allowedAutoPlacements = options.allowedAutoPlacements;
  var preferredPlacement = state.options.placement;
  var basePlacement = getBasePlacement(preferredPlacement);
  var isBasePlacement = basePlacement === preferredPlacement;
  var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
  var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
    return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      padding: padding,
      flipVariations: flipVariations,
      allowedAutoPlacements: allowedAutoPlacements
    }) : placement);
  }, []);
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var checksMap = new Map();
  var makeFallbackChecks = true;
  var firstFittingPlacement = placements[0];

  for (var i = 0; i < placements.length; i++) {
    var placement = placements[i];

    var _basePlacement = getBasePlacement(placement);

    var isStartVariation = getVariation(placement) === start;
    var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
    var len = isVertical ? 'width' : 'height';
    var overflow = detectOverflow(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      altBoundary: altBoundary,
      padding: padding
    });
    var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;

    if (referenceRect[len] > popperRect[len]) {
      mainVariationSide = getOppositePlacement(mainVariationSide);
    }

    var altVariationSide = getOppositePlacement(mainVariationSide);
    var checks = [];

    if (checkMainAxis) {
      checks.push(overflow[_basePlacement] <= 0);
    }

    if (checkAltAxis) {
      checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
    }

    if (checks.every(function (check) {
      return check;
    })) {
      firstFittingPlacement = placement;
      makeFallbackChecks = false;
      break;
    }

    checksMap.set(placement, checks);
  }

  if (makeFallbackChecks) {
    // `2` may be desired in some cases – research later
    var numberOfChecks = flipVariations ? 3 : 1;

    var _loop = function _loop(_i) {
      var fittingPlacement = placements.find(function (placement) {
        var checks = checksMap.get(placement);

        if (checks) {
          return checks.slice(0, _i).every(function (check) {
            return check;
          });
        }
      });

      if (fittingPlacement) {
        firstFittingPlacement = fittingPlacement;
        return "break";
      }
    };

    for (var _i = numberOfChecks; _i > 0; _i--) {
      var _ret = _loop(_i);

      if (_ret === "break") break;
    }
  }

  if (state.placement !== firstFittingPlacement) {
    state.modifiersData[name]._skip = true;
    state.placement = firstFittingPlacement;
    state.reset = true;
  }
} // eslint-disable-next-line import/no-unused-modules


const flip$1 = {
  name: 'flip',
  enabled: true,
  phase: 'main',
  fn: flip,
  requiresIfExists: ['offset'],
  data: {
    _skip: false
  }
};

function getSideOffsets(overflow, rect, preventedOffsets) {
  if (preventedOffsets === void 0) {
    preventedOffsets = {
      x: 0,
      y: 0
    };
  }

  return {
    top: overflow.top - rect.height - preventedOffsets.y,
    right: overflow.right - rect.width + preventedOffsets.x,
    bottom: overflow.bottom - rect.height + preventedOffsets.y,
    left: overflow.left - rect.width - preventedOffsets.x
  };
}

function isAnySideFullyClipped(overflow) {
  return [top, right, bottom, left].some(function (side) {
    return overflow[side] >= 0;
  });
}

function hide(_ref) {
  var state = _ref.state,
      name = _ref.name;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var preventedOffsets = state.modifiersData.preventOverflow;
  var referenceOverflow = detectOverflow(state, {
    elementContext: 'reference'
  });
  var popperAltOverflow = detectOverflow(state, {
    altBoundary: true
  });
  var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
  var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
  var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
  var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
  state.modifiersData[name] = {
    referenceClippingOffsets: referenceClippingOffsets,
    popperEscapeOffsets: popperEscapeOffsets,
    isReferenceHidden: isReferenceHidden,
    hasPopperEscaped: hasPopperEscaped
  };
  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    'data-popper-reference-hidden': isReferenceHidden,
    'data-popper-escaped': hasPopperEscaped
  });
} // eslint-disable-next-line import/no-unused-modules


const hide$1 = {
  name: 'hide',
  enabled: true,
  phase: 'main',
  requiresIfExists: ['preventOverflow'],
  fn: hide
};

function distanceAndSkiddingToXY(placement, rects, offset) {
  var basePlacement = getBasePlacement(placement);
  var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;

  var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {
    placement: placement
  })) : offset,
      skidding = _ref[0],
      distance = _ref[1];

  skidding = skidding || 0;
  distance = (distance || 0) * invertDistance;
  return [left, right].indexOf(basePlacement) >= 0 ? {
    x: distance,
    y: skidding
  } : {
    x: skidding,
    y: distance
  };
}

function offset(_ref2) {
  var state = _ref2.state,
      options = _ref2.options,
      name = _ref2.name;
  var _options$offset = options.offset,
      offset = _options$offset === void 0 ? [0, 0] : _options$offset;
  var data = placements.reduce(function (acc, placement) {
    acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);
    return acc;
  }, {});
  var _data$state$placement = data[state.placement],
      x = _data$state$placement.x,
      y = _data$state$placement.y;

  if (state.modifiersData.popperOffsets != null) {
    state.modifiersData.popperOffsets.x += x;
    state.modifiersData.popperOffsets.y += y;
  }

  state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules


const offset$1 = {
  name: 'offset',
  enabled: true,
  phase: 'main',
  requires: ['popperOffsets'],
  fn: offset
};

function popperOffsets(_ref) {
  var state = _ref.state,
      name = _ref.name;
  // Offsets are the actual position the popper needs to have to be
  // properly positioned near its reference element
  // This is the most basic placement, and will be adjusted by
  // the modifiers in the next step
  state.modifiersData[name] = computeOffsets({
    reference: state.rects.reference,
    element: state.rects.popper,
    strategy: 'absolute',
    placement: state.placement
  });
} // eslint-disable-next-line import/no-unused-modules


const popperOffsets$1 = {
  name: 'popperOffsets',
  enabled: true,
  phase: 'read',
  fn: popperOffsets,
  data: {}
};

function getAltAxis(axis) {
  return axis === 'x' ? 'y' : 'x';
}

function preventOverflow(_ref) {
  var state = _ref.state,
      options = _ref.options,
      name = _ref.name;
  var _options$mainAxis = options.mainAxis,
      checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
      _options$altAxis = options.altAxis,
      checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,
      boundary = options.boundary,
      rootBoundary = options.rootBoundary,
      altBoundary = options.altBoundary,
      padding = options.padding,
      _options$tether = options.tether,
      tether = _options$tether === void 0 ? true : _options$tether,
      _options$tetherOffset = options.tetherOffset,
      tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
  var overflow = detectOverflow(state, {
    boundary: boundary,
    rootBoundary: rootBoundary,
    padding: padding,
    altBoundary: altBoundary
  });
  var basePlacement = getBasePlacement(state.placement);
  var variation = getVariation(state.placement);
  var isBasePlacement = !variation;
  var mainAxis = getMainAxisFromPlacement(basePlacement);
  var altAxis = getAltAxis(mainAxis);
  var popperOffsets = state.modifiersData.popperOffsets;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {
    placement: state.placement
  })) : tetherOffset;
  var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {
    mainAxis: tetherOffsetValue,
    altAxis: tetherOffsetValue
  } : Object.assign({
    mainAxis: 0,
    altAxis: 0
  }, tetherOffsetValue);
  var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
  var data = {
    x: 0,
    y: 0
  };

  if (!popperOffsets) {
    return;
  }

  if (checkMainAxis) {
    var _offsetModifierState$;

    var mainSide = mainAxis === 'y' ? top : left;
    var altSide = mainAxis === 'y' ? bottom : right;
    var len = mainAxis === 'y' ? 'height' : 'width';
    var offset = popperOffsets[mainAxis];
    var min$1 = offset + overflow[mainSide];
    var max$1 = offset - overflow[altSide];
    var additive = tether ? -popperRect[len] / 2 : 0;
    var minLen = variation === start ? referenceRect[len] : popperRect[len];
    var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go
    // outside the reference bounds

    var arrowElement = state.elements.arrow;
    var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
      width: 0,
      height: 0
    };
    var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();
    var arrowPaddingMin = arrowPaddingObject[mainSide];
    var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want
    // to include its full size in the calculation. If the reference is small
    // and near the edge of a boundary, the popper can overflow even if the
    // reference is not overflowing as well (e.g. virtual elements with no
    // width or height)

    var arrowLen = within(0, referenceRect[len], arrowRect[len]);
    var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
    var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
    var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
    var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
    var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
    var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;
    var tetherMax = offset + maxOffset - offsetModifierValue;
    var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1);
    popperOffsets[mainAxis] = preventedOffset;
    data[mainAxis] = preventedOffset - offset;
  }

  if (checkAltAxis) {
    var _offsetModifierState$2;

    var _mainSide = mainAxis === 'x' ? top : left;

    var _altSide = mainAxis === 'x' ? bottom : right;

    var _offset = popperOffsets[altAxis];

    var _len = altAxis === 'y' ? 'height' : 'width';

    var _min = _offset + overflow[_mainSide];

    var _max = _offset - overflow[_altSide];

    var isOriginSide = [top, left].indexOf(basePlacement) !== -1;

    var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;

    var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;

    var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;

    var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);

    popperOffsets[altAxis] = _preventedOffset;
    data[altAxis] = _preventedOffset - _offset;
  }

  state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules


const preventOverflow$1 = {
  name: 'preventOverflow',
  enabled: true,
  phase: 'main',
  fn: preventOverflow,
  requiresIfExists: ['offset']
};

function getHTMLElementScroll(element) {
  return {
    scrollLeft: element.scrollLeft,
    scrollTop: element.scrollTop
  };
}

function getNodeScroll(node) {
  if (node === getWindow(node) || !isHTMLElement(node)) {
    return getWindowScroll(node);
  } else {
    return getHTMLElementScroll(node);
  }
}

function isElementScaled(element) {
  var rect = element.getBoundingClientRect();
  var scaleX = round(rect.width) / element.offsetWidth || 1;
  var scaleY = round(rect.height) / element.offsetHeight || 1;
  return scaleX !== 1 || scaleY !== 1;
} // Returns the composite rect of an element relative to its offsetParent.
// Composite means it takes into account transforms as well as layout.


function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
  if (isFixed === void 0) {
    isFixed = false;
  }

  var isOffsetParentAnElement = isHTMLElement(offsetParent);
  var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);
  var documentElement = getDocumentElement(offsetParent);
  var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);
  var scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  var offsets = {
    x: 0,
    y: 0
  };

  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078
    isScrollParent(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }

    if (isHTMLElement(offsetParent)) {
      offsets = getBoundingClientRect(offsetParent, true);
      offsets.x += offsetParent.clientLeft;
      offsets.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
  };
}

function order(modifiers) {
  var map = new Map();
  var visited = new Set();
  var result = [];
  modifiers.forEach(function (modifier) {
    map.set(modifier.name, modifier);
  }); // On visiting object, check for its dependencies and visit them recursively

  function sort(modifier) {
    visited.add(modifier.name);
    var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
    requires.forEach(function (dep) {
      if (!visited.has(dep)) {
        var depModifier = map.get(dep);

        if (depModifier) {
          sort(depModifier);
        }
      }
    });
    result.push(modifier);
  }

  modifiers.forEach(function (modifier) {
    if (!visited.has(modifier.name)) {
      // check for visited object
      sort(modifier);
    }
  });
  return result;
}

function orderModifiers(modifiers) {
  // order based on dependencies
  var orderedModifiers = order(modifiers); // order based on phase

  return modifierPhases.reduce(function (acc, phase) {
    return acc.concat(orderedModifiers.filter(function (modifier) {
      return modifier.phase === phase;
    }));
  }, []);
}

function debounce(fn) {
  var pending;
  return function () {
    if (!pending) {
      pending = new Promise(function (resolve) {
        Promise.resolve().then(function () {
          pending = undefined;
          resolve(fn());
        });
      });
    }

    return pending;
  };
}

function mergeByName(modifiers) {
  var merged = modifiers.reduce(function (merged, current) {
    var existing = merged[current.name];
    merged[current.name] = existing ? Object.assign({}, existing, current, {
      options: Object.assign({}, existing.options, current.options),
      data: Object.assign({}, existing.data, current.data)
    }) : current;
    return merged;
  }, {}); // IE11 does not support Object.values

  return Object.keys(merged).map(function (key) {
    return merged[key];
  });
}

var DEFAULT_OPTIONS = {
  placement: 'bottom',
  modifiers: [],
  strategy: 'absolute'
};

function areValidElements() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  return !args.some(function (element) {
    return !(element && typeof element.getBoundingClientRect === 'function');
  });
}

function popperGenerator(generatorOptions) {
  if (generatorOptions === void 0) {
    generatorOptions = {};
  }

  var _generatorOptions = generatorOptions,
      _generatorOptions$def = _generatorOptions.defaultModifiers,
      defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
      _generatorOptions$def2 = _generatorOptions.defaultOptions,
      defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
  return function createPopper(reference, popper, options) {
    if (options === void 0) {
      options = defaultOptions;
    }

    var state = {
      placement: 'bottom',
      orderedModifiers: [],
      options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
      modifiersData: {},
      elements: {
        reference: reference,
        popper: popper
      },
      attributes: {},
      styles: {}
    };
    var effectCleanupFns = [];
    var isDestroyed = false;
    var instance = {
      state: state,
      setOptions: function setOptions(setOptionsAction) {
        var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;
        cleanupModifierEffects();
        state.options = Object.assign({}, defaultOptions, state.options, options);
        state.scrollParents = {
          reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
          popper: listScrollParents(popper)
        }; // Orders the modifiers based on their dependencies and `phase`
        // properties

        var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers

        state.orderedModifiers = orderedModifiers.filter(function (m) {
          return m.enabled;
        });
        runModifierEffects();
        return instance.update();
      },
      // Sync update – it will always be executed, even if not necessary. This
      // is useful for low frequency updates where sync behavior simplifies the
      // logic.
      // For high frequency updates (e.g. `resize` and `scroll` events), always
      // prefer the async Popper#update method
      forceUpdate: function forceUpdate() {
        if (isDestroyed) {
          return;
        }

        var _state$elements = state.elements,
            reference = _state$elements.reference,
            popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
        // anymore

        if (!areValidElements(reference, popper)) {
          return;
        } // Store the reference and popper rects to be read by modifiers


        state.rects = {
          reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),
          popper: getLayoutRect(popper)
        }; // Modifiers have the ability to reset the current update cycle. The
        // most common use case for this is the `flip` modifier changing the
        // placement, which then needs to re-run all the modifiers, because the
        // logic was previously ran for the previous placement and is therefore
        // stale/incorrect

        state.reset = false;
        state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
        // is filled with the initial data specified by the modifier. This means
        // it doesn't persist and is fresh on each update.
        // To ensure persistent data, use `${name}#persistent`

        state.orderedModifiers.forEach(function (modifier) {
          return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
        });

        for (var index = 0; index < state.orderedModifiers.length; index++) {
          if (state.reset === true) {
            state.reset = false;
            index = -1;
            continue;
          }

          var _state$orderedModifie = state.orderedModifiers[index],
              fn = _state$orderedModifie.fn,
              _state$orderedModifie2 = _state$orderedModifie.options,
              _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
              name = _state$orderedModifie.name;

          if (typeof fn === 'function') {
            state = fn({
              state: state,
              options: _options,
              name: name,
              instance: instance
            }) || state;
          }
        }
      },
      // Async and optimistically optimized update – it will not be executed if
      // not necessary (debounced to run at most once-per-tick)
      update: debounce(function () {
        return new Promise(function (resolve) {
          instance.forceUpdate();
          resolve(state);
        });
      }),
      destroy: function destroy() {
        cleanupModifierEffects();
        isDestroyed = true;
      }
    };

    if (!areValidElements(reference, popper)) {
      return instance;
    }

    instance.setOptions(options).then(function (state) {
      if (!isDestroyed && options.onFirstUpdate) {
        options.onFirstUpdate(state);
      }
    }); // Modifiers have the ability to execute arbitrary code before the first
    // update cycle runs. They will be executed in the same order as the update
    // cycle. This is useful when a modifier adds some persistent data that
    // other modifiers need to use, but the modifier is run after the dependent
    // one.

    function runModifierEffects() {
      state.orderedModifiers.forEach(function (_ref) {
        var name = _ref.name,
            _ref$options = _ref.options,
            options = _ref$options === void 0 ? {} : _ref$options,
            effect = _ref.effect;

        if (typeof effect === 'function') {
          var cleanupFn = effect({
            state: state,
            name: name,
            instance: instance,
            options: options
          });

          var noopFn = function noopFn() {};

          effectCleanupFns.push(cleanupFn || noopFn);
        }
      });
    }

    function cleanupModifierEffects() {
      effectCleanupFns.forEach(function (fn) {
        return fn();
      });
      effectCleanupFns = [];
    }

    return instance;
  };
}
var createPopper$2 = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules

var defaultModifiers$1 = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1];
var createPopper$1 = /*#__PURE__*/popperGenerator({
  defaultModifiers: defaultModifiers$1
}); // eslint-disable-next-line import/no-unused-modules

var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1];
var createPopper = /*#__PURE__*/popperGenerator({
  defaultModifiers: defaultModifiers
}); // eslint-disable-next-line import/no-unused-modules

// popper
const popper = ref(null);
const showPopper = (content, element) => {
  removePopperIfOpen();
  // If the element is not set, we want to use the mouse position instead
  const mousePosition = {
    x: window.event.clientX,
    y: window.event.clientY
  };
  const reference = element
    ? element
    : {
      getBoundingClientRect: () => ({
        top: mousePosition.y,
        left: mousePosition.x,
        bottom: mousePosition.y,
        right: mousePosition.x,
        width: 0,
        height: 0,
      }),
    };
  const popperElement = document.createElement('div');
  popperElement.classList.add('popper');
  popperElement.innerHTML = content;
  document.body.appendChild(popperElement);
  popper.value = createPopper(reference, popperElement, {
    placement: 'bottom',
    modifiers: [
      {
        name: 'offset',
        options: {
          offset: [0, 8],
        },
      },
    ],
  });
};

const removePopperIfOpen = () => {
  // Remove any poppers that are open
  if (popper.value) {
    popper.value.destroy();
    popper.value = null;
    const popperElement = document.querySelector('.popper');
    if (popperElement) {
      popperElement.remove();
    }
  }
};

const popperBox = (title, content, data_key = null) => {
  // If the data key is not set, we want to use a random key
  if (!data_key) {
    data_key = Math.random().toString(36).substring(7);
  }
  return `<div class="popper-box" data-key="${data_key}">
<article class="message">
  <div class="message-body">
    <strong>${title}</strong><br>
    ${content}
  </div>
</article>
</div>`;
};

const popperBoxProductAddonHtml = (id, name, price, description, classes = '') => {

  let html = `<div class="popper-box ${classes}" data-key="product-addon-${id}-popper">`;
  html += `<p class="title is-6">${name}&nbsp; / &nbsp;${price} Kr.</p>`;
  html += `<p class="subtitle is-6 mb-1 has-text-link">No. ${id}</p>`;
  // If the description is set (and isn't empty), show it
  if (description && description !== '' && description !== ' ') {
    html += `<p class="subtitle is-6">${description}</p>`;
  }
  // Otherwise, show a placeholder
  else {
    html += `<p class="subtitle is-6">No description available</p>`;
  }
  html += `</div>`;
  return html;
};

const showPopperWithContent = (title, content) => {
  showPopper(popperBox(title, content));
};


const _sfc_main$1k = {};
const PopperDefault = /*#__PURE__*/_export_sfc(_sfc_main$1k, [['__file',"PopperDefault.vue"]]);

const _sfc_main$1j = /* @__PURE__ */ defineComponent({
  __name: "InvoicingPeriodFlagList",
  props: {
    flags: {
      type: Array,
      default: () => []
    },
    compact: {
      type: Boolean,
      default: false
    }
  },
  emits: ["statusChanged"],
  setup(__props, { expose: __expose, emit: __emit }) {
    __expose();
    const props = __props;
    const emit = __emit;
    const { t, locale } = useI18n();
    const isActiveFlag = (flag) => String(flag?.status || "active") === "active";
    const activeFlags = computed(() => props.flags.filter((flag) => isActiveFlag(flag)));
    const translate = (key, fallback, params = {}) => {
      const translated = t(key, params);
      return translated === key ? fallback : translated;
    };
    const escapeHtml = (value) => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
    const flagColorClass = (flag) => flag?.source === "manual" ? "has-text-danger" : "has-text-warning";
    const isManualFlag = (flag) => flag?.source === "manual";
    const localeValue = () => typeof locale === "string" ? locale : locale.value;
    const formatCreatedAt = (value) => {
      const rawValue = String(value ?? "").trim();
      if (rawValue === "") {
        return translate("invoice_period.flags.tooltip.unknown", "Unknown");
      }
      const parsedDate = new Date(rawValue.includes("T") ? rawValue : rawValue.replace(" ", "T"));
      if (Number.isNaN(parsedDate.getTime())) {
        return rawValue;
      }
      return new Intl.DateTimeFormat(localeValue() || void 0, {
        dateStyle: "short",
        timeStyle: "short"
      }).format(parsedDate);
    };
    const createdByLabel = (flag) => {
      const displayName = String(flag?.created_by_name || flag?.created_by_display_name || "").trim();
      if (displayName !== "") {
        return displayName;
      }
      const createdBy = Number(flag?.created_by || 0);
      if (createdBy > 0) {
        return `#${createdBy}`;
      }
      return translate("invoice_period.flags.tooltip.unknown", "Unknown");
    };
    const flagLabel = (flag) => {
      if (flag?.source === "manual") {
        return String(flag?.reason || flag?.message || "");
      }
      if (flag?.message_key) {
        return translate(flag.message_key, flag?.message || "", flag?.message_params || {});
      }
      return String(flag?.message || "");
    };
    const findCaseInsensitive = (haystack, needle) => {
      if (!needle) {
        return -1;
      }
      return haystack.toLocaleLowerCase().indexOf(needle.toLocaleLowerCase());
    };
    const localizedTokenParts = (flag, tokens) => {
      const message = flagLabel(flag);
      const matches = tokens.map((token) => ({
        ...token,
        index: findCaseInsensitive(message, token.text)
      })).filter((token) => token.index >= 0).sort((a, b) => a.index - b.index);
      if (matches.length === 0) {
        return Array.isArray(flag?.message_parts) ? flag.message_parts : [];
      }
      const parts = [];
      let cursor = 0;
      for (const match of matches) {
        if (match.index < cursor) {
          continue;
        }
        if (match.index > cursor) {
          parts.push({ type: "text", text: message.slice(cursor, match.index) });
        }
        const end = match.index + match.text.length;
        parts.push({ type: match.type, text: message.slice(match.index, end) });
        cursor = end;
      }
      if (cursor < message.length) {
        parts.push({ type: "text", text: message.slice(cursor) });
      }
      return parts.filter((part) => part.text !== "");
    };
    const localizedPriceMismatchParts = (flag) => localizedTokenParts(flag, [
      { type: "order_item", text: String(flag?.message_params?.product || flag?.context?.product_name || "Item") },
      { type: "expected_price", text: translate("invoice_period.flags.tokens.expected", "expected") }
    ]);
    const localizedOrderParts = (flag) => localizedTokenParts(flag, [
      { type: "order", text: translate("invoice_period.flags.tokens.order", "Order") }
    ]);
    const localizedWashCertificateItemParts = (flag) => localizedTokenParts(flag, [
      { type: "order_item", text: translate("invoice_period.flags.tokens.wash_certificate_item", "Wash certificate item") }
    ]);
    const localizedWashCertificateParts = (flag) => localizedTokenParts(flag, [
      { type: "order", text: translate("invoice_period.flags.tokens.wash_certificate", "Wash certificate") }
    ]);
    const localizedXlVaskUsageLogParts = (flag) => localizedTokenParts(flag, [
      { type: "xlvask_usage_log", text: translate("invoice_period.flags.tokens.xlvask_usage_log", "XL Vask wash") }
    ]);
    const flagMessageParts = (flag) => {
      if (flag?.definition_key === "price_mismatch") {
        return localizedPriceMismatchParts(flag);
      }
      if (flag?.definition_key === "multiple_identical_primary_vehicle_items") {
        return localizedOrderParts(flag);
      }
      if (["customer_rule_requires_reference", "customer_rule_requires_po_number"].includes(flag?.definition_key)) {
        return localizedOrderParts(flag);
      }
      if (flag?.definition_key === "wash_certificate_item_without_certificate") {
        return localizedWashCertificateItemParts(flag);
      }
      if (flag?.definition_key === "wash_certificate_attached_without_item") {
        return localizedWashCertificateParts(flag);
      }
      if (flag?.definition_key === "xlvask_missing_order_link") {
        return localizedXlVaskUsageLogParts(flag);
      }
      return Array.isArray(flag?.message_parts) ? flag.message_parts : [];
    };
    const isOrderNavigationPart = (part) => part?.type === "order" || part?.type === "order_item";
    const isXlVaskUsageLogPart = (part) => part?.type === "xlvask_usage_log";
    const statusLabel = (status) => {
      const labels = {
        resolved: "Resolved",
        ignored: "Ignored",
        false_positive: "False positive"
      };
      return translate(`invoice_period.flags.status.${status}`, labels[status] || status);
    };
    const statusIcon = (status) => ({
      resolved: "fas fa-check",
      ignored: "fas fa-eye-slash",
      false_positive: "fas fa-times-circle"
    })[status] || "fas fa-flag";
    const orderItemPreviewHtml = (flag) => {
      const highlightedId = Number(flag?.order_item_id || flag?.context?.order_item_id || 0);
      const rows = Array.isArray(flag?.context?.order_items) ? flag.context.order_items : [];
      if (rows.length === 0) {
        return escapeHtml(translate("invoice_period.flags.preview.no_order_items", "No order items available.", {
          entity: translate("invoice_period.flags.preview.entities.order_items", "order items")
        }));
      }
      const body = rows.map((row) => {
        const rowId = Number(row?.id || 0);
        const className = rowId === highlightedId ? "has-background-warning-light" : "";
        const name = row?.product_name || row?.product?.name || `#${row?.product_id || rowId}`;
        return `<tr class="${className}">
      <td>${escapeHtml(name)}</td>
      <td class="has-text-right">${escapeHtml(row?.quantity ?? "")}</td>
      <td class="has-text-right">${escapeHtml(row?.price ?? "")}</td>
    </tr>`;
      }).join("");
      return `<table class="table is-narrow is-fullwidth">
    <thead><tr><th>${escapeHtml(translate("invoice_period.flags.preview.product", "Product"))}</th><th>${escapeHtml(translate("invoice_period.flags.preview.quantity", "Qty"))}</th><th>${escapeHtml(translate("invoice_period.flags.preview.price", "Price"))}</th></tr></thead>
    <tbody>${body}</tbody>
  </table>`;
    };
    const expectedPriceHtml = (flag) => {
      const breakdown = flag?.context?.expected_price_breakdown || {};
      const rows = [
        ["Product price", breakdown.product_price],
        ["Department price", breakdown.department_price],
        ["Effective base", breakdown.effective_base_price],
        ["Product discount", `${breakdown.product_discount_percentage ?? 0}%`],
        ["Category discount", `${breakdown.category_discount_percentage ?? 0}%`],
        ["Economic customer discount", `${breakdown.economic_customer_discount_percentage ?? 0}%`],
        ["Applied discount", `${breakdown.applied_discount_percentage ?? 0}%`],
        ["Expected", breakdown.expected_price]
      ];
      return `<table class="table is-narrow is-fullwidth">
    <tbody>
      ${rows.map(([label, value]) => `<tr><td>${escapeHtml(label)}</td><td class="has-text-right">${escapeHtml(value ?? "-")}</td></tr>`).join("")}
    </tbody>
  </table>`;
    };
    const xlvaskUsageLogHtml = (flag) => {
      const context = flag?.context || {};
      const rows = [
        [translate("invoice_period.flags.preview.wash_id", "Wash ID"), context.wash_id || flag?.message_params?.wash_id],
        [translate("invoice_period.flags.preview.registration_number", "Registration"), context.registration_number || flag?.message_params?.registration_number],
        [translate("invoice_period.flags.preview.start_time", "Start time"), context.start_time],
        [translate("invoice_period.flags.preview.customer", "Customer"), context.customer_name || flag?.customer_name]
      ].filter(([, value]) => String(value ?? "").trim() !== "");
      if (rows.length === 0) {
        return escapeHtml(translate("invoice_period.flags.preview.no_xlvask_usage_log", "No XL Vask details available.", {
          entity: translate("invoice_period.flags.preview.entities.xlvask_usage_log", "XL Vask details")
        }));
      }
      return `<table class="table is-narrow is-fullwidth">
    <tbody>
      ${rows.map(([label, value]) => `<tr><td>${escapeHtml(label)}</td><td class="has-text-right">${escapeHtml(value)}</td></tr>`).join("")}
    </tbody>
  </table>`;
    };
    const showOrderItemPreview = (flag, target) => {
      showPopper(
        popperBox(translate("invoice_period.flags.preview.order_items", "Order items"), orderItemPreviewHtml(flag)),
        target
      );
    };
    const showExpectedPricePreview = (flag, target) => {
      showPopper(
        popperBox(translate("invoice_period.flags.preview.expected_price", "Expected price"), expectedPriceHtml(flag)),
        target
      );
    };
    const showXlVaskUsageLogPreview = (flag, target) => {
      showPopper(
        popperBox(translate("invoice_period.flags.preview.xlvask_usage_log", "XL Vask registration"), xlvaskUsageLogHtml(flag)),
        target
      );
    };
    const openOrderItem = (flag) => {
      const orderId = Number(flag?.order_id || flag?.context?.order_id || 0);
      const departmentId = Number(flag?.context?.department_id || 0);
      const orderItemId = Number(flag?.order_item_id || flag?.context?.order_item_id || 0);
      if (orderId < 1 || departmentId < 1) {
        return;
      }
      const suffix = orderItemId > 0 ? `?highlightOrderItem=${encodeURIComponent(String(orderItemId))}` : "";
      SessionUser.functions.redirectTo.department(departmentId, `modules/pos/orders/${orderId}${suffix}`, true);
    };
    const openXlVaskUsageLog = (flag) => {
      const usageLogId = Number(flag?.xlvask_usage_log_id || flag?.context?.xlvask_usage_log_id || flag?.target_id || 0);
      const query = new URLSearchParams({
        activeTab: "period",
        periodView: "self_wash"
      });
      if (usageLogId > 0) {
        query.set("xlvaskUsageLogId", String(usageLogId));
      }
      SessionUser.functions.redirectTo.superUser(`/invoices?${query.toString()}`, true);
    };
    const saveFlagStatus = async (flag, status) => {
      const result = await Swal.fire({
        title: statusLabel(status),
        input: "textarea",
        inputPlaceholder: translate("invoice_period.flags.status.reason_placeholder", "Optional reason"),
        showCancelButton: true,
        confirmButtonText: statusLabel(status),
        cancelButtonText: t("common.cancel")
      });
      if (!result.isConfirmed) {
        return;
      }
      const reason = typeof result.value === "string" ? result.value : "";
      if (flag?.source === "manual") {
        await SessionUser.request(`/superuser/invoicing/period/flags/${flag.id}/status`, "PATCH", {
          status,
          reason
        });
      } else {
        await SessionUser.request("/superuser/invoicing/period/flags/automatic/status", "POST", {
          fingerprint: flag.fingerprint,
          status,
          target_type: flag.target_type,
          target_id: flag.target_id,
          field: flag.field,
          definition_key: flag.definition_key,
          reason
        });
      }
      emit("statusChanged", { ...flag, status, status_reason: reason });
    };
    const __returned__ = { props, emit, t, locale, isActiveFlag, activeFlags, translate, escapeHtml, flagColorClass, isManualFlag, localeValue, formatCreatedAt, createdByLabel, flagLabel, findCaseInsensitive, localizedTokenParts, localizedPriceMismatchParts, localizedOrderParts, localizedWashCertificateItemParts, localizedWashCertificateParts, localizedXlVaskUsageLogParts, flagMessageParts, isOrderNavigationPart, isXlVaskUsageLogPart, statusLabel, statusIcon, orderItemPreviewHtml, expectedPriceHtml, xlvaskUsageLogHtml, showOrderItemPreview, showExpectedPricePreview, showXlVaskUsageLogPreview, openOrderItem, openXlVaskUsageLog, saveFlagStatus, get BTooltip() {
      return Tooltip$1;
    }, removePopperIfOpen };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$F = ["data-testid"];
const _hoisted_2$x = ["data-testid"];
const _hoisted_3$t = { class: "invoice-period-flag-created-tooltip__row" };
const _hoisted_4$t = { class: "invoice-period-flag-created-tooltip__row" };
const _hoisted_5$s = { class: "invoice-period-flag-row__icon icon is-small" };
const _hoisted_6$s = {
  key: 1,
  class: "invoice-period-flag-row__icon icon is-small"
};
const _hoisted_7$r = { class: "invoice-period-flag-row__message" };
const _hoisted_8$r = ["onClick", "onMouseover"];
const _hoisted_9$p = ["onMouseover"];
const _hoisted_10$o = ["onClick", "onMouseover"];
const _hoisted_11$k = { class: "invoice-period-flag-row__actions buttons are-small" };
const _hoisted_12$j = ["title", "onClick"];
const _hoisted_13$h = { class: "icon is-small" };
function _sfc_render$M(_ctx, _cache, $props, $setup, $data, $options) {
  return $setup.activeFlags.length > 0 ? (openBlock(), createElementBlock(
    "div",
    {
      key: 0,
      class: normalizeClass(["invoice-period-flags", { "invoice-period-flags--compact": $setup.props.compact }]),
      "data-testid": "invoice-period-flags"
    },
    [
      (openBlock(true), createElementBlock(
        Fragment,
        null,
        renderList($setup.activeFlags, (flag) => {
          return openBlock(), createElementBlock("div", {
            key: flag.id || flag.fingerprint,
            class: "invoice-period-flag-row",
            "data-testid": `invoice-period-flag-${flag.id || flag.fingerprint}`
          }, [
            $setup.isManualFlag(flag) ? (openBlock(), createBlock(
              $setup["BTooltip"],
              {
                key: 0,
                class: "invoice-period-flag-row__tooltip",
                position: "is-top",
                type: "is-dark",
                multilined: "",
                "append-to-body": ""
              },
              {
                content: withCtx(() => [
                  createBaseVNode("div", {
                    class: "invoice-period-flag-created-tooltip",
                    "data-testid": `invoice-period-flag-created-tooltip-${flag.id || flag.fingerprint}`
                  }, [
                    createBaseVNode("div", _hoisted_3$t, [
                      createBaseVNode(
                        "span",
                        null,
                        toDisplayString($setup.translate("invoice_period.flags.tooltip.created_at", "Created")),
                        1
                        /* TEXT */
                      ),
                      createBaseVNode(
                        "strong",
                        null,
                        toDisplayString($setup.formatCreatedAt(flag.created_at)),
                        1
                        /* TEXT */
                      )
                    ]),
                    createBaseVNode("div", _hoisted_4$t, [
                      createBaseVNode(
                        "span",
                        null,
                        toDisplayString($setup.translate("invoice_period.flags.tooltip.created_by", "By")),
                        1
                        /* TEXT */
                      ),
                      createBaseVNode(
                        "strong",
                        null,
                        toDisplayString($setup.createdByLabel(flag)),
                        1
                        /* TEXT */
                      )
                    ])
                  ], 8, _hoisted_2$x)
                ]),
                default: withCtx(() => [
                  createBaseVNode("span", _hoisted_5$s, [
                    createBaseVNode(
                      "i",
                      {
                        class: normalizeClass(["fas fa-flag", $setup.flagColorClass(flag)])
                      },
                      null,
                      2
                      /* CLASS */
                    )
                  ])
                ]),
                _: 2
                /* DYNAMIC */
              },
              1024
              /* DYNAMIC_SLOTS */
            )) : (openBlock(), createElementBlock("span", _hoisted_6$s, [
              createBaseVNode(
                "i",
                {
                  class: normalizeClass(["fas fa-flag", $setup.flagColorClass(flag)])
                },
                null,
                2
                /* CLASS */
              )
            ])),
            createBaseVNode("span", _hoisted_7$r, [
              $setup.flagMessageParts(flag).length > 0 ? (openBlock(true), createElementBlock(
                Fragment,
                { key: 0 },
                renderList($setup.flagMessageParts(flag), (part, index) => {
                  return openBlock(), createElementBlock(
                    Fragment,
                    {
                      key: `${flag.id || flag.fingerprint}-${index}`
                    },
                    [
                      $setup.isOrderNavigationPart(part) ? (openBlock(), createElementBlock("button", {
                        key: 0,
                        type: "button",
                        class: "invoice-period-flag-token",
                        onClick: withModifiers(($event) => $setup.openOrderItem(flag), ["stop"]),
                        onMouseover: ($event) => $setup.showOrderItemPreview(flag, $event.currentTarget),
                        onMouseleave: _cache[0] || (_cache[0] = (...args) => $setup.removePopperIfOpen && $setup.removePopperIfOpen(...args))
                      }, toDisplayString(part.text), 41, _hoisted_8$r)) : part.type === "expected_price" ? (openBlock(), createElementBlock("button", {
                        key: 1,
                        type: "button",
                        class: "invoice-period-flag-token",
                        onMouseover: ($event) => $setup.showExpectedPricePreview(flag, $event.currentTarget),
                        onMouseleave: _cache[1] || (_cache[1] = (...args) => $setup.removePopperIfOpen && $setup.removePopperIfOpen(...args))
                      }, toDisplayString(part.text), 41, _hoisted_9$p)) : $setup.isXlVaskUsageLogPart(part) ? (openBlock(), createElementBlock("button", {
                        key: 2,
                        type: "button",
                        class: "invoice-period-flag-token",
                        onClick: withModifiers(($event) => $setup.openXlVaskUsageLog(flag), ["stop"]),
                        onMouseover: ($event) => $setup.showXlVaskUsageLogPreview(flag, $event.currentTarget),
                        onMouseleave: _cache[2] || (_cache[2] = (...args) => $setup.removePopperIfOpen && $setup.removePopperIfOpen(...args))
                      }, toDisplayString(part.text), 41, _hoisted_10$o)) : (openBlock(), createElementBlock(
                        Fragment,
                        { key: 3 },
                        [
                          createTextVNode(
                            toDisplayString(part.text),
                            1
                            /* TEXT */
                          )
                        ],
                        64
                        /* STABLE_FRAGMENT */
                      ))
                    ],
                    64
                    /* STABLE_FRAGMENT */
                  );
                }),
                128
                /* KEYED_FRAGMENT */
              )) : (openBlock(), createElementBlock(
                Fragment,
                { key: 1 },
                [
                  createTextVNode(
                    toDisplayString($setup.flagLabel(flag)),
                    1
                    /* TEXT */
                  )
                ],
                64
                /* STABLE_FRAGMENT */
              ))
            ]),
            createBaseVNode("span", _hoisted_11$k, [
              (openBlock(), createElementBlock(
                Fragment,
                null,
                renderList(["resolved", "ignored", "false_positive"], (status) => {
                  return createBaseVNode("button", {
                    key: `${flag.id || flag.fingerprint}-${status}`,
                    type: "button",
                    class: "button is-white",
                    title: $setup.statusLabel(status),
                    onClick: withModifiers(($event) => $setup.saveFlagStatus(flag, status), ["stop"])
                  }, [
                    createBaseVNode("span", _hoisted_13$h, [
                      createBaseVNode(
                        "i",
                        {
                          class: normalizeClass($setup.statusIcon(status))
                        },
                        null,
                        2
                        /* CLASS */
                      )
                    ])
                  ], 8, _hoisted_12$j);
                }),
                64
                /* STABLE_FRAGMENT */
              ))
            ])
          ], 8, _hoisted_1$F);
        }),
        128
        /* KEYED_FRAGMENT */
      ))
    ],
    2
    /* CLASS */
  )) : createCommentVNode("v-if", true);
}
const InvoicingPeriodFlagList = /* @__PURE__ */ _export_sfc(_sfc_main$1j, [["render", _sfc_render$M], ["__scopeId", "data-v-9376c27f"], ["__file", "InvoicingPeriodFlagList.vue"]]);

const MULTI_MONTH_INVOICE_ACTION = {
  CONTINUE: "continue",
  CANCEL: "cancel",
  SPLIT: "split",
};

const toPositiveInteger = (value) => {
  const parsed = Number.parseInt(String(value ?? ""), 10);
  return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
};

const getDateKey = (value) => {
  const rawValue = String(value ?? "").trim();
  const directMatch = rawValue.match(/^(\d{4})-(\d{2})-(\d{2})/);
  if (directMatch) {
    return `${directMatch[1]}-${directMatch[2]}-${directMatch[3]}`;
  }

  const parsedDate = new Date(rawValue);
  if (Number.isNaN(parsedDate.getTime())) {
    return null;
  }

  const year = parsedDate.getFullYear();
  const month = String(parsedDate.getMonth() + 1).padStart(2, "0");
  const day = String(parsedDate.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

const getMonthKey = (value) => {
  const dateKey = getDateKey(value);
  return dateKey ? dateKey.slice(0, 7) : null;
};

const translate = (key, params = {}) => i18n.global.t(key, params);

const getSplitResponsePayload = (response = {}) => response?.data?.data ?? response?.data ?? {};

const buildMultiMonthInvoiceContext = (
  items = [],
  {
    getDate = (item) => item?.created_at ?? item?.date,
    getInvoiceCollectionId = (item) => item?.invoice_collection_id,
  } = {}
) => {
  const months = new Set();
  const dateKeys = [];
  const invoiceCollectionIds = new Set();

  (Array.isArray(items) ? items : []).forEach((item) => {
    const dateValue = getDate(item);
    const dateKey = getDateKey(dateValue);
    if (dateKey) {
      dateKeys.push(dateKey);
      months.add(dateKey.slice(0, 7));
    }

    const invoiceCollectionId = toPositiveInteger(getInvoiceCollectionId(item));
    if (invoiceCollectionId) {
      invoiceCollectionIds.add(invoiceCollectionId);
    }
  });

  dateKeys.sort();

  return {
    months: Array.from(months).sort(),
    dateFrom: dateKeys[0] ?? null,
    dateTo: dateKeys[dateKeys.length - 1] ?? null,
    invoiceCollectionIds: Array.from(invoiceCollectionIds).sort((left, right) => left - right),
  };
};

const shouldWarnAboutMultiMonthInvoice = (context = {}) => (
  Array.isArray(context.months) &&
  context.months.length > 1 &&
  Array.isArray(context.invoiceCollectionIds) &&
  context.invoiceCollectionIds.length > 0 &&
  Boolean(context.dateFrom) &&
  Boolean(context.dateTo)
);

const promptMultiMonthInvoiceWarning = async ({
  context,
  splitByMonth,
  parseErrorMessage = (error) => error?.message ?? String(error),
} = {}) => {
  if (!shouldWarnAboutMultiMonthInvoice(context)) {
    return MULTI_MONTH_INVOICE_ACTION.CONTINUE;
  }

  const months = context.months.join(", ");
  const confirmation = await Swal.fire({
    icon: "warning",
    title: translate("invoicing_period.multi_month_invoice_warning.title"),
    text: translate("invoicing_period.multi_month_invoice_warning.text", { months }),
    showCancelButton: true,
    showDenyButton: true,
    confirmButtonText: translate("invoicing_period.multi_month_invoice_warning.split_by_month"),
    denyButtonText: translate("invoicing_period.multi_month_invoice_warning.invoice_together"),
    cancelButtonText: translate("common.cancel"),
  });

  if (confirmation.isDenied) {
    return MULTI_MONTH_INVOICE_ACTION.CONTINUE;
  }

  if (!confirmation.isConfirmed) {
    return MULTI_MONTH_INVOICE_ACTION.CANCEL;
  }

  try {
    const response = await splitByMonth(context.dateFrom, context.dateTo, {
      invoiceCollectionIds: context.invoiceCollectionIds,
      preview: false,
    });
    const result = getSplitResponsePayload(response);
    await Swal.fire({
      icon: "success",
      title: translate("invoicing_period.multi_month_invoice_warning.split_success_title"),
      text: translate("invoicing_period.multi_month_invoice_warning.split_success_text", {
        processed: result.processed_count ?? 0,
        changed: result.changed_count ?? 0,
        skipped: result.skipped_count ?? 0,
      }),
    });
    return MULTI_MONTH_INVOICE_ACTION.SPLIT;
  } catch (error) {
    await Swal.fire({
      icon: "error",
      title: translate("invoicing_period.multi_month_invoice_warning.split_error_title"),
      text: parseErrorMessage(error),
    });
    return MULTI_MONTH_INVOICE_ACTION.CANCEL;
  }
};

const PLATE_FIELDS = [
  "reg_1",
  "reg_2",
  "reg_3",
  "license_plate",
  "licensePlate",
  "registration_number",
  "registrationNumber",
  "plate",
];

const DATE_FIELDS = [
  "date",
  "created_at",
  "completed_at",
  "datetime",
];

const AMOUNT_FIELDS = [
  "amount",
  "total_net_amount",
  "net_amount",
  "price",
];

const asTrimmedString = (value) => {
  if (value === null || value === undefined) {
    return "";
  }

  return String(value).trim();
};

const normalizeDuplicatePlate = (value) => asTrimmedString(value)
  .toUpperCase()
  .replace(/\s+/g, "");

const getDuplicateTransactionPlate = (transaction = {}) => {
  for (const field of PLATE_FIELDS) {
    const plate = normalizeDuplicatePlate(transaction?.[field]);
    if (plate) {
      return plate;
    }
  }

  const nestedPlate = normalizeDuplicatePlate(
    transaction?.vehicle?.reg_1
    ?? transaction?.vehicle?.registration_number
    ?? transaction?.vehicle?.license_plate
  );

  return nestedPlate || "";
};

const normalizeDuplicateDateKey = (value) => {
  const rawValue = asTrimmedString(value);
  if (!rawValue) {
    return "";
  }

  const isoDateMatch = rawValue.match(/^(\d{4}-\d{2}-\d{2})/);
  if (isoDateMatch) {
    return isoDateMatch[1];
  }

  const parsedDate = new Date(rawValue);
  if (Number.isNaN(parsedDate.getTime())) {
    return "";
  }

  return parsedDate.toISOString().split("T")[0];
};

const getDuplicateTransactionDateKey = (transaction = {}) => {
  for (const field of DATE_FIELDS) {
    const dateKey = normalizeDuplicateDateKey(transaction?.[field]);
    if (dateKey) {
      return dateKey;
    }
  }

  return "";
};

const formatDuplicateDateLabel = (dateKey) => {
  const normalizedDateKey = normalizeDuplicateDateKey(dateKey);
  if (!normalizedDateKey) {
    return "Ukendt dato";
  }

  const [year, month, day] = normalizedDateKey.split("-");
  return `${day}/${month}/${year}`;
};

const getDuplicateTransactionAmount = (transaction = {}) => {
  for (const field of AMOUNT_FIELDS) {
    const amount = Number(transaction?.[field]);
    if (Number.isFinite(amount)) {
      return amount;
    }
  }

  return 0;
};

const uniqueBy = (items, keyGetter) => {
  const result = [];
  const seen = new Set();

  items.forEach((item) => {
    const key = keyGetter(item);
    if (seen.has(key)) {
      return;
    }

    seen.add(key);
    result.push(item);
  });

  return result;
};

const isTransactionBookedOrExcluded = (transaction = {}) => (
  transaction?.booked === true
  || transaction?.excluded === true
  || transaction?.completed_at !== null && transaction?.completed_at !== undefined
);

const enrichTransaction = (customer = {}, transaction = {}) => ({
  ...transaction,
  customer_number: transaction?.customer_number ?? customer?.customer_number ?? null,
  customer_name: transaction?.customer_name ?? customer?.customer_name ?? "",
  customer_id: transaction?.customer_id ?? customer?.customer_number ?? null,
  user_id: transaction?.user_id ?? customer?.id ?? null,
});

const buildPossibleDuplicateGroups = (customers = [], options = {}) => {
  const safeCustomers = Array.isArray(customers) ? customers : [];
  const includeSingletons = options.includeSingletons === true;
  const getTransactions = typeof options.getTransactions === "function"
    ? options.getTransactions
    : (customer) => customer?.transactions ?? [];

  const groupsByKey = new Map();

  safeCustomers.forEach((customer) => {
    const transactions = Array.isArray(getTransactions(customer)) ? getTransactions(customer) : [];

    transactions
      .filter((transaction) => transaction?.excluded !== true)
      .forEach((transaction) => {
        const enrichedTransaction = enrichTransaction(customer, transaction);
        const plate = getDuplicateTransactionPlate(enrichedTransaction);
        const dateKey = getDuplicateTransactionDateKey(enrichedTransaction);
        const groupKey = plate && dateKey
          ? `${plate}|${dateKey}`
          : `unknown|${enrichedTransaction.id ?? customer?.customer_number ?? groupsByKey.size}`;

        if (!groupsByKey.has(groupKey)) {
          groupsByKey.set(groupKey, {
            key: groupKey,
            testId: groupKey.replace(/[^A-Z0-9_-]/gi, "-"),
            plate: plate || "Ukendt køretøj",
            dateKey,
            dateLabel: formatDuplicateDateLabel(dateKey),
            transactions: [],
            customers: [],
            requires_action: false,
            draft: {
              is_action_blocked: false,
            },
            queue: {
              statuses: [],
              invoice_collection_ids: [],
              is_action_blocked: false,
            },
          });
        }

        const group = groupsByKey.get(groupKey);
        group.transactions.push(enrichedTransaction);
        group.customers.push({
          id: customer?.id ?? enrichedTransaction.user_id ?? null,
          customer_number: enrichedTransaction.customer_number,
          customer_name: enrichedTransaction.customer_name,
        });
        group.requires_action = group.requires_action || customer?.requires_action === true;
        group.draft.is_action_blocked = group.draft.is_action_blocked || customer?.draft?.is_action_blocked === true;
        group.queue.is_action_blocked = group.queue.is_action_blocked || customer?.queue?.is_action_blocked === true;
        group.queue.statuses = Array.from(new Set([
          ...group.queue.statuses,
          ...(Array.isArray(customer?.queue?.statuses) ? customer.queue.statuses : []),
        ]));
        group.queue.invoice_collection_ids = Array.from(new Set([
          ...group.queue.invoice_collection_ids,
          ...(Array.isArray(customer?.queue?.invoice_collection_ids) ? customer.queue.invoice_collection_ids : []),
        ]));
      });
  });

  return Array.from(groupsByKey.values())
    .map((group) => {
      const customersForGroup = uniqueBy(
        group.customers,
        (customer) => `${customer.customer_number ?? ""}|${customer.customer_name ?? ""}`
      );
      const allTransactionsResolved = group.transactions.length > 0
        && group.transactions.every((transaction) => isTransactionBookedOrExcluded(transaction));

      return {
        ...group,
        customers: customersForGroup,
        totalNetAmount: group.transactions.reduce(
          (sum, transaction) => sum + getDuplicateTransactionAmount(transaction),
          0
        ),
        allTransactionsResolved,
        requires_action: group.requires_action || !allTransactionsResolved,
      };
    })
    .filter((group) => includeSingletons || group.transactions.length > 1)
    .sort((first, second) => (
      first.dateKey.localeCompare(second.dateKey)
      || first.plate.localeCompare(second.plate)
      || first.key.localeCompare(second.key)
    ));
};

const _sfc_main$1i = /* @__PURE__ */ defineComponent({
  __name: "InvoicingBillingPeriodViewAll",
  setup(__props, { expose: __expose }) {
    __expose();
    const expandedDuplicateGroupKey = ref(null);
    const onClickCustomer = (customer) => {
      const shouldExpandCustomer = customer.expanded !== true;
      customersInCurrentView.value.forEach((currentCustomer) => {
        currentCustomer.expanded = currentCustomer === customer ? shouldExpandCustomer : false;
      });
    };
    const getTransactionsInView = (customer) => {
      if (!customer.transactions || customer.transactions.length === 0) {
        return [];
      }
      return customer.transactions.filter((transaction) => {
        const transactionDateKey = getDuplicateTransactionDateKey(transaction);
        if (!transactionDateKey) {
          return true;
        }
        const transactionDate = /* @__PURE__ */ new Date(`${transactionDateKey}T00:00:00.000Z`);
        return transactionDate >= dates.variables.start.value && transactionDate <= dates.variables.end.value;
      });
    };
    const getCustomerTransactionsInView = (customer) => {
      return getTransactionsInView(customer).map((transaction) => transaction.id);
    };
    const doesCustomerHaveTransactionsDifferentDays = (customer) => {
      if (!customer.transactions || customer.transactions.length < 2) {
        return false;
      }
      const datesSet = new Set(
        customer.transactions.map((transaction) => getDuplicateTransactionDateKey(transaction)).filter((dateKey) => dateKey.length > 0)
      );
      return datesSet.size > 1;
    };
    const tmpFilters = ref({
      displayRequiresAction: true,
      displayBooked: true,
      displayStatistics: false,
      isCustomerVisible: () => true
    });
    const periodSearchInput = ref(periodPaging.search);
    let periodSearchDebounceTimer = null;
    const commitPeriodSearch = (value) => {
      const nextSearch = String(value || "").trim();
      if (periodPaging.search === nextSearch) {
        return;
      }
      periodPaging.search = nextSearch;
      periodPaging.page = 1;
    };
    const onPeriodSearchInput = () => {
      if (periodSearchDebounceTimer !== null) {
        clearTimeout(periodSearchDebounceTimer);
      }
      periodSearchDebounceTimer = setTimeout(() => {
        commitPeriodSearch(periodSearchInput.value);
      }, 300);
    };
    const setPeriodPage = (page) => {
      const nextPage = Math.max(1, Math.min(periodPageCount.value, Number.parseInt(String(page), 10) || 1));
      if (periodPaging.page !== nextPage) {
        periodPaging.page = nextPage;
      }
    };
    const onPeriodLimitChange = (event) => {
      const target = event.target;
      const nextLimit = target.value === "all" ? "all" : Number.parseInt(target.value, 10);
      if ((nextLimit === "all" || Number.isInteger(nextLimit) && nextLimit > 0) && periodPaging.limit !== nextLimit) {
        periodPaging.limit = nextLimit;
        periodPaging.page = 1;
      }
    };
    const reloadPeriodPage = () => {
      clearPeriodCache();
      requestPeriodReload();
    };
    const loadPeriodPage = () => {
    };
    const onFilterChanged = (filters) => {
      tmpFilters.value = filters;
      const includeRequiresAction = filters.displayRequiresAction !== false;
      const includeBooked = filters.displayBooked !== false;
      if (periodPaging.includeRequiresAction !== includeRequiresAction || periodPaging.includeBooked !== includeBooked) {
        periodPaging.includeRequiresAction = includeRequiresAction;
        periodPaging.includeBooked = includeBooked;
        periodPaging.page = 1;
      }
    };
    watch(
      () => periodPaging.search,
      (nextSearch) => {
        if (periodSearchInput.value !== nextSearch) {
          periodSearchInput.value = nextSearch;
        }
      }
    );
    onUnmounted(() => {
      if (periodSearchDebounceTimer !== null) {
        clearTimeout(periodSearchDebounceTimer);
      }
    });
    const customersInCurrentView = computed(
      () => view.variables.sharedVariables.value?.types?.[view.computed.componentName.value] ?? []
    );
    const selectedFlagTab = computed({
      get: () => periodPaging.flagTab || "all",
      set: (value) => {
        if (periodPaging.flagTab !== value) {
          periodPaging.flagTab = value;
          periodPaging.page = 1;
        }
      }
    });
    const getCustomerFlagTabType = (customer) => {
      const flagCounts = getCustomerActiveFlagCounts(customer);
      if (flagCounts.manual > 0) {
        return "red";
      }
      if (flagCounts.automatic > 0) {
        return "yellow";
      }
      return "none";
    };
    const toNonNegativeInteger = (value) => {
      const parsed = Number.parseInt(String(value ?? "0"), 10);
      return Number.isInteger(parsed) && parsed > 0 ? parsed : 0;
    };
    const periodFlagTabCounts = computed(() => {
      const currentTypeName = view.computed.componentName.value;
      const backendCounts = periodPaging.typeCounts?.[currentTypeName];
      if (backendCounts && typeof backendCounts === "object") {
        const all = toNonNegativeInteger(backendCounts.total);
        const red = Math.min(all, toNonNegativeInteger(backendCounts.manual_flags));
        const yellow = Math.min(Math.max(0, all - red), toNonNegativeInteger(backendCounts.automatic_flags));
        return {
          all,
          red,
          yellow,
          none: Math.max(0, all - red - yellow)
        };
      }
      const counts = { all: 0, red: 0, yellow: 0, none: 0 };
      customersInCurrentView.value.forEach((customer) => {
        counts.all += 1;
        counts[getCustomerFlagTabType(customer)] += 1;
      });
      return counts;
    });
    const filteredCustomersInCurrentView = computed(() => {
      return customersInCurrentView.value;
    });
    const getPeriodFlagTabIconClass = (tab) => {
      if (tab === "red") {
        return "has-text-danger";
      }
      if (tab === "yellow") {
        return "has-text-warning";
      }
      if (tab === "none") {
        return "has-text-success";
      }
      return "has-text-grey-dark";
    };
    const isPossibleDuplicatesView = computed(() => view.variables.currentView.value === "possible_duplicates");
    const possibleDuplicateGroupsInCurrentView = computed(
      () => buildPossibleDuplicateGroups(customersInCurrentView.value, {
        getTransactions: getTransactionsInView
      })
    );
    const onClickDuplicateGroup = (duplicateGroup) => {
      expandedDuplicateGroupKey.value = expandedDuplicateGroupKey.value === duplicateGroup.key ? null : duplicateGroup.key;
    };
    const isDuplicateGroupExpanded = (duplicateGroup) => expandedDuplicateGroupKey.value === duplicateGroup.key;
    const getDuplicateGroupTransactionIds = (duplicateGroup) => {
      return (duplicateGroup.transactions ?? []).filter((transaction) => transaction.excluded !== true).map((transaction) => transaction.id).filter((transactionId) => transactionId !== null && transactionId !== void 0);
    };
    const getDuplicateGroupExcludedTransactionIds = (duplicateGroup) => {
      return (duplicateGroup.transactions ?? []).filter((transaction) => transaction.excluded === true).map((transaction) => transaction.id).filter((transactionId) => transactionId !== null && transactionId !== void 0);
    };
    const getDuplicateGroupStatusColorClass = (duplicateGroup) => {
      if (duplicateGroup?.draft?.is_action_blocked === true) {
        return "has-text-warning";
      }
      return duplicateGroup.requires_action ? "has-text-danger" : "has-text-success";
    };
    const getDuplicateGroupCustomerLabel = (duplicateGroup) => {
      const customerCount = duplicateGroup.customers?.length ?? 0;
      return `${customerCount} ${customerCount === 1 ? "kunde" : "kunder"}`;
    };
    const getDuplicateGroupTransactionLabel = (duplicateGroup) => {
      const transactionCount = duplicateGroup.transactions?.length ?? 0;
      return `${transactionCount} vaskelog`;
    };
    const getDuplicateTransactionCustomerLabel = (transaction) => {
      const customerName = String(transaction?.customer_name ?? "").trim();
      const customerNumber = transaction?.customer_number ? `#${transaction.customer_number}` : "";
      return [customerName, customerNumber].filter(Boolean).join(" ");
    };
    const getDuplicateTransactionDateLabel = (transaction) => formatDuplicateDateLabel(
      getDuplicateTransactionDateKey(transaction)
    );
    const getDuplicateTransactionAmountLabel = (transaction) => SessionUser.functions.currency.toLocal(
      getDuplicateTransactionAmount(transaction)
    );
    const getTransactionIds = (customer) => {
      if (!customer.transactions || customer.transactions.length === 0) {
        return [];
      }
      return customer.transactions.filter((transaction) => transaction.excluded !== true).map((transaction) => transaction.id);
    };
    const getAllTransactionIds = (customer) => {
      if (!customer.transactions || customer.transactions.length === 0) {
        return [];
      }
      return customer.transactions.map((transaction) => transaction.id).filter((transactionId) => transactionId !== null && transactionId !== void 0);
    };
    const getExcludedTransactionIds = (customer) => {
      if (!customer.transactions || customer.transactions.length === 0) {
        return [];
      }
      return customer.transactions.filter((transaction) => transaction.excluded === true).map((transaction) => transaction.id);
    };
    const transactionIdsInvoiceCollectionCache = ref({});
    const parsePositiveInteger = (value) => {
      const parsed = Number.parseInt(String(value), 10);
      return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
    };
    const getCustomerNumber = (customer) => parsePositiveInteger(customer?.customer_number);
    const markCustomerPeriodRefreshLoading = (customer) => {
      const customerNumber = getCustomerNumber(customer);
      if (customerNumber) {
        invoiceQueue.markPeriodRefreshLoading?.([customerNumber], []);
      }
    };
    const queueInvoiceCollections = (invoiceCollectionIds, customer = null) => {
      const uniqueInvoiceCollectionIds = Array.from(
        new Set(
          invoiceCollectionIds.filter(
            (invoiceCollectionId) => Number.isInteger(invoiceCollectionId) && invoiceCollectionId > 0
          )
        )
      );
      if (uniqueInvoiceCollectionIds.length === 0) {
        return;
      }
      invoiceQueue.addInvoiceCollectionsToQueue(uniqueInvoiceCollectionIds, {
        customerNumber: getCustomerNumber(customer)
      });
      invoiceQueue.processInvoiceCollectionQueue();
    };
    const onClickInvoiceNow = async (customer, transactionIds) => {
      const customerNumber = getCustomerNumber(customer);
      try {
        if (transactionIds.length === 0) {
          markCustomerPeriodRefreshLoading(customer);
          const month = dates.variables.start.value.getMonth() + 1;
          const year = dates.variables.start.value.getFullYear();
          if (customer?.meta?.fixed_pricing) {
            const response = await SessionUser.objects.collectedOrderInvoices.functions.createVehicleSubscriptionInvoice(customer.customer_number, month, year);
            const newInvoiceCollectionId = parsePositiveInteger(response?.data?.data?.id);
            if (!newInvoiceCollectionId) {
              invoiceQueue.finishPeriodRefresh?.([customerNumber], []);
              return;
            }
            await SessionUser.objects.collectedOrderInvoices.functions.add_fixed_pricing(newInvoiceCollectionId);
            queueInvoiceCollections([newInvoiceCollectionId], customer);
          } else if (view.variables.currentView.value === "vehicle_subscriptions") {
            const response = await SessionUser.objects.collectedOrderInvoices.functions.createVehicleSubscriptionInvoice(customer.customer_number, month, year);
            const newInvoiceCollectionId = parsePositiveInteger(response?.data?.data?.id);
            if (!newInvoiceCollectionId) {
              invoiceQueue.finishPeriodRefresh?.([customerNumber], []);
              return;
            }
            await SessionUser.objects.collectedOrderInvoices.functions.add_vehicle_subscriptions(newInvoiceCollectionId);
            queueInvoiceCollections([newInvoiceCollectionId], customer);
          } else {
            invoiceQueue.finishPeriodRefresh?.([customerNumber], []);
          }
          return;
        }
        await fetchMissingInvoiceCollections(customer, transactionIds);
        const invoiceCollectionIds = getInvoiceCollectionIdsForTransactionIds(customer, transactionIds);
        if (invoiceCollectionIds.length === 0) {
          return;
        }
        const invoiceWarningContext = buildMultiMonthInvoiceContext(
          transactionIds.map((transactionId) => getTransactionById(customer, transactionId)).filter((transaction) => transaction !== null),
          {
            getDate: (transaction) => transaction?.date ?? transaction?.created_at,
            getInvoiceCollectionId: (transaction) => getTransactionInvoiceCollectionId(transaction)
          }
        );
        const invoiceWarningAction = await promptMultiMonthInvoiceWarning({
          context: invoiceWarningContext,
          splitByMonth: SessionUser.objects.collectedOrderInvoices.functions.split_by_month,
          parseErrorMessage: SessionUser.functions.parseErrorMessage
        });
        if (invoiceWarningAction === MULTI_MONTH_INVOICE_ACTION.SPLIT) {
          reloadPeriodPage();
          return;
        }
        if (invoiceWarningAction === MULTI_MONTH_INVOICE_ACTION.CANCEL) {
          return;
        }
        markCustomerPeriodRefreshLoading(customer);
        queueInvoiceCollections(invoiceCollectionIds, customer);
      } catch (error) {
        invoiceQueue.finishPeriodRefresh?.([customerNumber], []);
        console.error("Error queueing invoice collection:", error);
      }
    };
    const getTransactionById = (customer, transactionId) => {
      return Array.isArray(customer?.transactions) ? customer.transactions.find((transaction) => Number(transaction?.id) === Number(transactionId)) : null;
    };
    const fetchMissingInvoiceCollections = async (customer, transactionIds) => {
      const uncachedTransactionIds = transactionIds.filter(
        (transactionId) => !(transactionId in transactionIdsInvoiceCollectionCache.value) && getTransactionInvoiceCollectionId(getTransactionById(customer, transactionId) ?? { id: transactionId }) === null
      );
      if (uncachedTransactionIds.length === 0) {
        return Promise.resolve();
      }
      return SessionUser.objects.orders.get.multiple(uncachedTransactionIds).then((orders) => {
        orders.forEach((order) => {
          transactionIdsInvoiceCollectionCache.value[order.id] = order.invoice_collection_id;
        });
      });
    };
    const getTransactionInvoiceCollectionId = (transaction) => {
      const directInvoiceCollectionId = Number.parseInt(String(transaction?.invoice_collection_id ?? ""), 10);
      if (Number.isInteger(directInvoiceCollectionId) && directInvoiceCollectionId > 0) {
        return directInvoiceCollectionId;
      }
      const cachedInvoiceCollectionId = transactionIdsInvoiceCollectionCache.value[transaction?.id];
      return Number.isInteger(cachedInvoiceCollectionId) && (cachedInvoiceCollectionId ?? 0) > 0 ? cachedInvoiceCollectionId : null;
    };
    const getInvoiceCollectionIdsForTransactionIds = (customer, transactionIds) => {
      return transactionIds.map(
        (transactionId) => getTransactionInvoiceCollectionId(getTransactionById(customer, transactionId) ?? { id: transactionId })
      ).filter((invoiceCollectionId) => invoiceCollectionId !== null);
    };
    const isInvoiceCollectionQueuedLocally = (invoiceCollectionId) => {
      if (!invoiceCollectionId) {
        return false;
      }
      return invoiceQueue.invoiceCollectionQueueInProgress.value.includes(invoiceCollectionId) || invoiceQueue.invoiceCollectionQueue.value.includes(invoiceCollectionId);
    };
    const getCustomerActionableTransactions = (customer) => {
      return getTransactionsInView(customer).filter(
        (transaction) => transaction?.booked !== true && transaction?.excluded !== true
      );
    };
    const getLocalQueuedInvoiceCollectionIdsForCustomer = (customer) => {
      return Array.from(
        new Set(
          getCustomerActionableTransactions(customer).map((transaction) => getTransactionInvoiceCollectionId(transaction)).filter(
            (invoiceCollectionId) => Number.isInteger(invoiceCollectionId) && (invoiceCollectionId ?? 0) > 0 && isInvoiceCollectionQueuedLocally(invoiceCollectionId)
          )
        )
      );
    };
    const getCustomerQueueStatuses = (customer) => {
      const backendStatuses = Array.isArray(customer?.queue?.statuses) ? Array.from(
        new Set(customer.queue.statuses.filter((status) => typeof status === "string" && status.length > 0))
      ) : [];
      if (backendStatuses.length > 0) {
        return backendStatuses;
      }
      const queuedInvoiceCollectionIds = getLocalQueuedInvoiceCollectionIdsForCustomer(customer);
      if (queuedInvoiceCollectionIds.length === 0) {
        return [];
      }
      const statuses = [];
      const hasProcessing = queuedInvoiceCollectionIds.some(
        (invoiceCollectionId) => invoiceQueue.invoiceCollectionQueueInProgress.value.includes(invoiceCollectionId)
      );
      const hasQueued = queuedInvoiceCollectionIds.some(
        (invoiceCollectionId) => invoiceQueue.invoiceCollectionQueue.value.includes(invoiceCollectionId)
      );
      if (hasProcessing) {
        statuses.push(ECONOMIC_QUEUE_STATUS.PROCESSING);
      }
      if (hasQueued) {
        statuses.push(ECONOMIC_QUEUE_STATUS.QUEUED);
      }
      return statuses;
    };
    const isCustomerQueueBlocked = (customer) => {
      if (customer?.queue?.is_action_blocked === true) {
        return true;
      }
      const actionableTransactions = getCustomerActionableTransactions(customer);
      if (actionableTransactions.length === 0) {
        return false;
      }
      return actionableTransactions.every((transaction) => {
        const invoiceCollectionId = getTransactionInvoiceCollectionId(transaction);
        return Number.isInteger(invoiceCollectionId) && (invoiceCollectionId ?? 0) > 0 && isInvoiceCollectionQueuedLocally(invoiceCollectionId);
      });
    };
    const isCustomerDraftBlocked = (customer) => {
      return customer?.draft?.is_action_blocked === true;
    };
    const isActiveFlag = (flag) => String(flag?.status || "active") === "active";
    const getActiveFlags = (flags = []) => flags.filter((flag) => isActiveFlag(flag));
    const sortCustomerFlags = (flags = []) => [...flags].sort((left, right) => {
      const sourceOrder = { manual: 0, automatic: 1 };
      const leftSource = sourceOrder[left?.source] ?? 99;
      const rightSource = sourceOrder[right?.source] ?? 99;
      if (leftSource !== rightSource) {
        return leftSource - rightSource;
      }
      return String(left?.created_at || left?.fingerprint || "").localeCompare(String(right?.created_at || right?.fingerprint || ""));
    });
    const flagIdentity = (flag) => String(flag?.id || flag?.fingerprint || "");
    const getFlagCounts = (flags = []) => {
      const counts = { manual: 0, automatic: 0, total: 0 };
      getActiveFlags(flags).forEach((flag) => {
        if (flag?.source === "manual") {
          counts.manual += 1;
        } else if (flag?.source === "automatic") {
          counts.automatic += 1;
        }
      });
      counts.total = counts.manual + counts.automatic;
      return counts;
    };
    const toPositiveIntegerSet = (values = []) => new Set(
      values.map((value) => parsePositiveInteger(value)).filter((value) => value !== null)
    );
    const getFlagOrderId = (flag) => {
      const targetType = String(flag?.target_type || "");
      return parsePositiveInteger(
        flag?.order_id ?? flag?.context?.order_id ?? (["order", "order_field"].includes(targetType) ? flag?.target_id : null)
      );
    };
    const getFlagInvoiceCollectionId = (flag) => parsePositiveInteger(
      flag?.invoice_collection_id ?? flag?.context?.invoice_collection_id ?? (String(flag?.target_type || "") === "collected_order_invoice" ? flag?.target_id : null)
    );
    const isFlagInCustomerCardScope = (customer, flag) => {
      if (!isActiveFlag(flag)) {
        return false;
      }
      const targetType = String(flag?.target_type || "");
      const flagCustomerNumber = Number(flag?.customer_number || 0);
      if (flagCustomerNumber > 0 && flagCustomerNumber === Number(customer?.customer_number || 0)) {
        return true;
      }
      if (targetType === "customer") {
        return Number(flag?.customer_number || flag?.target_id || 0) === Number(customer?.customer_number || 0);
      }
      const transactionIds = getAllTransactionIds(customer);
      const transactionIdSet = toPositiveIntegerSet(transactionIds);
      if (["order", "order_field", "order_item", "order_item_field"].includes(targetType)) {
        const orderId = getFlagOrderId(flag);
        return orderId !== null && transactionIdSet.has(orderId);
      }
      if (targetType === "collected_order_invoice") {
        const invoiceCollectionId = getFlagInvoiceCollectionId(flag);
        return invoiceCollectionId !== null && toPositiveIntegerSet(getInvoiceCollectionIdsForTransactionIds(customer, transactionIds)).has(invoiceCollectionId);
      }
      return false;
    };
    const getCustomerScopedFlags = (customer) => sortCustomerFlags(
      getActiveFlags(customer?.flags || []).filter((flag) => isFlagInCustomerCardScope(customer, flag))
    );
    const getCustomerActiveFlagCounts = (customer) => {
      const scopedFlags = getCustomerScopedFlags(customer);
      if (Array.isArray(customer?.flags)) {
        return getFlagCounts(scopedFlags);
      }
      return {
        manual: Number(customer?.flag_counts?.manual ?? 0),
        automatic: Number(customer?.flag_counts?.automatic ?? 0),
        total: Number(customer?.flag_counts?.total ?? 0)
      };
    };
    const getCustomerStatusColorClass = (customer) => {
      const flagCounts = getCustomerActiveFlagCounts(customer);
      if (flagCounts.manual > 0) {
        return "has-text-danger";
      }
      if (flagCounts.automatic > 0) {
        return "has-text-warning";
      }
      if (isCustomerDraftBlocked(customer)) {
        return "has-text-warning";
      }
      return customer.requires_action ? "has-text-danger" : "has-text-success";
    };
    const getCustomerStatusIconClass = (customer) => {
      if (getCustomerActiveFlagCounts(customer).total > 0) {
        return "fas fa-flag";
      }
      return "fas fa-circle";
    };
    const isOrderLineFlag = (flag) => ["order", "order_field"].includes(String(flag?.target_type || ""));
    const isOrderItemLineFlag = (flag) => ["order_item", "order_item_field"].includes(String(flag?.target_type || ""));
    const getCustomerCardFlags = (customer) => getCustomerScopedFlags(customer).filter((flag) => !isOrderLineFlag(flag) && !isOrderItemLineFlag(flag));
    const recomputeCustomerFlagState = (customer) => {
      customer.flags = sortCustomerFlags(getActiveFlags(customer.flags || []));
      customer.flag_counts = getCustomerActiveFlagCounts(customer);
      if (customer.flag_counts.manual > 0) {
        customer.status_indicator = "flag_red";
      } else if (customer.flag_counts.automatic > 0) {
        customer.status_indicator = "flag_yellow";
      } else if (isCustomerDraftBlocked(customer)) {
        customer.status_indicator = "circle_yellow";
      } else {
        customer.status_indicator = customer.requires_action ? "circle_red" : "circle_green";
      }
    };
    const forEachPeriodCustomerWithNumber = (customerNumber, callback) => {
      const types = view.variables.sharedVariables.value?.types || {};
      Object.values(types).forEach((customers) => {
        if (!Array.isArray(customers)) {
          return;
        }
        customers.forEach((candidate) => {
          if (Number(candidate?.customer_number) === Number(customerNumber)) {
            callback(candidate);
          }
        });
      });
    };
    const onFlagCreated = (customer, flag) => {
      const customerNumber = Number(flag?.customer_number || customer?.customer_number || 0);
      if (customerNumber < 1) {
        return;
      }
      forEachPeriodCustomerWithNumber(customerNumber, (candidate) => {
        const existing = Array.isArray(candidate.flags) ? candidate.flags : [];
        const nextFlag = { ...flag, source: "manual", severity: "red", status: "active" };
        candidate.flags = sortCustomerFlags([
          ...existing.filter((item) => flagIdentity(item) !== flagIdentity(nextFlag)),
          nextFlag
        ]);
        recomputeCustomerFlagState(candidate);
      });
      reloadPeriodPage();
    };
    const onFlagStatusChanged = (customer, flag) => {
      const customerNumber = Number(flag?.customer_number || customer?.customer_number || 0);
      const identity = flagIdentity(flag);
      if (customerNumber < 1 || identity === "") {
        return;
      }
      forEachPeriodCustomerWithNumber(customerNumber, (candidate) => {
        candidate.flags = (candidate.flags || []).filter((item) => flagIdentity(item) !== identity);
        recomputeCustomerFlagState(candidate);
      });
      reloadPeriodPage();
    };
    const isCustomerQueueProcessing = (customer) => {
      return getCustomerQueueStatuses(customer).includes(ECONOMIC_QUEUE_STATUS.PROCESSING);
    };
    const getCustomerQueueLabel = (customer) => {
      if (isCustomerQueueProcessing(customer)) {
        return SessionUser.objects.global.language.processing ?? "Processing";
      }
      return SessionUser.objects.global.language.queued ?? "Queued";
    };
    const isCustomerPeriodActionLoading = (customer) => {
      const customerNumber = getCustomerNumber(customer);
      if (!customerNumber || typeof invoiceQueue.isPeriodCustomerRefreshLoading !== "function") {
        return false;
      }
      return invoiceQueue.isPeriodCustomerRefreshLoading(customerNumber);
    };
    const isAllCustomerTransactionsBooked = (customer, transactionIds) => {
      if (!customer.transactions || customer.transactions.length === 0 || transactionIds.length === 0) {
        return false;
      }
      const bookedTransactionIds = customer.transactions.filter((transaction) => transaction.booked === true).map((transaction) => transaction.id);
      const excludedTransactionIds = customer.transactions.filter((transaction) => transaction.excluded === true).map((transaction) => transaction.id);
      return transactionIds.every((transactionId) => bookedTransactionIds.includes(transactionId)) || transactionIds.every((transactionId) => excludedTransactionIds.includes(transactionId));
    };
    const getTransactionQueryParameters = () => {
      return {
        show_wash_subscription: true,
        show_vehicle_subscription: true,
        show_fixed_pricing: true
      };
    };
    const __returned__ = { expandedDuplicateGroupKey, onClickCustomer, getTransactionsInView, getCustomerTransactionsInView, doesCustomerHaveTransactionsDifferentDays, tmpFilters, periodSearchInput, get periodSearchDebounceTimer() {
      return periodSearchDebounceTimer;
    }, set periodSearchDebounceTimer(v) {
      periodSearchDebounceTimer = v;
    }, commitPeriodSearch, onPeriodSearchInput, setPeriodPage, onPeriodLimitChange, reloadPeriodPage, loadPeriodPage, onFilterChanged, customersInCurrentView, selectedFlagTab, getCustomerFlagTabType, toNonNegativeInteger, periodFlagTabCounts, filteredCustomersInCurrentView, getPeriodFlagTabIconClass, isPossibleDuplicatesView, possibleDuplicateGroupsInCurrentView, onClickDuplicateGroup, isDuplicateGroupExpanded, getDuplicateGroupTransactionIds, getDuplicateGroupExcludedTransactionIds, getDuplicateGroupStatusColorClass, getDuplicateGroupCustomerLabel, getDuplicateGroupTransactionLabel, getDuplicateTransactionCustomerLabel, getDuplicateTransactionDateLabel, getDuplicateTransactionAmountLabel, getTransactionIds, getAllTransactionIds, getExcludedTransactionIds, transactionIdsInvoiceCollectionCache, parsePositiveInteger, getCustomerNumber, markCustomerPeriodRefreshLoading, queueInvoiceCollections, onClickInvoiceNow, getTransactionById, fetchMissingInvoiceCollections, getTransactionInvoiceCollectionId, getInvoiceCollectionIdsForTransactionIds, isInvoiceCollectionQueuedLocally, getCustomerActionableTransactions, getLocalQueuedInvoiceCollectionIdsForCustomer, getCustomerQueueStatuses, isCustomerQueueBlocked, isCustomerDraftBlocked, isActiveFlag, getActiveFlags, sortCustomerFlags, flagIdentity, getFlagCounts, toPositiveIntegerSet, getFlagOrderId, getFlagInvoiceCollectionId, isFlagInCustomerCardScope, getCustomerScopedFlags, getCustomerActiveFlagCounts, getCustomerStatusColorClass, getCustomerStatusIconClass, isOrderLineFlag, isOrderItemLineFlag, getCustomerCardFlags, recomputeCustomerFlagState, forEachPeriodCustomerWithNumber, onFlagCreated, onFlagStatusChanged, isCustomerQueueProcessing, getCustomerQueueLabel, isCustomerPeriodActionLoading, isAllCustomerTransactionsBooked, getTransactionQueryParameters, view, dates, get PERIOD_LIMIT_OPTIONS() {
      return PERIOD_LIMIT_OPTIONS;
    }, get periodPageCount() {
      return periodPageCount;
    }, get periodPaging() {
      return periodPaging;
    }, SessionUser, ColorIndicator, WhiteBox, ActionSettingsWheelButton, InvoiceOrdersPagination, SmallCustomerActivityChart, InvoicingBillingPeriodStatistics, InvoicingBillingPeriodFilters, InvoicingBillingPeriodCustomerAttributes, InvoicingPeriodFlagList, PaginationNavigation, get getDuplicateTransactionPlate() {
      return getDuplicateTransactionPlate;
    } };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$E = ["data-current-view"];
const _hoisted_2$w = {
  class: "columns is-vcentered is-multiline pagination-general-search-reload",
  "data-testid": "invoicing-period-page-controls"
};
const _hoisted_3$s = { class: "column pagination-general-search-reload__search-column" };
const _hoisted_4$s = ["placeholder"];
const _hoisted_5$r = { class: "column is-narrow pl-0 pagination-general-search-reload__action-column" };
const _hoisted_6$r = ["disabled"];
const _hoisted_7$q = {
  key: 0,
  class: "py-2"
};
const _hoisted_8$q = { class: "columns is-vcentered is-multiline is-mobile" };
const _hoisted_9$o = { class: "column is-narrow my-3" };
const _hoisted_10$n = { class: "control" };
const _hoisted_11$j = { class: "select" };
const _hoisted_12$i = ["value"];
const _hoisted_13$g = ["value"];
const _hoisted_14$f = {
  key: 1,
  class: "py-2"
};
const _hoisted_15$f = { class: "period-flag-tab-header" };
const _hoisted_16$f = { class: "icon is-small" };
const _hoisted_17$d = { class: "tag is-light is-rounded" };
const _hoisted_18$d = { class: "period-flag-tab-header" };
const _hoisted_19$b = { class: "icon is-small" };
const _hoisted_20$a = { class: "tag is-light is-rounded" };
const _hoisted_21$a = { class: "period-flag-tab-header" };
const _hoisted_22$a = { class: "icon is-small" };
const _hoisted_23$a = { class: "tag is-light is-rounded" };
const _hoisted_24$a = { class: "period-flag-tab-header" };
const _hoisted_25$a = { class: "icon is-small" };
const _hoisted_26$a = { class: "tag is-light is-rounded" };
const _hoisted_27$9 = { class: "period-flag-tab-content py-2" };
const _hoisted_28$9 = {
  class: "columns is-vcentered is-multiline is-mobile",
  "data-testid": "invoicing-period-table-filters"
};
const _hoisted_29$8 = { class: "column is-narrow my-3" };
const _hoisted_30$8 = { class: "control" };
const _hoisted_31$8 = { class: "select" };
const _hoisted_32$8 = ["value"];
const _hoisted_33$8 = ["value"];
const _hoisted_34$8 = {
  key: 2,
  class: "columns is-multiline is-mobile"
};
const _hoisted_35$8 = ["onClick"];
const _hoisted_36$7 = { class: "column is-narrow duplicate-group-status" };
const _hoisted_37$7 = { class: "icon is-small" };
const _hoisted_38$7 = { class: "column is-narrow duplicate-group-tags" };
const _hoisted_39$7 = ["data-testid"];
const _hoisted_40$7 = ["data-testid"];
const _hoisted_41$7 = { class: "column is-narrow" };
const _hoisted_42$7 = { class: "column is-narrow" };
const _hoisted_43$7 = { class: "column is-narrow" };
const _hoisted_44$7 = { class: "column duplicate-group-customers" };
const _hoisted_45$7 = { class: "column is-narrow" };
const _hoisted_46$7 = { class: "icon is-small" };
const _hoisted_47$7 = ["data-testid"];
const _hoisted_48$7 = ["data-testid"];
const _hoisted_49$6 = { class: "duplicate-comparison-grid" };
const _hoisted_50$6 = ["data-testid"];
const _hoisted_51$6 = {
  key: 3,
  class: "columns is-multiline is-mobile"
};
const _hoisted_52$6 = ["onClick"];
const _hoisted_53$5 = { class: "column" };
const _hoisted_54$5 = { class: "column is-narrow" };
const _hoisted_55$5 = { class: "column is-narrow" };
const _hoisted_56$5 = { class: "column is-narrow" };
const _hoisted_57$5 = { key: 0 };
const _hoisted_58$5 = { key: 1 };
const _hoisted_59$4 = { class: "column is-narrow" };
const _hoisted_60$4 = {
  key: 0,
  class: "has-text-grey-light is-size-7"
};
const _hoisted_61$4 = {
  key: 0,
  class: "column is-narrow"
};
const _hoisted_62$4 = { class: "tag is-success is-light is-small" };
const _hoisted_63$3 = {
  key: 1,
  class: "column is-narrow"
};
const _hoisted_64$2 = ["data-testid"];
const _hoisted_65$2 = {
  key: 2,
  class: "column is-narrow"
};
const _hoisted_66$2 = ["data-testid"];
const _hoisted_67$2 = {
  key: 3,
  class: "column is-narrow"
};
const _hoisted_68$2 = ["disabled", "onClick", "data-testid"];
const _hoisted_69$2 = { class: "column is-narrow" };
const _hoisted_70$2 = ["data-testid"];
const _hoisted_71$2 = {
  class: "mt-3",
  "data-testid": "invoicing-period-pagination-navigation"
};
function _sfc_render$L(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_b_tab_item = resolveComponent("b-tab-item");
  const _component_b_tabs = resolveComponent("b-tabs");
  return openBlock(), createElementBlock("div", {
    "data-testid": "invoicing-period-view-all",
    "data-current-view": $setup.view.variables.currentView.value
  }, [
    createVNode($setup["InvoicingBillingPeriodStatistics"]),
    createBaseVNode("div", _hoisted_2$w, [
      createBaseVNode("div", _hoisted_3$s, [
        withDirectives(createBaseVNode("input", {
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => $setup.periodSearchInput = $event),
          class: "input",
          type: "text",
          placeholder: $setup.SessionUser.objects.global.language.search ?? "Search",
          "data-testid": "invoicing-period-search-input",
          onInput: $setup.onPeriodSearchInput
        }, null, 40, _hoisted_4$s), [
          [vModelText, $setup.periodSearchInput]
        ])
      ]),
      createBaseVNode("div", _hoisted_5$r, [
        createBaseVNode("button", {
          type: "button",
          class: normalizeClass(["button is-dark button-same-width action-dropdown-main is-inverted", { "is-loading": $setup.periodPaging.isRefreshing }]),
          disabled: $setup.periodPaging.isRefreshing,
          "data-testid": "invoicing-period-page-reload-button",
          onClick: $setup.reloadPeriodPage
        }, [
          _cache[3] || (_cache[3] = createBaseVNode(
            "span",
            { class: "icon is-small" },
            [
              createBaseVNode("i", { class: "fas fa-sync-alt" })
            ],
            -1
            /* CACHED */
          )),
          createBaseVNode(
            "span",
            null,
            toDisplayString($setup.SessionUser.objects.global.language.reload ?? $setup.SessionUser.objects.global.language.update ?? "Reload"),
            1
            /* TEXT */
          )
        ], 10, _hoisted_6$r)
      ])
    ]),
    $setup.isPossibleDuplicatesView ? (openBlock(), createElementBlock("div", _hoisted_7$q, [
      createBaseVNode("div", _hoisted_8$q, [
        createBaseVNode("div", _hoisted_9$o, [
          _cache[4] || (_cache[4] = createBaseVNode(
            "label",
            { class: "label is-small" },
            "Per page",
            -1
            /* CACHED */
          )),
          createBaseVNode("div", _hoisted_10$n, [
            createBaseVNode("div", _hoisted_11$j, [
              createBaseVNode("select", {
                value: $setup.periodPaging.limit,
                "data-testid": "invoicing-period-limit-select",
                onChange: $setup.onPeriodLimitChange
              }, [
                (openBlock(true), createElementBlock(
                  Fragment,
                  null,
                  renderList($setup.PERIOD_LIMIT_OPTIONS, (limit) => {
                    return openBlock(), createElementBlock("option", {
                      key: limit,
                      value: limit
                    }, toDisplayString(limit === "all" ? "All" : limit), 9, _hoisted_13$g);
                  }),
                  128
                  /* KEYED_FRAGMENT */
                ))
              ], 40, _hoisted_12$i)
            ])
          ])
        ])
      ])
    ])) : createCommentVNode("v-if", true),
    !$setup.isPossibleDuplicatesView ? (openBlock(), createElementBlock("div", _hoisted_14$f, [
      createVNode(_component_b_tabs, {
        modelValue: $setup.selectedFlagTab,
        "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => $setup.selectedFlagTab = $event),
        expanded: "",
        class: normalizeClass(["period-flag-tabs", { "is-filters-tab-selected": $setup.selectedFlagTab === "filters" }]),
        "data-testid": "invoicing-period-flag-tabs"
      }, {
        default: withCtx(() => [
          createVNode(_component_b_tab_item, { value: "all" }, {
            header: withCtx(() => [
              createBaseVNode("span", _hoisted_15$f, [
                createBaseVNode("span", _hoisted_16$f, [
                  createBaseVNode(
                    "i",
                    {
                      class: normalizeClass(["fas fa-flag", $setup.getPeriodFlagTabIconClass("all")])
                    },
                    null,
                    2
                    /* CLASS */
                  )
                ]),
                _cache[5] || (_cache[5] = createBaseVNode(
                  "span",
                  null,
                  "All",
                  -1
                  /* CACHED */
                )),
                createBaseVNode(
                  "span",
                  _hoisted_17$d,
                  toDisplayString($setup.periodFlagTabCounts.all),
                  1
                  /* TEXT */
                )
              ])
            ]),
            _: 1
            /* STABLE */
          }),
          createVNode(_component_b_tab_item, { value: "red" }, {
            header: withCtx(() => [
              createBaseVNode("span", _hoisted_18$d, [
                createBaseVNode("span", _hoisted_19$b, [
                  createBaseVNode(
                    "i",
                    {
                      class: normalizeClass(["fas fa-flag", $setup.getPeriodFlagTabIconClass("red")])
                    },
                    null,
                    2
                    /* CLASS */
                  )
                ]),
                _cache[6] || (_cache[6] = createBaseVNode(
                  "span",
                  null,
                  "Red flags",
                  -1
                  /* CACHED */
                )),
                createBaseVNode(
                  "span",
                  _hoisted_20$a,
                  toDisplayString($setup.periodFlagTabCounts.red),
                  1
                  /* TEXT */
                )
              ])
            ]),
            _: 1
            /* STABLE */
          }),
          createVNode(_component_b_tab_item, { value: "yellow" }, {
            header: withCtx(() => [
              createBaseVNode("span", _hoisted_21$a, [
                createBaseVNode("span", _hoisted_22$a, [
                  createBaseVNode(
                    "i",
                    {
                      class: normalizeClass(["fas fa-flag", $setup.getPeriodFlagTabIconClass("yellow")])
                    },
                    null,
                    2
                    /* CLASS */
                  )
                ]),
                _cache[7] || (_cache[7] = createBaseVNode(
                  "span",
                  null,
                  "Yellow flags",
                  -1
                  /* CACHED */
                )),
                createBaseVNode(
                  "span",
                  _hoisted_23$a,
                  toDisplayString($setup.periodFlagTabCounts.yellow),
                  1
                  /* TEXT */
                )
              ])
            ]),
            _: 1
            /* STABLE */
          }),
          createVNode(_component_b_tab_item, { value: "none" }, {
            header: withCtx(() => [
              createBaseVNode("span", _hoisted_24$a, [
                createBaseVNode("span", _hoisted_25$a, [
                  createBaseVNode(
                    "i",
                    {
                      class: normalizeClass(["fas fa-flag", $setup.getPeriodFlagTabIconClass("none")])
                    },
                    null,
                    2
                    /* CLASS */
                  )
                ]),
                _cache[8] || (_cache[8] = createBaseVNode(
                  "span",
                  null,
                  "No flags",
                  -1
                  /* CACHED */
                )),
                createBaseVNode(
                  "span",
                  _hoisted_26$a,
                  toDisplayString($setup.periodFlagTabCounts.none),
                  1
                  /* TEXT */
                )
              ])
            ]),
            _: 1
            /* STABLE */
          }),
          createVNode(_component_b_tab_item, {
            value: "filters",
            class: "filters-tab",
            "data-testid": "invoicing-period-filters-tab"
          }, {
            header: withCtx(() => [..._cache[9] || (_cache[9] = [
              createBaseVNode(
                "span",
                { class: "period-flag-tab-header" },
                [
                  createBaseVNode("span", { class: "icon is-small" }, [
                    createBaseVNode("i", { class: "fas fa-filter" })
                  ]),
                  createBaseVNode("span", null, "Filters")
                ],
                -1
                /* CACHED */
              )
            ])]),
            default: withCtx(() => [
              createBaseVNode("div", _hoisted_27$9, [
                createBaseVNode("div", _hoisted_28$9, [
                  createBaseVNode("div", _hoisted_29$8, [
                    _cache[10] || (_cache[10] = createBaseVNode(
                      "label",
                      { class: "label is-small" },
                      "Per page",
                      -1
                      /* CACHED */
                    )),
                    createBaseVNode("div", _hoisted_30$8, [
                      createBaseVNode("div", _hoisted_31$8, [
                        createBaseVNode("select", {
                          value: $setup.periodPaging.limit,
                          "data-testid": "invoicing-period-limit-select",
                          onChange: $setup.onPeriodLimitChange
                        }, [
                          (openBlock(true), createElementBlock(
                            Fragment,
                            null,
                            renderList($setup.PERIOD_LIMIT_OPTIONS, (limit) => {
                              return openBlock(), createElementBlock("option", {
                                key: limit,
                                value: limit
                              }, toDisplayString(limit === "all" ? "All" : limit), 9, _hoisted_33$8);
                            }),
                            128
                            /* KEYED_FRAGMENT */
                          ))
                        ], 40, _hoisted_32$8)
                      ])
                    ])
                  ])
                ]),
                createVNode($setup["InvoicingBillingPeriodFilters"], {
                  onFilterChanged: _cache[1] || (_cache[1] = (filters) => $setup.onFilterChanged(filters))
                })
              ])
            ]),
            _: 1
            /* STABLE */
          })
        ]),
        _: 1
        /* STABLE */
      }, 8, ["modelValue", "class"])
    ])) : createCommentVNode("v-if", true),
    $setup.isPossibleDuplicatesView ? (openBlock(), createElementBlock("div", _hoisted_34$8, [
      (openBlock(true), createElementBlock(
        Fragment,
        null,
        renderList($setup.possibleDuplicateGroupsInCurrentView, (duplicateGroup) => {
          return openBlock(), createElementBlock("div", {
            key: duplicateGroup.key,
            class: "column is-12"
          }, [
            createVNode($setup["WhiteBox"], {
              class: "mb-2 duplicate-group-card",
              "has-border": true,
              "data-testid": `invoicing-period-duplicate-group-${duplicateGroup.testId}`
            }, {
              default: withCtx(() => [
                createBaseVNode("div", {
                  class: "columns is-vcentered is-clickable duplicate-group-header",
                  onClick: ($event) => $setup.onClickDuplicateGroup(duplicateGroup)
                }, [
                  createBaseVNode("div", _hoisted_36$7, [
                    createBaseVNode("span", _hoisted_37$7, [
                      createBaseVNode(
                        "i",
                        {
                          class: normalizeClass(["fas fa-circle", $setup.getDuplicateGroupStatusColorClass(duplicateGroup)])
                        },
                        null,
                        2
                        /* CLASS */
                      )
                    ])
                  ]),
                  createBaseVNode("div", _hoisted_38$7, [
                    createBaseVNode("span", {
                      class: "tag is-light duplicate-group-chip",
                      "data-testid": `invoicing-period-duplicate-plate-tag-${duplicateGroup.testId}`
                    }, [
                      _cache[11] || (_cache[11] = createBaseVNode(
                        "span",
                        { class: "icon is-small" },
                        [
                          createBaseVNode("i", { class: "fas fa-car-side" })
                        ],
                        -1
                        /* CACHED */
                      )),
                      createBaseVNode(
                        "span",
                        null,
                        toDisplayString(duplicateGroup.plate),
                        1
                        /* TEXT */
                      )
                    ], 8, _hoisted_39$7),
                    createBaseVNode("span", {
                      class: "tag is-light duplicate-group-chip",
                      "data-testid": `invoicing-period-duplicate-date-tag-${duplicateGroup.testId}`
                    }, [
                      _cache[12] || (_cache[12] = createBaseVNode(
                        "span",
                        { class: "icon is-small" },
                        [
                          createBaseVNode("i", { class: "fas fa-calendar-day" })
                        ],
                        -1
                        /* CACHED */
                      )),
                      createBaseVNode(
                        "span",
                        null,
                        toDisplayString(duplicateGroup.dateLabel),
                        1
                        /* TEXT */
                      )
                    ], 8, _hoisted_40$7)
                  ]),
                  createBaseVNode("div", _hoisted_41$7, [
                    createBaseVNode(
                      "p",
                      null,
                      toDisplayString($setup.getDuplicateGroupCustomerLabel(duplicateGroup)),
                      1
                      /* TEXT */
                    )
                  ]),
                  createBaseVNode("div", _hoisted_42$7, [
                    createBaseVNode(
                      "p",
                      null,
                      toDisplayString($setup.getDuplicateGroupTransactionLabel(duplicateGroup)),
                      1
                      /* TEXT */
                    )
                  ]),
                  createBaseVNode("div", _hoisted_43$7, [
                    createBaseVNode(
                      "p",
                      null,
                      toDisplayString($setup.SessionUser.functions.currency.toLocal(duplicateGroup.totalNetAmount)),
                      1
                      /* TEXT */
                    )
                  ]),
                  createBaseVNode("div", _hoisted_44$7, [
                    (openBlock(true), createElementBlock(
                      Fragment,
                      null,
                      renderList(duplicateGroup.customers, (customer) => {
                        return openBlock(), createElementBlock("span", {
                          key: `${duplicateGroup.key}-${customer.customer_number}-${customer.customer_name}`,
                          class: "tag is-light duplicate-customer-chip"
                        }, [
                          createTextVNode(
                            toDisplayString(customer.customer_name),
                            1
                            /* TEXT */
                          ),
                          customer.customer_number ? (openBlock(), createElementBlock(
                            Fragment,
                            { key: 0 },
                            [
                              createTextVNode(
                                " #" + toDisplayString(customer.customer_number),
                                1
                                /* TEXT */
                              )
                            ],
                            64
                            /* STABLE_FRAGMENT */
                          )) : createCommentVNode("v-if", true)
                        ]);
                      }),
                      128
                      /* KEYED_FRAGMENT */
                    ))
                  ]),
                  createBaseVNode("div", _hoisted_45$7, [
                    createBaseVNode("span", _hoisted_46$7, [
                      createBaseVNode(
                        "i",
                        {
                          class: normalizeClass(["fas", $setup.isDuplicateGroupExpanded(duplicateGroup) ? "fa-chevron-down" : "fa-chevron-right"])
                        },
                        null,
                        2
                        /* CLASS */
                      )
                    ])
                  ])
                ], 8, _hoisted_35$8),
                $setup.isDuplicateGroupExpanded(duplicateGroup) ? (openBlock(), createElementBlock("div", {
                  key: 0,
                  class: "duplicate-group-expanded",
                  "data-testid": `invoicing-period-duplicate-group-expanded-${duplicateGroup.testId}`
                }, [
                  createBaseVNode("div", {
                    class: "duplicate-comparison",
                    "data-testid": `invoicing-period-duplicate-comparison-${duplicateGroup.testId}`
                  }, [
                    _cache[16] || (_cache[16] = createBaseVNode(
                      "div",
                      { class: "duplicate-comparison-heading" },
                      "Sammenligning",
                      -1
                      /* CACHED */
                    )),
                    createBaseVNode("div", _hoisted_49$6, [
                      (openBlock(true), createElementBlock(
                        Fragment,
                        null,
                        renderList(duplicateGroup.transactions, (transaction) => {
                          return openBlock(), createElementBlock("div", {
                            key: `${duplicateGroup.key}-${transaction.id}`,
                            class: "duplicate-comparison-row",
                            "data-testid": `invoicing-period-duplicate-comparison-row-${transaction.id}`
                          }, [
                            createBaseVNode("div", null, [
                              createBaseVNode(
                                "strong",
                                null,
                                toDisplayString($setup.getDuplicateTransactionCustomerLabel(transaction)),
                                1
                                /* TEXT */
                              )
                            ]),
                            createBaseVNode("div", null, [
                              _cache[13] || (_cache[13] = createBaseVNode(
                                "span",
                                { class: "is-size-7 has-text-grey" },
                                "Nummerplade",
                                -1
                                /* CACHED */
                              )),
                              createBaseVNode(
                                "p",
                                null,
                                toDisplayString($setup.getDuplicateTransactionPlate(transaction) || "Ukendt"),
                                1
                                /* TEXT */
                              )
                            ]),
                            createBaseVNode("div", null, [
                              _cache[14] || (_cache[14] = createBaseVNode(
                                "span",
                                { class: "is-size-7 has-text-grey" },
                                "Dato",
                                -1
                                /* CACHED */
                              )),
                              createBaseVNode(
                                "p",
                                null,
                                toDisplayString($setup.getDuplicateTransactionDateLabel(transaction)),
                                1
                                /* TEXT */
                              )
                            ]),
                            createBaseVNode("div", null, [
                              _cache[15] || (_cache[15] = createBaseVNode(
                                "span",
                                { class: "is-size-7 has-text-grey" },
                                "Beløb",
                                -1
                                /* CACHED */
                              )),
                              createBaseVNode(
                                "p",
                                null,
                                toDisplayString($setup.getDuplicateTransactionAmountLabel(transaction)),
                                1
                                /* TEXT */
                              )
                            ])
                          ], 8, _hoisted_50$6);
                        }),
                        128
                        /* KEYED_FRAGMENT */
                      ))
                    ])
                  ], 8, _hoisted_48$7),
                  createVNode($setup["InvoiceOrdersPagination"], {
                    "hide-search": true,
                    "hide-filter": true,
                    "invoice-view": true,
                    "apply-default-filters": false,
                    "group-invoice-collection": false,
                    "limit-results": false,
                    "hide-pagination": true,
                    dates: {
                      dateFrom: duplicateGroup.dateKey || $setup.dates.computed.formattedStartDate.value,
                      dateTo: duplicateGroup.dateKey || $setup.dates.computed.formattedEndDate.value
                    },
                    "show-only-with-ids": $setup.getDuplicateGroupTransactionIds(duplicateGroup),
                    "query-parameters": $setup.getTransactionQueryParameters(),
                    "excluded-order-ids": $setup.getDuplicateGroupExcludedTransactionIds(duplicateGroup),
                    "invoice-period-flags": $setup.getActiveFlags(duplicateGroup.customers.flatMap((customer) => customer.flags || [])),
                    onFlagStatusChanged: (flag) => $setup.onFlagStatusChanged(duplicateGroup.customers[0] || {}, flag)
                  }, null, 8, ["dates", "show-only-with-ids", "query-parameters", "excluded-order-ids", "invoice-period-flags", "onFlagStatusChanged"])
                ], 8, _hoisted_47$7)) : createCommentVNode("v-if", true)
              ]),
              _: 2
              /* DYNAMIC */
            }, 1032, ["data-testid"])
          ]);
        }),
        128
        /* KEYED_FRAGMENT */
      ))
    ])) : (openBlock(), createElementBlock("div", _hoisted_51$6, [
      (openBlock(true), createElementBlock(
        Fragment,
        null,
        renderList($setup.filteredCustomersInCurrentView, (customer) => {
          return openBlock(), createElementBlock("div", {
            key: customer.customer_number,
            class: "column is-12"
          }, [
            createVNode($setup["WhiteBox"], {
              class: "mb-2",
              "has-border": true,
              "data-testid": `invoicing-period-customer-${customer.customer_number}`
            }, {
              default: withCtx(() => [
                createBaseVNode("div", {
                  class: "columns is-vcentered is-clickable",
                  onClick: ($event) => $setup.onClickCustomer(customer)
                }, [
                  createBaseVNode("div", _hoisted_53$5, [
                    createVNode($setup["ColorIndicator"], {
                      color_class: $setup.getCustomerStatusColorClass(customer),
                      icon_class: $setup.getCustomerStatusIconClass(customer),
                      label: {
                        text: customer.customer_name,
                        classes: []
                      },
                      visibility: {
                        icon: true,
                        dropdown: false
                      }
                    }, null, 8, ["color_class", "icon_class", "label"])
                  ]),
                  createBaseVNode("div", _hoisted_54$5, [
                    createVNode($setup["InvoicingBillingPeriodCustomerAttributes"], {
                      customer,
                      "is-expanded": customer.expanded || false
                    }, null, 8, ["customer", "is-expanded"])
                  ]),
                  createBaseVNode("div", _hoisted_55$5, [
                    $setup.tmpFilters.displayStatistics ? withDirectives((openBlock(), createBlock($setup["SmallCustomerActivityChart"], {
                      key: 0,
                      dates: {
                        dateFrom: $setup.dates.computed.formattedStartDate,
                        dateTo: $setup.dates.computed.formattedEndDate
                      },
                      transactions: customer.transactions
                    }, null, 8, ["dates", "transactions"])), [
                      [vShow, customer.transactions.length > 1 && $setup.doesCustomerHaveTransactionsDifferentDays(customer)]
                    ]) : createCommentVNode("v-if", true)
                  ]),
                  createBaseVNode("div", _hoisted_56$5, [
                    customer.transactions.length !== 0 ? (openBlock(), createElementBlock(
                      "p",
                      _hoisted_57$5,
                      toDisplayString($setup.view.functions.filterExcluded(customer.transactions).length) + " " + toDisplayString($setup.view.functions.filterExcluded(customer.transactions).length > 1 ? $setup.SessionUser.objects.orders.meta.labels.multiple : $setup.SessionUser.objects.orders.meta.labels.single),
                      1
                      /* TEXT */
                    )) : (openBlock(), createElementBlock(
                      "p",
                      _hoisted_58$5,
                      toDisplayString($setup.SessionUser.objects.global.language.none) + " " + toDisplayString($setup.SessionUser.objects.orders.meta.labels.multiple),
                      1
                      /* TEXT */
                    ))
                  ]),
                  createBaseVNode("div", _hoisted_59$4, [
                    createBaseVNode(
                      "p",
                      null,
                      toDisplayString($setup.SessionUser.functions.currency.toLocal(
                        $setup.view.functions.getCustomerViewTotalNetAmount(customer, {
                          includeFixedPricing: true,
                          includeVehicleSubscriptions: true,
                          includeTransactions: true
                        })
                      )),
                      1
                      /* TEXT */
                    ),
                    $setup.view.functions.getCustomerViewTotalNetAmount(customer, {
                      includeFixedPricing: true,
                      includeVehicleSubscriptions: true,
                      includeTransactions: true
                    }) !== $setup.view.functions.getCustomerViewTotalNetAmount(customer, {
                      includeFixedPricing: false,
                      includeVehicleSubscriptions: false,
                      includeTransactions: true
                    }) ? (openBlock(), createElementBlock(
                      "p",
                      _hoisted_60$4,
                      " (" + toDisplayString($setup.SessionUser.functions.currency.toLocal(
                        $setup.view.functions.getCustomerViewTotalNetAmount(customer, {
                          includeFixedPricing: false,
                          includeVehicleSubscriptions: false,
                          includeTransactions: true
                        })
                      )) + ") ",
                      1
                      /* TEXT */
                    )) : createCommentVNode("v-if", true)
                  ]),
                  $setup.isAllCustomerTransactionsBooked(customer, $setup.getCustomerTransactionsInView(customer)) && !customer.requires_action && $setup.getCustomerActiveFlagCounts(customer).total === 0 && !$setup.isCustomerQueueBlocked(customer) ? (openBlock(), createElementBlock("div", _hoisted_61$4, [
                    createBaseVNode("span", _hoisted_62$4, [
                      _cache[17] || (_cache[17] = createBaseVNode(
                        "span",
                        { class: "icon is-small" },
                        [
                          createBaseVNode("i", { class: "fas fa-check-circle" })
                        ],
                        -1
                        /* CACHED */
                      )),
                      createBaseVNode(
                        "span",
                        null,
                        toDisplayString($setup.SessionUser.objects.global.language.all_booked),
                        1
                        /* TEXT */
                      )
                    ])
                  ])) : $setup.isCustomerQueueBlocked(customer) ? (openBlock(), createElementBlock("div", _hoisted_63$3, [
                    createBaseVNode("button", {
                      class: normalizeClass(["button is-small is-dark", { "is-loading": $setup.isCustomerQueueProcessing(customer) || $setup.isCustomerPeriodActionLoading(customer) }]),
                      disabled: "",
                      "data-testid": `invoicing-period-customer-queue-${customer.customer_number}`
                    }, [
                      _cache[18] || (_cache[18] = createBaseVNode(
                        "span",
                        { class: "icon is-small" },
                        [
                          createBaseVNode("i", { class: "fas fa-file-invoice" })
                        ],
                        -1
                        /* CACHED */
                      )),
                      createBaseVNode(
                        "span",
                        null,
                        toDisplayString($setup.getCustomerQueueLabel(customer)),
                        1
                        /* TEXT */
                      )
                    ], 10, _hoisted_64$2)
                  ])) : $setup.isCustomerDraftBlocked(customer) ? (openBlock(), createElementBlock("div", _hoisted_65$2, [
                    createBaseVNode("span", {
                      class: "tag is-warning is-light is-small",
                      "aria-disabled": "true",
                      "data-testid": `invoicing-period-customer-draft-${customer.customer_number}`
                    }, [
                      _cache[19] || (_cache[19] = createBaseVNode(
                        "span",
                        { class: "icon is-small" },
                        [
                          createBaseVNode("i", { class: "fas fa-file-alt" })
                        ],
                        -1
                        /* CACHED */
                      )),
                      createBaseVNode(
                        "span",
                        null,
                        toDisplayString($setup.SessionUser.objects.global.language.draft ?? "Kladde"),
                        1
                        /* TEXT */
                      )
                    ], 8, _hoisted_66$2)
                  ])) : (openBlock(), createElementBlock("div", _hoisted_67$2, [
                    $setup.tmpFilters.displayRequiresAction && customer.requires_action ? (openBlock(), createElementBlock("button", {
                      key: 0,
                      type: "button",
                      class: normalizeClass(["button is-small is-dark is-inverted", { "is-loading": $setup.isCustomerPeriodActionLoading(customer) }]),
                      disabled: $setup.isCustomerPeriodActionLoading(customer),
                      onClick: withModifiers(($event) => $setup.onClickInvoiceNow(customer, $setup.getTransactionIds(customer)), ["prevent", "stop"]),
                      "data-testid": `invoicing-period-customer-invoice-${customer.customer_number}`
                    }, [
                      _cache[20] || (_cache[20] = createBaseVNode(
                        "span",
                        { class: "icon is-small" },
                        [
                          createBaseVNode("i", { class: "fas fa-file-invoice" })
                        ],
                        -1
                        /* CACHED */
                      )),
                      createBaseVNode(
                        "span",
                        null,
                        toDisplayString($setup.SessionUser.objects.global.language.invoice_now),
                        1
                        /* TEXT */
                      )
                    ], 10, _hoisted_68$2)) : createCommentVNode("v-if", true)
                  ])),
                  createBaseVNode("div", _hoisted_69$2, [
                    createVNode($setup["ActionSettingsWheelButton"], {
                      user_id: customer.id,
                      customer_number: customer.customer_number,
                      "flag-target": { target_type: "customer", target_id: customer.customer_number },
                      onFlagCreated: (flag) => $setup.onFlagCreated(customer, flag)
                    }, {
                      actions: withCtx(() => [..._cache[21] || (_cache[21] = [])]),
                      _: 1
                      /* STABLE */
                    }, 8, ["user_id", "customer_number", "flag-target", "onFlagCreated"])
                  ])
                ], 8, _hoisted_52$6),
                createVNode($setup["InvoicingPeriodFlagList"], {
                  flags: $setup.getCustomerCardFlags(customer),
                  onStatusChanged: (flag) => $setup.onFlagStatusChanged(customer, flag)
                }, null, 8, ["flags", "onStatusChanged"]),
                customer.expanded ? (openBlock(), createElementBlock("div", {
                  key: 0,
                  "data-testid": `invoicing-period-customer-expanded-${customer.customer_number}`
                }, [
                  $setup.view.variables.currentView.value === "possible_duplicates" ? (openBlock(), createBlock($setup["InvoiceOrdersPagination"], {
                    key: 0,
                    "set-customer-filter": customer.customer_number,
                    "hide-search": true,
                    "hide-filter": true,
                    "invoice-view": true,
                    "apply-default-filters": false,
                    "group-invoice-collection": true,
                    "limit-results": false,
                    "hide-pagination": true,
                    dates: {
                      dateFrom: $setup.dates.computed.formattedStartDate.value,
                      dateTo: $setup.dates.computed.formattedEndDate.value
                    },
                    "show-only-with-ids": $setup.getTransactionIds(customer),
                    "query-parameters": $setup.getTransactionQueryParameters(),
                    "excluded-order-ids": $setup.getExcludedTransactionIds(customer),
                    "invoice-period-flags": $setup.getCustomerScopedFlags(customer),
                    onFlagStatusChanged: (flag) => $setup.onFlagStatusChanged(customer, flag),
                    onFlagCreated: (flag) => $setup.onFlagCreated(customer, flag)
                  }, null, 8, ["set-customer-filter", "dates", "show-only-with-ids", "query-parameters", "excluded-order-ids", "invoice-period-flags", "onFlagStatusChanged", "onFlagCreated"])) : (openBlock(), createBlock($setup["InvoiceOrdersPagination"], {
                    key: 1,
                    "set-customer-filter": customer.customer_number,
                    "hide-search": true,
                    "hide-filter": true,
                    "invoice-view": true,
                    "apply-default-filters": false,
                    "group-invoice-collection": true,
                    "limit-results": false,
                    "hide-pagination": true,
                    "auto-expand-all": $setup.view.variables.currentView.value === "invoice_per_order",
                    "query-parameters": $setup.getTransactionQueryParameters(),
                    dates: {
                      dateFrom: $setup.dates.computed.formattedStartDate.value,
                      dateTo: $setup.dates.computed.formattedEndDate.value
                    },
                    "show-only-with-ids": $setup.getTransactionIds(customer),
                    "excluded-order-ids": $setup.getExcludedTransactionIds(customer),
                    "invoice-period-flags": $setup.getCustomerScopedFlags(customer),
                    onFlagStatusChanged: (flag) => $setup.onFlagStatusChanged(customer, flag),
                    onFlagCreated: (flag) => $setup.onFlagCreated(customer, flag)
                  }, null, 8, ["set-customer-filter", "auto-expand-all", "query-parameters", "dates", "show-only-with-ids", "excluded-order-ids", "invoice-period-flags", "onFlagStatusChanged", "onFlagCreated"]))
                ], 8, _hoisted_70$2)) : createCommentVNode("v-if", true)
              ]),
              _: 2
              /* DYNAMIC */
            }, 1032, ["data-testid"])
          ]);
        }),
        128
        /* KEYED_FRAGMENT */
      ))
    ])),
    createBaseVNode("div", _hoisted_71$2, [
      createVNode($setup["PaginationNavigation"], {
        currentPage: $setup.periodPaging.page,
        totalPages: $setup.periodPageCount,
        loadFunction: $setup.loadPeriodPage,
        setPage: $setup.setPeriodPage,
        isLoading: $setup.periodPaging.isRefreshing
      }, null, 8, ["currentPage", "totalPages", "isLoading"])
    ])
  ], 8, _hoisted_1$E);
}
const InvoicingBillingPeriodViewAll = /* @__PURE__ */ _export_sfc(_sfc_main$1i, [["render", _sfc_render$L], ["__scopeId", "data-v-9fe570ed"], ["__file", "InvoicingBillingPeriodViewAll.vue"]]);

const _sfc_main$1h = {
  __name: 'ActionSettingsWheelItemLabel',
  props: {
  icon: {
    type: String,
    default: undefined,
  },
  label: String,
  detailValue: {
    type: [String, Number],
    default: "",
  },
  appearance: {
    type: String,
    default: "default",
  },
  template: {
    type: String,
    default: 'default', // The style of the button (default, danger, success, warning, info, light)
  },
},
  setup(__props, { expose: __expose }) {
  __expose();


const props = __props;

const styles = {
  default: {
    button: 'button is-small is-dark',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-black'
    },
    label: {
      color: 'has-text-black'
    },
  },
  danger: {
    button: 'button is-small is-danger',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-danger'
    },
    label: {
      color: 'has-text-danger'
    },
  },
  success: {
    button: 'button is-small is-success',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-success'
    },
    label: {
      color: 'has-text-success'
    },
  },
  warning: {
    button: 'button is-small is-warning',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-warning'
    },
    label: {
      color: 'has-text-warning'
    },
  },
  info: {
    button: 'button is-small is-info',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-info'
    },
    label: {
      color: 'has-text-info'
    },
  },
  light: {
    button: 'button is-small is-light',
    icon: {
      icon: 'fas fa-cog',
      color: 'has-text-black'
    },
    label: {
      color: 'has-text-black'
    },
  },
};


const getIcon = () => {
  return props.icon ?? 'fas fa-cog';
};

const getLabel = () => {
  return props.label ?? 'Unavngivet handling';
};

const hasDetailValue = () => {
  return props.detailValue !== undefined && props.detailValue !== null && String(props.detailValue).length > 0;
};

const getStyle = () => {
  return styles[props.template] ?? styles.default;
};

const getButtonClass = () => {
  return getStyle().button;
};

const getIconClass = () => {
  return getStyle().icon.icon;
};

const getIconColor = () => {
  return getStyle().icon.color;
};

const getLabelColor = () => {
  return getStyle().label.color;
};

const hasIcon = () => {
  return props.icon !== undefined && props.icon !== null;
};

const isMetadataAppearance = () => props.appearance === "metadata";

const __returned__ = { props, styles, getIcon, getLabel, hasDetailValue, getStyle, getButtonClass, getIconClass, getIconColor, getLabelColor, hasIcon, isMetadataAppearance, SessionUser };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$D = {
  key: 0,
  class: "icon"
};
const _hoisted_2$v = {
  key: 1,
  class: "dropdown-item-label__detail"
};

function _sfc_render$K(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("a", {
    class: normalizeClass(["dropdown-item dropdown-item-label is-disabled", { 'dropdown-item-label--metadata': $setup.isMetadataAppearance() }])
  }, [
    ($setup.hasIcon())
      ? (openBlock(), createElementBlock("span", _hoisted_1$D, [
          createBaseVNode("i", {
            class: normalizeClass($setup.getIcon() + ' ' + $setup.getIconColor())
          }, null, 2 /* CLASS */)
        ]))
      : createCommentVNode("v-if", true),
    createBaseVNode("span", {
      class: normalizeClass(["dropdown-item-label__text ml-1", $setup.getLabelColor()])
    }, toDisplayString($setup.SessionUser.functions.ucFirst($setup.getLabel())), 3 /* TEXT, CLASS */),
    ($setup.hasDetailValue())
      ? (openBlock(), createElementBlock("span", _hoisted_2$v, toDisplayString($setup.props.detailValue), 1 /* TEXT */))
      : createCommentVNode("v-if", true)
  ], 2 /* CLASS */))
}
const ActionSettingsWheelItemLabel = /*#__PURE__*/_export_sfc(_sfc_main$1h, [['render',_sfc_render$K],['__scopeId',"data-v-5c092749"],['__file',"ActionSettingsWheelItemLabel.vue"]]);

const _sfc_main$1g = {
  __name: 'EditableTableColumn',
  props: {
  object: Object,
  loadList: Function,
  editFunction: Function,
  column: String,
  parseFunction: Function,
  virtualColumn: Boolean,
  hoverText: {
    type: String,
    default: () => {
      return null;
    }
  },
  permissionCheckFunction: {
    type: Function,
    default: () => {
      return SessionUser.canAccessSuperUser();
    }
  },
  // The component wrapper is used to wrap the table cell in a component. By default, it is null, which means it will use the <td> element.
  componentWrapper: {
    type: String,
    default: () => {
      return null; // Example: <td>
    }
  },
  // Theme can be 'divided' or 'simple'
  theme: {
    type: String,
    validator(value, props) {
      return ['divided', 'simple'].includes(value);
    },
    default: () => {
      return 'simple';
    }
  },
  // Hover HTML content
  hoverHtml: {
    type: Boolean,
    default: () => {
      return false;
    }
  },
  cellTestId: {
    type: String,
    default: () => {
      return null;
    }
  },
  editButtonTestId: {
    type: String,
    default: () => {
      return null;
    }
  }
},
  setup(__props, { expose: __expose }) {
  __expose();

const slots = useSlots();
const props = __props;

const canEdit = computed(() => Boolean(props.editFunction) && props.permissionCheckFunction());

const clickEdit = () => {
  if (!canEdit.value) {
    return;
  }

  // If the virtual column is not set, then show the edit form
  if (!props.virtualColumn) {
    isLoading.value = true;
    props.editFunction(
        props.object.id,
        props.column,
        props.object[props.column],
        props.loadList
    ).then(() => {
      isLoading.value = false;
    });
  } else {
    isLoading.value = true;
    props.editFunction(props.object.id).then(() => {
      isLoading.value = false;
    });
    // if the props.column is set, then throw an error
    if (props.column) {
      throw new Error("The column should not be set when the virtual column is set");
    }
  }
};
const isLoading = ref(false);
const hasHoverHtmlSlot = computed(() => Boolean(slots.hoverHtml));
const isTooltipMultiline = computed(() => Boolean(props.hoverHtml || hasHoverHtmlSlot.value));

//console.log(props);

const __returned__ = { slots, props, canEdit, clickEdit, isLoading, hasHoverHtmlSlot, isTooltipMultiline, computed, ref, useSlots, SessionUser, get BTooltip() { return Tooltip$1 } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$C = {
  key: 0,
  class: "level is-mobile",
  style: {"min-width":"-webkit-fill-available","width":"-webkit-fill-available","overflow":"visible","max-width":"-webkit-fill-available"}
};
const _hoisted_2$u = {
  class: "level-left",
  style: {"overflow":"hidden","max-width":"calc(100% - 2.5em)","text-overflow":"ellipsis","white-space":"nowrap"}
};
const _hoisted_3$r = ["title"];
const _hoisted_4$r = {
  key: 0,
  class: ""
};
const _hoisted_5$q = {
  key: 1,
  class: ""
};
const _hoisted_6$q = { class: "level-right" };
const _hoisted_7$p = { class: "level-item" };
const _hoisted_8$p = {
  key: 0,
  class: "ml-2 is-float-right"
};
const _hoisted_9$n = ["disabled", "data-testid"];
const _hoisted_10$m = {
  key: 0,
  class: ""
};
const _hoisted_11$i = {
  key: 1,
  class: ""
};
const _hoisted_12$h = ["innerHTML"];
const _hoisted_13$f = { key: 1 };

function _sfc_render$J(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createBlock(resolveDynamicComponent($setup.props.componentWrapper ? $setup.props.componentWrapper : 'td'), {
    onClick: $setup.clickEdit,
    class: normalizeClass(["hover-illustration", {'is-clickable': $setup.canEdit}]),
    "data-testid": $setup.props.cellTestId || null
  }, {
    default: withCtx(() => [
      createBaseVNode("div", null, [
        createCommentVNode(" Divided display ( value | edit button ) "),
        ($setup.props.theme === 'divided')
          ? (openBlock(), createElementBlock("nav", _hoisted_1$C, [
              createBaseVNode("div", _hoisted_2$u, [
                createBaseVNode("div", {
                  class: "level-item",
                  title: $setup.props.hoverText ? $setup.props.hoverText : ( !$setup.props.virtualColumn ? ($props.parseFunction ? $props.parseFunction($setup.props.object[$setup.props.column]) : $setup.props.object[$setup.props.column]) : ($props.parseFunction ? $props.parseFunction($setup.props.object) : $setup.props.object) )
                }, [
                  (!$setup.props.virtualColumn)
                    ? (openBlock(), createElementBlock("span", _hoisted_4$r, toDisplayString($props.parseFunction ? $props.parseFunction($setup.props.object[$setup.props.column]) : $setup.props.object[$setup.props.column]), 1 /* TEXT */))
                    : (openBlock(), createElementBlock("span", _hoisted_5$q, toDisplayString($props.parseFunction ? $props.parseFunction($setup.props.object) : $setup.props.object), 1 /* TEXT */))
                ], 8 /* PROPS */, _hoisted_3$r)
              ]),
              createBaseVNode("div", _hoisted_6$q, [
                createBaseVNode("div", _hoisted_7$p, [
                  ($setup.canEdit)
                    ? (openBlock(), createElementBlock("span", _hoisted_8$p, [
                        ($setup.props.editFunction)
                          ? (openBlock(), createElementBlock("button", {
                              key: 0,
                              class: normalizeClass(["button is-small is-transparent is-text", {'is-loading': $setup.isLoading}]),
                              style: {"text-decoration-line":"none"},
                              onClick: withModifiers($setup.clickEdit, ["stop"]),
                              disabled: $setup.isLoading,
                              "data-testid": $setup.props.editButtonTestId || null
                            }, [...(_cache[0] || (_cache[0] = [
                              createBaseVNode("span", { class: "icon" }, [
                                createBaseVNode("i", { class: "fas fa-edit" })
                              ], -1 /* CACHED */)
                            ]))], 10 /* CLASS, PROPS */, _hoisted_9$n))
                          : createCommentVNode("v-if", true)
                      ]))
                    : createCommentVNode("v-if", true)
                ])
              ])
            ]))
          : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
              createCommentVNode(" Simple display ( value ) with edit button on hover "),
              createCommentVNode(" Hover Edit icon "),
              createVNode($setup["BTooltip"], {
                type: "is-light",
                position: "is-bottom",
                multilined: $setup.isTooltipMultiline,
                square: ""
              }, {
                content: withCtx(() => [
                  renderSlot(_ctx.$slots, "hoverHtml", {}, () => [
                    ($setup.props.hoverText)
                      ? (openBlock(), createElementBlock("div", {
                          key: 0,
                          innerHTML: $setup.props.hoverText
                        }, null, 8 /* PROPS */, _hoisted_12$h))
                      : (openBlock(), createElementBlock("div", _hoisted_13$f, toDisplayString(!$setup.props.virtualColumn ? ($props.parseFunction ? $props.parseFunction($setup.props.object[$setup.props.column]) : $setup.props.object[$setup.props.column]) : ($props.parseFunction ? $props.parseFunction($setup.props.object) : $setup.props.object)), 1 /* TEXT */))
                  ], true)
                ]),
                default: withCtx(() => [
                  (!$setup.props.virtualColumn)
                    ? (openBlock(), createElementBlock("span", _hoisted_10$m, toDisplayString($props.parseFunction ? $props.parseFunction($setup.props.object[$setup.props.column]) : $setup.props.object[$setup.props.column]), 1 /* TEXT */))
                    : (openBlock(), createElementBlock("span", _hoisted_11$i, toDisplayString($props.parseFunction ? $props.parseFunction($setup.props.object) : $setup.props.object), 1 /* TEXT */))
                ]),
                _: 3 /* FORWARDED */
              }, 8 /* PROPS */, ["multilined"])
            ], 64 /* STABLE_FRAGMENT */))
      ])
    ]),
    _: 3 /* FORWARDED */
  }, 8 /* PROPS */, ["class", "data-testid"]))
}
const EditableTableColumn = /*#__PURE__*/_export_sfc(_sfc_main$1g, [['render',_sfc_render$J],['__scopeId',"data-v-24688ed5"],['__file',"EditableTableColumn.vue"]]);

const _sfc_main$1f = {
  __name: 'ConfigurationInput',
  props: {
  onSave: Function, // Function to call when the secret key is changed
  value: [String, Number], // The value of the secret key
  title: String, // The label of the select
  disabled: {
    type: Boolean,
    default: false,
  },
  description: String, // The description of the select
  icon: String, // The icon of the select
  color: String, // The color of the select
  forceEdit: {
    type: Boolean,
    default: null,
  },
  showEmptyWarning: {
    type: Boolean,
    default: true,
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;

const isEditting = ref(false);

const v_model = ref(props.value);

// Watch for changes in the value prop and update v_model
watch(() => props.value, (newValue) => {
  v_model.value = newValue;
});

const errorId = ref(null);

const parseErrorOnSave = (error) => {
  let unique_id = Math.random().toString(36).substring(7);
  errorId.value = unique_id;
  parseError(error, unique_id);
};



const __returned__ = { props, isEditting, v_model, errorId, parseErrorOnSave, ref, watch, parseError, getError };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$B = { class: "field" };
const _hoisted_2$t = { class: "label" };
const _hoisted_3$q = {
  key: 0,
  class: "message is-warning"
};
const _hoisted_4$q = { class: "control" };
const _hoisted_5$p = { class: "field has-addons" };
const _hoisted_6$p = { class: "control is-expanded" };
const _hoisted_7$o = ["disabled"];
const _hoisted_8$o = {
  key: 0,
  class: "control"
};
const _hoisted_9$m = {
  key: 0,
  class: "help is-danger"
};
const _hoisted_10$l = { key: 0 };
const _hoisted_11$h = { key: 1 };
const _hoisted_12$g = { class: "help" };

function _sfc_render$I(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$B, [
    createBaseVNode("label", _hoisted_2$t, toDisplayString($props.title), 1 /* TEXT */),
    createCommentVNode(" If the value is not set, show a warning message "),
    (!$setup.props.value && $props.showEmptyWarning && !$setup.isEditting)
      ? (openBlock(), createElementBlock("div", _hoisted_3$q, [...(_cache[3] || (_cache[3] = [
          createBaseVNode("div", { class: "message-body" }, [
            createBaseVNode("strong", null, "Warning:"),
            createTextVNode(" The value of this field is not set. Please set the value before continuing. ")
          ], -1 /* CACHED */)
        ]))]))
      : createCommentVNode("v-if", true),
    createBaseVNode("div", _hoisted_4$q, [
      createBaseVNode("div", _hoisted_5$p, [
        createBaseVNode("div", _hoisted_6$p, [
          withDirectives(createBaseVNode("input", {
            class: "input",
            type: "text",
            "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (($setup.v_model) = $event)),
            disabled: $props.disabled || (!$setup.isEditting && !$props.forceEdit)
          }, null, 8 /* PROPS */, _hoisted_7$o), [
            [vModelText, $setup.v_model]
          ])
        ]),
        renderSlot(_ctx.$slots, "actions"),
        (!$props.disabled)
          ? (openBlock(), createElementBlock("div", _hoisted_8$o, [
              ($setup.isEditting || $props.forceEdit)
                ? (openBlock(), createElementBlock("a", {
                    key: 0,
                    class: "button is-info",
                    onClick: _cache[1] || (_cache[1] = $event => {$props.onSave($setup.v_model).catch($setup.parseErrorOnSave); $setup.isEditting = false;})
                  }, [...(_cache[4] || (_cache[4] = [
                    createBaseVNode("span", { class: "icon" }, [
                      createBaseVNode("i", { class: "fas fa-save" })
                    ], -1 /* CACHED */)
                  ]))]))
                : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
                    createCommentVNode(" If the secret key is set, show the edit button "),
                    createBaseVNode("a", {
                      class: "button is-warning",
                      onClick: _cache[2] || (_cache[2] = $event => ($setup.isEditting = !$setup.isEditting))
                    }, [...(_cache[5] || (_cache[5] = [
                      createBaseVNode("span", { class: "icon" }, [
                        createBaseVNode("i", { class: "fas fa-edit" })
                      ], -1 /* CACHED */)
                    ]))])
                  ], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */))
            ]))
          : createCommentVNode("v-if", true)
      ]),
      createCommentVNode(" If the errorId is set, show the error message "),
      ($setup.errorId)
        ? (openBlock(), createElementBlock("div", _hoisted_9$m, [
            ($setup.getError($setup.errorId))
              ? (openBlock(), createElementBlock("span", _hoisted_10$l, "ERROR: " + toDisplayString($setup.getError($setup.errorId)), 1 /* TEXT */))
              : (openBlock(), createElementBlock("span", _hoisted_11$h, "Unknown error"))
          ]))
        : createCommentVNode("v-if", true)
    ]),
    createBaseVNode("p", _hoisted_12$g, toDisplayString($props.description), 1 /* TEXT */)
  ]))
}
const ConfigurationInput = /*#__PURE__*/_export_sfc(_sfc_main$1f, [['render',_sfc_render$I],['__file',"ConfigurationInput.vue"]]);

const _sfc_main$1e = {
  __name: 'orderItemsTable',
  props: {
  orderItems: {
    type: Array,
    default: () => [
      // Example order items for testing
      //{ id: 1, product: { name: 'Coffee', price: 20 }, notes: 'Extra hot', reference: '123', quantity: 2, price: 20 },
      //{ id: 2, product: { name: 'Sandwich', price: 50 }, notes: '', reference: '456', quantity: 1, price: 50 },
    ],
    required: true,
  },
  isLoading: {
    type: Boolean,
    default: false,
  },
  taxPercentage: {
    type: Number,
    default: 0,
  },
  paid: {
    type: Boolean,
    default: false,
  },
  showPaymentStatus: {
    type: Boolean,
    default: false,
  },
  allowEdit: {
    type: Boolean,
    default: false,
  },
  setItemValue: {
    type: Function,
    default: (orderItem, column, value) => {
      // Default function does nothing
      console.warn('setItemValue function not provided', orderItem, column, value);
    },
  },
  highlightOrderItemId: {
    type: Number,
    default: 0,
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const { t } = useI18n();

const props = __props;

const calculateTax = (price) => {
  if (!price || !props.taxPercentage) {
    return 0;
  }
  return price * (props.taxPercentage / 100);
};
const calculateTotalPrice = (price, quantity) => {
  if (!price || !quantity) {
    return 0;
  }
  const totalPrice = price * quantity;
  const tax = calculateTax(totalPrice, props.taxPercentage);
  return totalPrice + tax;
};

const getOrderItemProductName = (orderItem) => {
  return orderItem?.product?.name || t('global.no_data');
};

const getOrderItemBasePrice = (orderItem) => {
  return Number(orderItem?.product?.price ?? orderItem?.price ?? 0);
};

const __returned__ = { t, props, calculateTax, calculateTotalPrice, getOrderItemProductName, getOrderItemBasePrice, get useI18n() { return useI18n }, SessionUser, EditableTableColumn, ConfigurationInput };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$A = { class: "table is-fullwidth is-hoverable is-striped is-bordered" };
const _hoisted_2$s = { style: {"text-align":"right"} };
const _hoisted_3$p = ["id"];
const _hoisted_4$p = ["onUpdate:modelValue", "onInput"];
const _hoisted_5$o = { key: 1 };
const _hoisted_6$o = ["onUpdate:modelValue", "onInput"];
const _hoisted_7$n = { key: 1 };
const _hoisted_8$n = ["onUpdate:modelValue", "onInput"];
const _hoisted_9$l = { key: 1 };
const _hoisted_10$k = {
  key: 0,
  style: {"text-align":"right"}
};
const _hoisted_11$g = {
  style: {"text-decoration":"line-through"},
  class: "has-text-dark"
};
const _hoisted_12$f = {
  key: 1,
  style: {"text-align":"right"}
};
const _hoisted_13$e = { key: 0 };
const _hoisted_14$e = { colspan: "4" };
const _hoisted_15$e = {
  key: 0,
  style: {"text-align":"right"}
};
const _hoisted_16$e = {
  key: 1,
  style: {"text-align":"right"}
};
const _hoisted_17$c = { key: 1 };
const _hoisted_18$c = { colspan: "4" };
const _hoisted_19$a = {
  key: 0,
  style: {"text-align":"right"}
};
const _hoisted_20$9 = {
  key: 1,
  style: {"text-align":"right"}
};
const _hoisted_21$9 = { colspan: "4" };
const _hoisted_22$9 = {
  key: 0,
  style: {"text-align":"right"}
};
const _hoisted_23$9 = {
  key: 1,
  style: {"text-align":"right"}
};
const _hoisted_24$9 = { key: 2 };
const _hoisted_25$9 = { colspan: "4" };
const _hoisted_26$9 = {
  key: 0,
  style: {"text-align":"right"}
};

function _sfc_render$H(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("table", _hoisted_1$A, [
    createBaseVNode("thead", null, [
      createBaseVNode("tr", null, [
        createBaseVNode("th", null, toDisplayString(_ctx.$t('tables.products.name')), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString(_ctx.$t('global.note')), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString(_ctx.$t('common.reference')), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString(_ctx.$t('common.quantity')), 1 /* TEXT */),
        createBaseVNode("th", _hoisted_2$s, toDisplayString(_ctx.$t('common.price')), 1 /* TEXT */)
      ])
    ]),
    createBaseVNode("tbody", null, [
      ($setup.props.isLoading)
        ? (openBlock(), createElementBlock(Fragment, { key: 0 }, renderList(5, (n) => {
            return createBaseVNode("tr", { key: n }, [
              createCommentVNode(" Skeleton-lines 5 rows "),
              (openBlock(), createElementBlock(Fragment, null, renderList(5, (n) => {
                return createBaseVNode("td", { key: n }, [...(_cache[0] || (_cache[0] = [
                  createBaseVNode("div", { class: "skeleton-lines" }, [
                    createBaseVNode("div", { style: {"width":"100%"} })
                  ], -1 /* CACHED */)
                ]))])
              }), 64 /* STABLE_FRAGMENT */))
            ])
          }), 64 /* STABLE_FRAGMENT */))
        : (openBlock(true), createElementBlock(Fragment, { key: 1 }, renderList($setup.props.orderItems, (orderItem) => {
            return (openBlock(), createElementBlock("tr", {
              key: orderItem.id,
              id: `order-item-${orderItem.id}`,
              class: normalizeClass({ 'order-item-highlight': Number(orderItem.id) === Number($setup.props.highlightOrderItemId) })
            }, [
              createBaseVNode("td", null, toDisplayString($setup.getOrderItemProductName(orderItem)), 1 /* TEXT */),
              createBaseVNode("td", null, [
                ($setup.props.allowEdit)
                  ? withDirectives((openBlock(), createElementBlock("input", {
                      key: 0,
                      type: "text",
                      "onUpdate:modelValue": $event => ((orderItem.notes) = $event),
                      onInput: $event => ($setup.props.setItemValue(orderItem, 'notes', orderItem.notes)),
                      class: "input is-small"
                    }, null, 40 /* PROPS, NEED_HYDRATION */, _hoisted_4$p)), [
                      [vModelText, orderItem.notes]
                    ])
                  : (openBlock(), createElementBlock("span", _hoisted_5$o, toDisplayString(orderItem.notes), 1 /* TEXT */))
              ]),
              createBaseVNode("td", null, [
                ($setup.props.allowEdit)
                  ? withDirectives((openBlock(), createElementBlock("input", {
                      key: 0,
                      type: "text",
                      "onUpdate:modelValue": $event => ((orderItem.reference) = $event),
                      onInput: $event => ($setup.props.setItemValue(orderItem, 'reference', orderItem.reference)),
                      class: "input is-small"
                    }, null, 40 /* PROPS, NEED_HYDRATION */, _hoisted_6$o)), [
                      [vModelText, orderItem.reference]
                    ])
                  : (openBlock(), createElementBlock("span", _hoisted_7$n, toDisplayString(orderItem.reference), 1 /* TEXT */))
              ]),
              createBaseVNode("td", null, [
                ($setup.props.allowEdit)
                  ? withDirectives((openBlock(), createElementBlock("input", {
                      key: 0,
                      type: "number",
                      "onUpdate:modelValue": $event => ((orderItem.quantity) = $event),
                      onInput: $event => ($setup.props.setItemValue(orderItem, 'quantity', orderItem.quantity)),
                      class: "input is-small",
                      min: "1"
                    }, null, 40 /* PROPS, NEED_HYDRATION */, _hoisted_8$n)), [
                      [
                        vModelText,
                        orderItem.quantity,
                        void 0,
                        { number: true }
                      ]
                    ])
                  : (openBlock(), createElementBlock("span", _hoisted_9$l, toDisplayString(orderItem.quantity), 1 /* TEXT */))
              ]),
              (orderItem.price !== $setup.getOrderItemBasePrice(orderItem))
                ? (openBlock(), createElementBlock("td", _hoisted_10$k, [
                    createBaseVNode("span", _hoisted_11$g, toDisplayString($setup.getOrderItemBasePrice(orderItem) * orderItem.quantity), 1 /* TEXT */),
                    _cache[1] || (_cache[1] = createTextVNode()),
                    createBaseVNode("span", null, toDisplayString($setup.SessionUser.functions.currency.toLocal(orderItem.price * orderItem.quantity)), 1 /* TEXT */)
                  ]))
                : (openBlock(), createElementBlock("td", _hoisted_12$f, toDisplayString($setup.SessionUser.functions.currency.toLocal(orderItem.price * orderItem.quantity)), 1 /* TEXT */))
            ], 10 /* CLASS, PROPS */, _hoisted_3$p))
          }), 128 /* KEYED_FRAGMENT */))
    ]),
    createBaseVNode("tfoot", null, [
      createCommentVNode(" Tax "),
      ($setup.props.taxPercentage > 0)
        ? (openBlock(), createElementBlock("tr", _hoisted_13$e, [
            createBaseVNode("td", _hoisted_14$e, toDisplayString(_ctx.$t('common.tax')) + " (" + toDisplayString($setup.props.taxPercentage) + "%)", 1 /* TEXT */),
            ($setup.props.isLoading)
              ? (openBlock(), createElementBlock("td", _hoisted_15$e, [
                  createCommentVNode(" Skeleton-lines 1 row "),
                  _cache[2] || (_cache[2] = createBaseVNode("div", { class: "skeleton-lines" }, [
                    createBaseVNode("div", { style: {"width":"100%"} })
                  ], -1 /* CACHED */))
                ]))
              : (openBlock(), createElementBlock("td", _hoisted_16$e, toDisplayString($setup.SessionUser.functions.currency.toLocal($setup.calculateTax($setup.props.orderItems.reduce((acc, orderItem) => acc + orderItem.price * orderItem.quantity, 0)))), 1 /* TEXT */))
          ]))
        : createCommentVNode("v-if", true),
      ($setup.props.taxPercentage > 0)
        ? (openBlock(), createElementBlock("tr", _hoisted_17$c, [
            createBaseVNode("td", _hoisted_18$c, toDisplayString(_ctx.$t('tables.orders.total')) + " " + toDisplayString(_ctx.$t('global.excl_tax')), 1 /* TEXT */),
            ($setup.props.isLoading)
              ? (openBlock(), createElementBlock("td", _hoisted_19$a, [
                  createCommentVNode(" Skeleton-lines 1 row "),
                  _cache[3] || (_cache[3] = createBaseVNode("div", { class: "skeleton-lines" }, [
                    createBaseVNode("div", { style: {"width":"100%"} })
                  ], -1 /* CACHED */))
                ]))
              : (openBlock(), createElementBlock("td", _hoisted_20$9, toDisplayString($setup.SessionUser.functions.currency.toLocal($setup.props.orderItems.reduce((acc, orderItem) => acc + orderItem.price * orderItem.quantity, 0))), 1 /* TEXT */))
          ]))
        : createCommentVNode("v-if", true),
      createBaseVNode("tr", null, [
        createBaseVNode("td", _hoisted_21$9, toDisplayString(_ctx.$t('tables.orders.total')) + " " + toDisplayString($setup.props.taxPercentage > 0 ? _ctx.$t('global.incl_tax') : ''), 1 /* TEXT */),
        ($setup.props.isLoading)
          ? (openBlock(), createElementBlock("td", _hoisted_22$9, [
              createCommentVNode(" Skeleton-lines 1 row "),
              _cache[4] || (_cache[4] = createBaseVNode("div", { class: "skeleton-lines" }, [
                createBaseVNode("div", { style: {"width":"100%"} })
              ], -1 /* CACHED */))
            ]))
          : (openBlock(), createElementBlock("td", _hoisted_23$9, toDisplayString($setup.SessionUser.functions.currency.toLocal($setup.props.orderItems.reduce((acc, orderItem) => acc + orderItem.price * orderItem.quantity, 0) + $setup.calculateTax($setup.props.orderItems.reduce((acc, orderItem) => acc + orderItem.price * orderItem.quantity, 0)))), 1 /* TEXT */))
      ]),
      ($setup.props.showPaymentStatus)
        ? (openBlock(), createElementBlock("tr", _hoisted_24$9, [
            createBaseVNode("td", _hoisted_25$9, toDisplayString(_ctx.$t('global.payment_status')), 1 /* TEXT */),
            ($setup.props.isLoading)
              ? (openBlock(), createElementBlock("td", _hoisted_26$9, [
                  createCommentVNode(" Skeleton-lines 1 row "),
                  _cache[5] || (_cache[5] = createBaseVNode("div", { class: "skeleton-lines" }, [
                    createBaseVNode("div", { style: {"width":"100%"} })
                  ], -1 /* CACHED */))
                ]))
              : (openBlock(), createElementBlock("td", {
                  key: 1,
                  style: {"text-align":"right"},
                  class: normalizeClass($setup.props.paid ? 'has-text-success' : 'has-text-danger')
                }, toDisplayString($setup.props.paid ? _ctx.$t('tables.invoices.paid') : _ctx.$t('tables.invoices.unpaid')), 3 /* TEXT, CLASS */))
          ]))
        : createCommentVNode("v-if", true)
    ])
  ]))
}
const OrderItemsTable = /*#__PURE__*/_export_sfc(_sfc_main$1e, [['render',_sfc_render$H],['__scopeId',"data-v-bbca93fc"],['__file',"orderItemsTable.vue"]]);

const hasLinkedOrder = (object) => Number(object?.linked_order_id) > 0;

const isUsageOrderAttachedToOrder = (object) => {
  if (hasLinkedOrder(object)) {
    return true;
  }

  const automation = object?.automation;
  const automationStatus = automation?.status;
  if (
    ["auto_accepted", "accepted"].includes(automationStatus) &&
    ["attach_order", "create_order"].includes(automation?.action)
  ) {
    return true;
  }

  const duplicates = Array.isArray(object?.duplicates) ? object.duplicates : [];
  return duplicates.some((duplicate) => duplicate?.wash_id === object?.wash_id);
};

const filterUsageOrdersByAttachment = (objects, showOnlyUnattachedVehicle) => {
  const sourceObjects = Array.isArray(objects) ? objects : [];

  if (!showOnlyUnattachedVehicle) {
    return sourceObjects;
  }

  return sourceObjects.filter((object) => !isUsageOrderAttachedToOrder(object));
};

const XLVASK_USAGE_AMOUNT_CACHE_TTL_MS = 10 * 60 * 1000;

const CACHE_PREFIX = "xlvask-usage-amount:";
const memoryCache = new Map();

const getStorageValue = (key) => {
  try {
    if (typeof window === "undefined" || !window.localStorage) {
      return "";
    }
    return window.localStorage.getItem(key) || "";
  } catch {
    return "";
  }
};

const hashCacheScopePart = (value) => {
  let hash = 5381;
  for (let index = 0; index < value.length; index += 1) {
    hash = ((hash << 5) + hash) ^ value.charCodeAt(index);
  }
  return (hash >>> 0).toString(36);
};

const getAuthenticatedCacheScope = () => {
  const token = getStorageValue("token");
  if (!token) {
    return "";
  }

  return [
    hashCacheScopePart(token),
    getStorageValue("is_subuser") === "true" ? "subuser" : "user",
    getStorageValue("selected_customer_number"),
  ]
    .map((part) => encodeURIComponent(String(part ?? "")))
    .join("|");
};

const getScopedCacheKey = (cacheKey) => {
  const scope = getAuthenticatedCacheScope();
  return scope ? `${scope}:${cacheKey}` : "";
};

const safeSessionStorage = () => {
  try {
    if (typeof window === "undefined" || !window.sessionStorage) {
      return null;
    }
    return window.sessionStorage;
  } catch {
    return null;
  }
};

const normalizeUsageLogId = (objectOrId) => {
  const value = typeof objectOrId === "object" ? objectOrId?.usage_log_id ?? objectOrId?.id : objectOrId;
  const parsed = Number.parseInt(String(value ?? ""), 10);
  return Number.isInteger(parsed) && parsed > 0 ? parsed : 0;
};

const isFreshEntry = (entry) => {
  const storedAt = Number(entry?.storedAt ?? 0);
  return storedAt > 0 && Date.now() - storedAt <= XLVASK_USAGE_AMOUNT_CACHE_TTL_MS;
};

const buildXlvaskUsageAmountCacheKey = (objectOrId) => {
  const usageLogId = normalizeUsageLogId(objectOrId);
  return usageLogId > 0 ? String(usageLogId) : "";
};

const getCachedXlvaskUsageAmount = (objectOrId) => {
  const cacheKey = buildXlvaskUsageAmountCacheKey(objectOrId);
  const scopedCacheKey = cacheKey ? getScopedCacheKey(cacheKey) : "";
  if (!scopedCacheKey) {
    return null;
  }

  const memoryEntry = memoryCache.get(scopedCacheKey);
  if (isFreshEntry(memoryEntry)) {
    return memoryEntry.data;
  }

  if (memoryEntry) {
    memoryCache.delete(scopedCacheKey);
  }

  const storage = safeSessionStorage();
  if (!storage) {
    return null;
  }

  const storageKey = `${CACHE_PREFIX}${scopedCacheKey}`;
  try {
    const parsed = JSON.parse(storage.getItem(storageKey) || "null");
    if (!isFreshEntry(parsed)) {
      storage.removeItem(storageKey);
      return null;
    }
    memoryCache.set(scopedCacheKey, parsed);
    return parsed.data;
  } catch {
    storage.removeItem(storageKey);
    return null;
  }
};

const setCachedXlvaskUsageAmount = (objectOrId, data) => {
  const cacheKey = buildXlvaskUsageAmountCacheKey(objectOrId);
  const scopedCacheKey = cacheKey ? getScopedCacheKey(cacheKey) : "";
  if (!scopedCacheKey) {
    return;
  }

  const entry = {
    storedAt: Date.now(),
    data,
  };
  memoryCache.set(scopedCacheKey, entry);

  const storage = safeSessionStorage();
  if (!storage) {
    return;
  }

  try {
    storage.setItem(`${CACHE_PREFIX}${scopedCacheKey}`, JSON.stringify(entry));
  } catch {
    // Best-effort cache. Quota errors should not block XL Vask usage rows.
  }
};

const clearCachedXlvaskUsageAmount = (objectOrId = null) => {
  const storage = safeSessionStorage();
  const cacheKey = objectOrId === null ? "" : buildXlvaskUsageAmountCacheKey(objectOrId);
  const scopedCacheKey = cacheKey ? getScopedCacheKey(cacheKey) : "";

  if (scopedCacheKey) {
    memoryCache.delete(scopedCacheKey);
    try {
      storage?.removeItem(`${CACHE_PREFIX}${scopedCacheKey}`);
    } catch {
      // Best-effort cache cleanup.
    }
    return;
  }

  memoryCache.clear();
  if (!storage) {
    return;
  }

  try {
    Object.keys(storage)
      .filter((key) => key.startsWith(CACHE_PREFIX))
      .forEach((key) => storage.removeItem(key));
  } catch {
    // Best-effort cache cleanup.
  }
};

const _sfc_main$1d = {
  __name: 'xlvaskUsageOrdersTable',
  props: {
  objects: {
    type: Object,
    required: true,
  },
  showOnlyUnattachedVehicle: {
    type: Boolean,
    default: false,
  },
  allowSelectMultiple: {
    type: Boolean,
    default: false,
  },
  highlightUsageLogId: {
    type: Number,
    default: 0,
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;
const { orderBy, orderDirection, setOrder, loadList } = usePaginatedListInstance();

const redirectDepartmentOrderPage = (orderId, departmentId) => {
  // Send the user to the order page (In a new tab)
  // `/admin/${departmentId}/modules/pos/orders/${orderId}`
  window.open(`/admin/${departmentId}/modules/pos/orders/${orderId}`, '_blank');
};

const redirectSuperUserInvoiceCollectionPage = (invoiceCollectionId) => {
  // Send the user to the invoice collection page (In a new tab)
  window.open(`/superuser/invoices/${invoiceCollectionId}`, '_blank');
};

// Get the departments (If the departments are not already loaded)
if (departments.value.length === 0) {
  getDepartments();
}

const clickUser = (customer_id) => {
  if (!SessionUser.canAccessSuperUser()) {
    return;
  }
  // Send the user to the user page
  SessionUser.adminUser.customers.fromCustomerNumber.getUserId(customer_id).then(response => window.open('/superuser/users/' + response.data.data.user_id, '_blank'));
};

const isColumnCurrentlyBeingSortedBy = (column) => {
  // Check if the column is currently being sorted by
  return orderBy.value === column;
};

const isCurrentSortDirectionAscending = () => {
  // Check if the current sort direction is ascending
  return orderDirection.value === 'asc';
};

const isCurrentSortDirectionDescending = () => {
  // Check if the current sort direction is descending
  return orderDirection.value === 'desc';
};

const onTableHeaderClick = (column) => {
  // Check if the column is already sorted
  if (orderBy.value === column) {
    // If the column is already sorted, toggle the direction
    const direction = orderDirection.value === 'asc' ? 'desc' : 'asc';
    setOrder(
        column,
        direction
    );
  } else {
    // If the column is not sorted, set the order to the new column and default to ascending
    const direction = 'asc';
    setOrder(
        column,
        direction
    );
  }
  // Load the list
  loadList();
};

const tableHeaders = ref([
  {
    name: 'id',
    title: 'Id',
    sortable: true,
  },
  {
    name: 'department_id',
    title: 'Afdeling',
    sortable: true,
  },
  {
    name: 'lane',
    title: SessionUser.objects.global.language.lane,
    sortable: true,
  },
  {
    name: 'customer_number',
    title: SessionUser.objects.global.language.customer,
    sortable: true,
  },
  {
    name: 'order_id',
    title: SessionUser.functions.ucFirst(SessionUser.objects.orders.meta.labels.single),
    sortable: true,
  },
  {
    name: 'created_at',
    title: 'Dato',
    sortable: true,
  },
  {
    name: 'actions',
    title: '',
    sortable: false,
  }
]);

const onClickMarkAsNotDuplicate = (object) => {
  // Mark the order as not a duplicate
  SessionUser.request(
      '/orders/sync/potential-matches/ignore-duplicate',
      'POST',
      {
        id: object.id,
      }
  ).then(() => {
    Swal.fire({
      title: 'Success',
      text: 'Transaktionen er nu markeret som ikke en duplikat.',
      icon: 'success',
      confirmButtonText: 'OK',
    });
    // Reload the list
    loadList();
  }).catch((error) => {
    Swal.fire({
      title: 'Fejl',
      text: 'Der opstod en fejl under markering af transaktionen som ikke en duplikat.',
    });
    console.error(error);
  });
};

const onClickAttachToOrder = (object) => {
  // Redirect the user to the order page
  SessionUser.objects.orders.set.wash_id(object.order_id, object.wash_id)
      .then(() => {
        Swal.fire({
          title: 'Success',
          text: 'Vasken er nu tilknyttet til transaktionen.',
          icon: 'success',
          confirmButtonText: 'OK',
        });
        // Since the order is now attached, we no longer consider it a (possible) duplicate.
        onClickMarkAsNotDuplicate(object);
      })
      .catch((error) => {
        Swal.fire({
          title: 'Fejl',
          text: 'Der opstod en fejl under tilknytning af vasken til transaktionen.',
        });
        console.error(error);
      });
};

const humanReadableTimeAgo = (dateString) => {
  // Convert the date string to a Date object
  const date = new Date(dateString);
  // Get the current date
  const now = new Date();
  // Calculate the difference in seconds
  const seconds = Math.floor((now - date) / 1000);

  // Define time intervals
  const intervals = [
    { label: 'år', multiple: '', seconds: 31536000 },
    { label: 'måned', multiple: 'er', seconds: 2592000 },
    { label: 'uge', multiple: 'r', seconds: 604800 },
    { label: 'dag', multiple: 'e', seconds: 86400 },
    { label: 'time', multiple: 'r', seconds: 3600 },
    { label: 'minut', multiple: 'ter', seconds: 60 },
    { label: 'sekund', multiple: 'er', seconds: 1 }
  ];

  for (const interval of intervals) {
    const count = Math.floor(seconds / interval.seconds);
    if (count >= 1) {
      return `${count} ${interval.label}${count > 1 ? interval.multiple : ''} siden`;
    }
  }

  return 'lige nu';
};

const applyGeneratedContent = (object, data) => {
  const orderItems = Array.isArray(data?.order_items) ? data.order_items : [];
  const potentialDuplicates = Array.isArray(data?.potential_duplicates) ? data.potential_duplicates : [];

  object.items = orderItems;
  if (potentialDuplicates.length > 0) {
    object.selectedDuplicateId = parseInt(potentialDuplicates[0].id);
    object.duplicates = potentialDuplicates;
  }
  if (data?.automation !== undefined) {
    object.automation = data.automation;
  }
  object.fast_link_key = undefined;
  object.loading = false;
};

const applyCachedGeneratedContent = (object) => {
  const cached = getCachedXlvaskUsageAmount(object);
  if (!cached) {
    return false;
  }

  applyGeneratedContent(object, cached);
  return true;
};

const generateContent = (object) => {
  if (applyCachedGeneratedContent(object)) {
    return Promise.resolve();
  }

  if (!object.fast_link_key || object.loading) {
    return Promise.resolve(); // If no fast link key, do not generate content
  }
  object.loading = true; // Set loading state to true
  // Generate content based on the object
  return SessionUser.request(
      '/modules/xlvask/services/usage/orders/fast-link?fast_link_key=' + object.fast_link_key,
      'GET'
  ).then((response) => {
    const data = response.data.data;
        applyGeneratedContent(object, data);
        setCachedXlvaskUsageAmount(object, {
          order_items: object.items,
          potential_duplicates: object.duplicates,
          automation: object.automation,
        });
      }
  ).catch((error) => {
    console.error('Error generating content:', error);
    object.loading = false;
  });
};

const setSelectedDuplicate = (newDuplicateId, object) => {
  // Set the selected duplicate ID
  object.selectedDuplicateId = parseInt(newDuplicateId);
};

const isComparingOrders = (object) => {
  // Check if the order is currently being compared
  return object?.isComparing ?? false;
};
const onClickCompareToggle = (object) => {
  // Toggle the comparing state
  isComparingOrders(object) ? object.isComparing = false : object.isComparing = true;
};
const getPriceFromOrderItems = (orderItems) => {
  // Calculate the total price from order items
  if (!orderItems || !Array.isArray(orderItems)) {
    return 0;
  }
  return orderItems.reduce((total, item) => {
    return total + (item.price * item.quantity);
  }, 0);
};

const getObjectPrice = (object) => {
  if (doesObjectHaveItems(object)) {
    return getPriceFromOrderItems(object.items);
  }

  const parsedAmount = Number(object?.total_net_amount ?? 0);
  return Number.isFinite(parsedAmount) ? parsedAmount : 0;
};

const doesObjectHaveAmount = (object) => getObjectPrice(object) > 0;

const doesObjectPriceMatchPotentialDuplicate = (object, potentialDuplicate) => {
  // Check if the price of the object matches the potential duplicate
  return getObjectPrice(object) === Number(potentialDuplicate?.total_net_amount ?? 0);
};

const getPrimaryItemFromOrderItems = (orderItems) => {
  // Get the primary item from order items
  if (!orderItems || !Array.isArray(orderItems)) {
    return null;
  }
  return orderItems[0]; // Assuming the first item is the primary item
};

const getProductFromOrderItem = (orderItem) => {
  // Get the product from the order item
  if (!orderItem || !orderItem.product) {
    return null;
  }
  return orderItem.product; // Assuming product is a property of orderItem
};

const getProductName = (orderItem) => {
  // Get the product name from the order item
  const product = getProductFromOrderItem(orderItem);
  return product ? product.name : 'Ukendt produkt';
};

const getObjectPrimaryProductName = (object) => {
  if (doesObjectHaveItems(object)) {
    return getProductName(getPrimaryItemFromOrderItems(object.items));
  }

  return object?.xlvask_primary_product_name || object?.primary_product_name || '';
};

const doesObjectHaveItems = (object) => {
  // Check if the object has items
  return object.items && Array.isArray(object.items) && object.items.length > 0;
};

const automaticallyLoadContent = (object) => {
  // Automatically load content for the object if it has a fast link key and is not already loading
  if (object.fast_link_key && !object.loading) {
    generateContent(object);
  }
};

const isHighlightedUsageLog = (object) => Number(object?.id || 0) === Number(props.highlightUsageLogId || 0);

// Reuse cached detail payloads immediately, but only fetch one-time fast-link details on demand.
watch(() => props.objects, (newObjects) => {
  newObjects.forEach(object => {
    applyCachedGeneratedContent(object);
  });
}, { immediate: true, deep: true });

const getCurrentComparingOrder = (object) => {
  // Get the current comparing order
  return object.duplicates.find(duplicate => duplicate.id === object.selectedDuplicateId) || null;
};
const isObjectEditing = (object) => {
  // Check if the object is currently being edited
  return object.isEditing ?? false;
};

const toggleObjectEditing = (object) => {
  // Toggle the editing state of the object
  object.isEditing = !object.isEditing;
};

const actions = {
  click: {
    comparison: {
      // Update the potential duplicate order with the the wash_id
      isEqual: (object) => {
        return SessionUser.objects.orders.set.wash_id(parseInt(getCurrentComparingOrder(object).id), object.wash_id)
          .then(() => {
            // Since no major changes are made, we can just modify the current object locally
            object.wash_id = getCurrentComparingOrder(object).wash_id;
            // Toggle the comparing state
            object.isComparing = false;
          })
          .catch((error) => {
            Swal.fire({
              title: 'Fejl',
              text: 'Der opstod en fejl under markering af ordrerne som ens.',
            });
            console.error(error);
          });
      },
      // Mark the potential duplicate order as not equal (Regret, no changes made)
      isNotEqual: (object) => {
        object.isComparing = false; // Just toggle the comparing state
      }
    },
    approval: {
      accept: (object) => {
        // Accept the order
        SessionUser.objects.global.add.object(
            SessionUser.objects.orders.meta.endpoint, // Endpoint for orders
            {
              customer_id: parseInt(object.customer_id), // Ensure customer_id is an integer
              department_id: parseInt(object.department_id), // Ensure department_id is an integer
              lane: parseInt(object.lane), // Ensure lane is an integer
              reg_1: object.reg_1,
              reg_2: object.reg_2 ?? '', // Ensure reg_2 is a string
              reg_3: object.reg_3 ?? '', // Ensure reg_3 is a string
              reference: object.reference ?? '', // Ensure reference is a string
              notes: object.notes ?? '', // Ensure notes is a string
              created_at: object.created_at,
              wash_id: object.wash_id, // This is the wash ID we want to set
            }, {authenticated: true}
        ).then(async (response) => {
          const data = response.data.data;
          console.log('Order created successfully:', data);
          // Create the order items
          const orderItems = object.items.map(item => ({
            order_id: parseInt(data.id), // Use the newly created order ID
            product_id: item.product_id,
            quantity: item.quantity,
            price: item.price,
            notes: item.notes,
            related_item_id: null, // This is changed once the first item has been created.
          }));
          let relatedItemId = null; // This will be updated after the first item is created.
          const createdOrderItems = []; // To store created order items
          for (const item of orderItems) {
            console.log('Order Item:', item);
            item.related_item_id = parseInt(relatedItemId); // Set the related item ID
            await SessionUser.objects.global.add.object(
                '/order/items',
                item, // The order item to create
                {authenticated: true}
            ).then((response) => {
              relatedItemId = response.data.data.id; // Update the related item ID for the next item
              createdOrderItems.push(response.data.data); // Add the created order item to the list
              // Add the created order item to the last order's order_items
              console.log('Order Item created successfully:', response.data.data);
            }).catch((error) => {
              console.error('Error creating order item:', error);
            });
          }
          // Add the order items to the order
          data.order_items = createdOrderItems;
          // Add the new order to the object
          object.duplicates.push(data);
          // Set the autoOpen state to true
          object.isOpen = true;
        });
      },
      edit: (object) => {
        // Edit the order
        console.log('Editing order:', object);
        toggleObjectEditing(object);
      },
      reject: (object) => {
        // Reject the order
        console.log('Rejecting order:', object);
      },
      history: (object) => {
        // Show the history of the order
        console.log('Showing history for order:', object);
      }
    }
  },
};

const isObjectAttachedToOrder = (object) => {
  // Check if any of the duplicates have a wash_id matching the current object's wash_id
  return isUsageOrderAttachedToOrder(object);
};

const doesObjectHaveExactMatch = (object) => {
  // Check if the object has any duplicates with the same order price
  return object.duplicates?.some(duplicate => {
    return getObjectPrice(object) === Number(duplicate.total_net_amount ?? 0);
  }) || false;
};

const doesObjectHaveDuplicates = (object) => {
  // Check if the object has any duplicates
  return object.duplicates && Array.isArray(object.duplicates) && object.duplicates.length > 0;
};

const hasAutomationState = (object) => {
  const status = object?.automation?.status;
  return !!status && status !== 'none' && status !== 'failed';
};

const isAutomationActionable = (object) => {
  return object?.automation?.can_accept || object?.automation?.can_deny;
};

const getAutomationOrderId = (object) => {
  return object?.automation?.matched_order_id
      ?? object?.automation?.created_order_id
      ?? object?.automation?.candidate_order?.id
      ?? null;
};

const getAutomationLabel = (object) => {
  const automation = object?.automation ?? {};
  const orderId = getAutomationOrderId(object);
  const orderSuffix = orderId ? ` #${orderId}` : '';

  if (automation.status === 'suggested') {
    return automation.action === 'create_order'
        ? 'Foreslået: Opret ordre'
        : `Foreslået: Tilknyt ordre${orderSuffix}`;
  }

  if (automation.status === 'auto_accepted') {
    return automation.action === 'create_order'
        ? `Oprettet automatisk${orderSuffix}`
        : `Tilknyttet automatisk${orderSuffix}`;
  }

  if (automation.status === 'accepted') {
    return automation.action === 'create_order'
        ? `Oprettet${orderSuffix}`
        : `Accepteret${orderSuffix}`;
  }

  if (automation.status === 'denied') {
    return 'Afvist';
  }

  return '';
};

const getAutomationReason = (object) => {
  return object?.automation?.reason || object?.automation?.error || '';
};

const getAutomationConfidence = (object) => {
  const confidence = Number(object?.automation?.confidence ?? 0);
  if (!Number.isFinite(confidence) || confidence <= 0) {
    return '';
  }

  return `${Math.round(confidence * 100)}% sikkerhed`;
};

const getAutomationTagClass = (object) => {
  const status = object?.automation?.status;
  if (status === 'auto_accepted' || status === 'accepted') {
    return 'is-success';
  }
  if (status === 'denied') {
    return 'is-light';
  }
  if (status === 'failed') {
    return 'is-danger';
  }
  return object?.automation?.source === 'openai' ? 'is-info' : 'is-warning';
};

const getAutomationMessageClass = (object) => {
  const status = object?.automation?.status;
  if (status === 'auto_accepted' || status === 'accepted') {
    return 'is-success';
  }
  if (status === 'denied') {
    return 'is-light';
  }
  if (status === 'failed') {
    return 'is-danger';
  }
  return object?.automation?.source === 'openai' ? 'is-info' : 'is-warning';
};

const getAutomationIconClass = (object) => {
  const automation = object?.automation ?? {};
  if (automation.status === 'denied') {
    return 'fa-ban';
  }
  if (automation.status === 'failed') {
    return 'fa-exclamation-triangle';
  }
  if (automation.action === 'create_order') {
    return 'fa-plus-circle';
  }
  return 'fa-link';
};

const setAutomationDecision = (object, decision) => {
  if (!object?.id || object.automationLoading) {
    return;
  }

  object.automationLoading = true;
  SessionUser.request(
      `/modules/xlvask/services/usage/orders/${object.id}/automation/${decision}`,
      'POST',
      {
        suggestion_id: object.automation?.id ?? null,
      }
  ).then((response) => {
    object.automation = response.data.data;
    clearCachedXlvaskUsageAmount(object);
    window.dispatchEvent(new CustomEvent('xlvask-usage-order-updated', {
      detail: {
        usageLogId: object.id,
        decision,
      },
    }));
  }).catch((error) => {
    Swal.fire({
      title: 'Fejl',
      text: decision === 'accept'
          ? 'Forslaget kunne ikke accepteres.'
          : 'Forslaget kunne ikke afvises.',
      icon: 'error',
      confirmButtonText: 'OK',
    });
    console.error(error);
  }).finally(() => {
    object.automationLoading = false;
  });
};

const acceptAutomation = (object) => {
  setAutomationDecision(object, 'accept');
};

const denyAutomation = (object) => {
  setAutomationDecision(object, 'deny');
};

const filteredObjects = computed(() => {
  return filterUsageOrdersByAttachment(props.objects, props.showOnlyUnattachedVehicle);
});


const __returned__ = { props, orderBy, orderDirection, setOrder, loadList, redirectDepartmentOrderPage, redirectSuperUserInvoiceCollectionPage, clickUser, isColumnCurrentlyBeingSortedBy, isCurrentSortDirectionAscending, isCurrentSortDirectionDescending, onTableHeaderClick, tableHeaders, onClickMarkAsNotDuplicate, onClickAttachToOrder, humanReadableTimeAgo, applyGeneratedContent, applyCachedGeneratedContent, generateContent, setSelectedDuplicate, isComparingOrders, onClickCompareToggle, getPriceFromOrderItems, getObjectPrice, doesObjectHaveAmount, doesObjectPriceMatchPotentialDuplicate, getPrimaryItemFromOrderItems, getProductFromOrderItem, getProductName, getObjectPrimaryProductName, doesObjectHaveItems, automaticallyLoadContent, isHighlightedUsageLog, getCurrentComparingOrder, isObjectEditing, toggleObjectEditing, actions, isObjectAttachedToOrder, doesObjectHaveExactMatch, doesObjectHaveDuplicates, hasAutomationState, isAutomationActionable, getAutomationOrderId, getAutomationLabel, getAutomationReason, getAutomationConfidence, getAutomationTagClass, getAutomationMessageClass, getAutomationIconClass, setAutomationDecision, acceptAutomation, denyAutomation, filteredObjects, ActionSettingsWheelButton, computed, ref, watch, departments, getDepartments, getDepartmentName, SessionUser, usePaginatedListInstance, ActionSettingsWheelItem, get Swal() { return Swal }, ActionSettingsWheelItemLabel, WhiteBoxCard, OrderItemsTable, get filterUsageOrdersByAttachment() { return filterUsageOrdersByAttachment }, get isUsageOrderAttachedToOrder() { return isUsageOrderAttachedToOrder }, get clearCachedXlvaskUsageAmount() { return clearCachedXlvaskUsageAmount }, get getCachedXlvaskUsageAmount() { return getCachedXlvaskUsageAmount }, get setCachedXlvaskUsageAmount() { return setCachedXlvaskUsageAmount } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$z = { class: "table is-fullwidth is-hoverable" };
const _hoisted_2$r = ["onClick"];
const _hoisted_3$o = { class: "is-flex-wrap-nowrap pleno-table-header-content" };
const _hoisted_4$o = { class: "has-text-weight-bold" };
const _hoisted_5$n = { class: "is-flex-wrap-nowrap pleno-table-header-content" };
const _hoisted_6$n = { class: "has-text-weight-bold" };
const _hoisted_7$m = { class: "has-text-centered" };
const _hoisted_8$m = { class: "is-align-content-end" };
const _hoisted_9$k = { colspan: "100%" };
const _hoisted_10$j = { class: "card-header-title xlvask-usage-card-header" };
const _hoisted_11$f = { class: "xlvask-usage-card-main" };
const _hoisted_12$e = { class: "xlvask-usage-card-primary" };
const _hoisted_13$d = { class: "has-text-weight-bold xlvask-usage-registration" };
const _hoisted_14$d = { class: "tag is-light is-size-7 xlvask-usage-chip" };
const _hoisted_15$d = {
  key: 0,
  class: "tag is-light is-size-7 xlvask-usage-chip"
};
const _hoisted_16$d = {
  key: 1,
  class: "tag is-light is-size-7 xlvask-usage-chip xlvask-usage-price"
};
const _hoisted_17$b = { class: "xlvask-usage-card-status" };
const _hoisted_18$b = { class: "icon is-small" };
const _hoisted_19$9 = { class: "has-text-weight-bold xlvask-usage-chip-text" };
const _hoisted_20$8 = ["data-testid"];
const _hoisted_21$8 = { class: "icon is-small" };
const _hoisted_22$8 = { class: "has-text-weight-bold xlvask-usage-chip-text" };
const _hoisted_23$8 = { class: "icon is-small" };
const _hoisted_24$8 = { class: "has-text-weight-bold xlvask-usage-chip-text" };
const _hoisted_25$8 = { class: "tags has-addons xlvask-usage-location-tags" };
const _hoisted_26$8 = { class: "tag xlvask-usage-chip" };
const _hoisted_27$8 = { class: "tag is-info is-light xlvask-usage-chip" };
const _hoisted_28$8 = ["title"];
const _hoisted_29$7 = { class: "columns xlvask-usage-content-columns" };
const _hoisted_30$7 = { class: "column is-10 xlvask-usage-main-column" };
const _hoisted_31$7 = { class: "content" };
const _hoisted_32$7 = { class: "message-body" };
const _hoisted_33$7 = { class: "is-flex is-align-items-center is-justify-content-space-between is-flex-wrap-wrap" };
const _hoisted_34$7 = { class: "has-text-weight-bold mb-1" };
const _hoisted_35$7 = { class: "icon is-small" };
const _hoisted_36$6 = {
  key: 0,
  class: "mb-1"
};
const _hoisted_37$6 = {
  key: 1,
  class: "is-size-7 has-text-grey"
};
const _hoisted_38$6 = {
  key: 0,
  class: "buttons mb-0"
};
const _hoisted_39$6 = ["disabled", "data-testid", "onClick"];
const _hoisted_40$6 = ["disabled", "data-testid", "onClick"];
const _hoisted_41$6 = { class: "message-body" };
const _hoisted_42$6 = {
  key: 1,
  class: "has-text-weight-bold"
};
const _hoisted_43$6 = ["onClick"];
const _hoisted_44$6 = { key: 0 };
const _hoisted_45$6 = ["onClick"];
const _hoisted_46$6 = {
  key: 1,
  class: "columns xlvask-order-comparison-columns"
};
const _hoisted_47$6 = { class: "field" };
const _hoisted_48$6 = ["value"];
const _hoisted_49$5 = {
  key: 0,
  class: "field"
};
const _hoisted_50$5 = {
  class: "textarea",
  readonly: ""
};
const _hoisted_51$5 = {
  key: 1,
  class: "field"
};
const _hoisted_52$5 = ["value"];
const _hoisted_53$4 = {
  key: 0,
  class: "column is-6"
};
const _hoisted_54$4 = { class: "field" };
const _hoisted_55$4 = ["onUpdate:modelValue", "onChange"];
const _hoisted_56$4 = ["value"];
const _hoisted_57$4 = {
  key: 0,
  class: "field"
};
const _hoisted_58$4 = {
  class: "textarea",
  readonly: ""
};
const _hoisted_59$3 = {
  key: 1,
  class: "field"
};
const _hoisted_60$3 = ["value"];
const _hoisted_61$3 = { class: "column is-2 xlvask-usage-actions-column" };
const _hoisted_62$3 = { class: "content" };
const _hoisted_63$2 = { class: "buttons" };
const _hoisted_64$1 = {
  class: "button is-fullwidth is-success is-light",
  disabled: "true"
};
const _hoisted_65$1 = ["onClick"];
const _hoisted_66$1 = ["onClick"];
const _hoisted_67$1 = ["onClick"];
const _hoisted_68$1 = ["onClick"];
const _hoisted_69$1 = ["onClick"];
const _hoisted_70$1 = ["onClick"];
const _hoisted_71$1 = { class: "message is-info" };
const _hoisted_72$1 = { class: "card-footer" };
const _hoisted_73$1 = ["onClick"];

function _sfc_render$G(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock(Fragment, null, [
    withDirectives(createBaseVNode("table", _hoisted_1$z, [
      createBaseVNode("thead", null, [
        createBaseVNode("tr", null, [
          (openBlock(true), createElementBlock(Fragment, null, renderList($setup.tableHeaders, (tableHeaders) => {
            return (openBlock(), createElementBlock(Fragment, { key: tableHeaders }, [
              (tableHeaders.sortable)
                ? (openBlock(), createElementBlock("th", {
                    key: 0,
                    class: normalizeClass({
                'is-clickable': tableHeaders.sortable,
                'has-text-centered': tableHeaders.name === 'id'
            }),
                    onClick: $event => ($setup.onTableHeaderClick(tableHeaders.name))
                  }, [
                    createBaseVNode("span", _hoisted_3$o, [
                      createBaseVNode("span", _hoisted_4$o, toDisplayString(tableHeaders.title), 1 /* TEXT */),
                      ($setup.isColumnCurrentlyBeingSortedBy(tableHeaders.name))
                        ? (openBlock(), createElementBlock("span", {
                            key: 0,
                            class: normalizeClass([{
                    'fas fa-sort-up': $setup.isCurrentSortDirectionAscending(),
                    'fas fa-sort-down': $setup.isCurrentSortDirectionDescending()
                }, "icon is-small"])
                          }, null, 2 /* CLASS */))
                        : createCommentVNode("v-if", true)
                    ])
                  ], 10 /* CLASS, PROPS */, _hoisted_2$r))
                : (openBlock(), createElementBlock("th", {
                    key: 1,
                    class: normalizeClass({
                'has-text-centered': tableHeaders.name === 'id'
            })
                  }, [
                    createBaseVNode("span", _hoisted_5$n, [
                      createBaseVNode("span", _hoisted_6$n, toDisplayString(tableHeaders.title), 1 /* TEXT */)
                    ])
                  ], 2 /* CLASS */))
            ], 64 /* STABLE_FRAGMENT */))
          }), 128 /* KEYED_FRAGMENT */))
        ])
      ]),
      createBaseVNode("tbody", null, [
        (openBlock(true), createElementBlock(Fragment, null, renderList($setup.filteredObjects, (object) => {
          return (openBlock(), createElementBlock("tr", {
            key: object.id
          }, [
            createCommentVNode(" Id "),
            createBaseVNode("td", _hoisted_7$m, toDisplayString(object.id), 1 /* TEXT */),
            createCommentVNode(" Department "),
            createBaseVNode("td", null, toDisplayString($setup.getDepartmentName(object.department_id)), 1 /* TEXT */),
            createCommentVNode(" Lane "),
            createBaseVNode("td", null, toDisplayString(object.lane), 1 /* TEXT */),
            createCommentVNode(" Customer Number "),
            createBaseVNode("td", null, toDisplayString(object.customer_name), 1 /* TEXT */),
            createCommentVNode(" Order Id "),
            createBaseVNode("td", null, toDisplayString(object.order_id), 1 /* TEXT */),
            createCommentVNode(" Created At "),
            createBaseVNode("td", null, toDisplayString(object.created_at), 1 /* TEXT */),
            createBaseVNode("td", _hoisted_8$m, [
              createCommentVNode(" Actions "),
              createVNode($setup["ActionSettingsWheelButton"], {
                order_id: object.order_id,
                refreshFunction: $setup.loadList
              }, {
                actions: withCtx(() => [
                  createCommentVNode(" Label "),
                  createVNode($setup["ActionSettingsWheelItemLabel"], {
                    label: 'Mulig duplikat af ' + object.order_id
                  }, null, 8 /* PROPS */, ["label"]),
                  createCommentVNode(" Compare\n            <ActionSettingsWheelItem\n              :icon=\"'fas fa-search-plus'\"\n              :label=\"SessionUser.objects.global.language.compare\"\n              @click=\"onClickCompare(object)\"\n            />\n            "),
                  createCommentVNode(" Mark as duplicate (Link to order) "),
                  createVNode($setup["ActionSettingsWheelItem"], {
                    icon: 'fas fa-link',
                    label: $setup.SessionUser.objects.global.language.attach_to_order,
                    onClick: $event => ($setup.onClickAttachToOrder(object))
                  }, null, 8 /* PROPS */, ["label", "onClick"]),
                  createCommentVNode(" Mark as not duplicate "),
                  createVNode($setup["ActionSettingsWheelItem"], {
                    icon: 'fas fa-check',
                    label: $setup.SessionUser.objects.global.language.mark_as_not_duplicate,
                    onClick: $event => ($setup.onClickMarkAsNotDuplicate(object))
                  }, null, 8 /* PROPS */, ["label", "onClick"])
                ]),
                _: 2 /* DYNAMIC */
              }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["order_id", "refreshFunction"])
            ])
          ]))
        }), 128 /* KEYED_FRAGMENT */))
      ]),
      createBaseVNode("tfoot", null, [
        createBaseVNode("tr", null, [
          createBaseVNode("td", _hoisted_9$k, "Viser " + toDisplayString($setup.filteredObjects.length) + " transaktioner", 1 /* TEXT */)
        ])
      ])
    ], 512 /* NEED_PATCH */), [
      [vShow, false]
    ]),
    (openBlock(true), createElementBlock(Fragment, null, renderList($setup.filteredObjects, (object) => {
      return (openBlock(), createElementBlock(Fragment, {
        key: object.id
      }, [
        createVNode($setup["WhiteBoxCard"], {
          loading: object.loading ?? false,
          toggleable: true,
          class: normalizeClass({ 'xlvask-usage-card--highlighted': $setup.isHighlightedUsageLog(object) }),
          onMouseover: $event => ($setup.automaticallyLoadContent(object)),
          onClick: $event => ($setup.automaticallyLoadContent(object)),
          "default-open": $setup.isHighlightedUsageLog(object) || (object.isOpen ?? false)
        }, {
          header: withCtx(() => [
            createBaseVNode("div", _hoisted_10$j, [
              createBaseVNode("div", _hoisted_11$f, [
                createBaseVNode("div", _hoisted_12$e, [
                  createBaseVNode("span", _hoisted_13$d, toDisplayString(object.reg_1), 1 /* TEXT */),
                  createBaseVNode("span", _hoisted_14$d, toDisplayString($setup.humanReadableTimeAgo(object.created_at)), 1 /* TEXT */),
                  ($setup.getObjectPrimaryProductName(object))
                    ? (openBlock(), createElementBlock("span", _hoisted_15$d, toDisplayString($setup.getObjectPrimaryProductName(object)), 1 /* TEXT */))
                    : createCommentVNode("v-if", true),
                  ($setup.doesObjectHaveAmount(object))
                    ? (openBlock(), createElementBlock("span", _hoisted_16$d, toDisplayString($setup.SessionUser.functions.currency.toLocal($setup.getObjectPrice(object).toFixed(2))), 1 /* TEXT */))
                    : createCommentVNode("v-if", true)
                ]),
                createBaseVNode("div", _hoisted_17$b, [
                  createBaseVNode("span", {
                    class: normalizeClass(["tag is-light is-size-7 xlvask-usage-chip", { 'is-grey': !$setup.isObjectAttachedToOrder(object), 'is-success': $setup.isObjectAttachedToOrder(object) }])
                  }, [
                    createBaseVNode("span", _hoisted_18$b, [
                      createBaseVNode("i", {
                        class: normalizeClass(["fas", $setup.isObjectAttachedToOrder(object) ? 'fa-link' : 'fa-unlink'])
                      }, null, 2 /* CLASS */)
                    ]),
                    createBaseVNode("span", _hoisted_19$9, toDisplayString($setup.isObjectAttachedToOrder(object) ? 'Tilknyttet ordre' : 'Ikke tilknyttet ordre'), 1 /* TEXT */)
                  ], 2 /* CLASS */),
                  ($setup.hasAutomationState(object))
                    ? (openBlock(), createElementBlock("span", {
                        key: 0,
                        class: normalizeClass(["tag is-light is-size-7 xlvask-usage-chip xlvask-usage-automation-chip", $setup.getAutomationTagClass(object)]),
                        "data-testid": 'xlvask-automation-suggestion-' + object.id
                      }, [
                        createBaseVNode("span", _hoisted_21$8, [
                          createBaseVNode("i", {
                            class: normalizeClass(["fas", $setup.getAutomationIconClass(object)])
                          }, null, 2 /* CLASS */)
                        ]),
                        createBaseVNode("span", _hoisted_22$8, toDisplayString($setup.getAutomationLabel(object)), 1 /* TEXT */)
                      ], 10 /* CLASS, PROPS */, _hoisted_20$8))
                    : createCommentVNode("v-if", true),
                  ($setup.doesObjectHaveDuplicates(object))
                    ? (openBlock(), createElementBlock("span", {
                        key: 1,
                        class: normalizeClass(["tag is-light is-size-7 xlvask-usage-chip xlvask-usage-warning-chip", { 'is-success': $setup.doesObjectHaveExactMatch(object), 'is-warning': !$setup.doesObjectHaveExactMatch(object) }])
                      }, [
                        createBaseVNode("span", _hoisted_23$8, [
                          createBaseVNode("i", {
                            class: normalizeClass(["fas", $setup.doesObjectHaveExactMatch(object) ? 'fa-check' : 'fa-exclamation-triangle'])
                          }, null, 2 /* CLASS */)
                        ]),
                        createBaseVNode("span", _hoisted_24$8, toDisplayString(($setup.doesObjectHaveExactMatch(object) ? $setup.SessionUser.objects.global.language.price_match : $setup.SessionUser.objects.global.language.price_unmatch)), 1 /* TEXT */)
                      ], 2 /* CLASS */))
                    : createCommentVNode("v-if", true),
                  createBaseVNode("span", _hoisted_25$8, [
                    createBaseVNode("span", _hoisted_26$8, toDisplayString($setup.getDepartmentName(object.department_id)), 1 /* TEXT */),
                    createBaseVNode("span", _hoisted_27$8, toDisplayString(object.lane), 1 /* TEXT */)
                  ])
                ])
              ]),
              createBaseVNode("div", {
                class: "xlvask-usage-card-customer",
                title: object.customer_name
              }, toDisplayString(object.customer_name), 9 /* TEXT, PROPS */, _hoisted_28$8)
            ])
          ]),
          content: withCtx(() => [
            createBaseVNode("div", _hoisted_29$7, [
              createBaseVNode("div", _hoisted_30$7, [
                createBaseVNode("div", _hoisted_31$7, [
                  ($setup.hasAutomationState(object))
                    ? (openBlock(), createElementBlock("article", {
                        key: 0,
                        class: normalizeClass(["message mb-3", $setup.getAutomationMessageClass(object)])
                      }, [
                        createBaseVNode("div", _hoisted_32$7, [
                          createBaseVNode("div", _hoisted_33$7, [
                            createBaseVNode("div", null, [
                              createBaseVNode("p", _hoisted_34$7, [
                                createBaseVNode("span", _hoisted_35$7, [
                                  createBaseVNode("i", {
                                    class: normalizeClass(["fas", $setup.getAutomationIconClass(object)])
                                  }, null, 2 /* CLASS */)
                                ]),
                                createBaseVNode("span", null, toDisplayString($setup.getAutomationLabel(object)), 1 /* TEXT */)
                              ]),
                              ($setup.getAutomationReason(object))
                                ? (openBlock(), createElementBlock("p", _hoisted_36$6, toDisplayString($setup.getAutomationReason(object)), 1 /* TEXT */))
                                : createCommentVNode("v-if", true),
                              ($setup.getAutomationConfidence(object))
                                ? (openBlock(), createElementBlock("p", _hoisted_37$6, toDisplayString($setup.getAutomationConfidence(object)), 1 /* TEXT */))
                                : createCommentVNode("v-if", true)
                            ]),
                            ($setup.isAutomationActionable(object))
                              ? (openBlock(), createElementBlock("div", _hoisted_38$6, [
                                  createBaseVNode("button", {
                                    class: normalizeClass(["button is-small is-success", { 'is-loading': object.automationLoading }]),
                                    disabled: object.automationLoading,
                                    "data-testid": 'xlvask-automation-accept-' + object.id,
                                    onClick: withModifiers($event => ($setup.acceptAutomation(object)), ["stop"])
                                  }, " Accepter ", 10 /* CLASS, PROPS */, _hoisted_39$6),
                                  createBaseVNode("button", {
                                    class: normalizeClass(["button is-small is-light", { 'is-loading': object.automationLoading }]),
                                    disabled: object.automationLoading,
                                    "data-testid": 'xlvask-automation-deny-' + object.id,
                                    onClick: withModifiers($event => ($setup.denyAutomation(object)), ["stop"])
                                  }, " Afvis ", 10 /* CLASS, PROPS */, _hoisted_40$6)
                                ]))
                              : createCommentVNode("v-if", true)
                          ])
                        ])
                      ], 2 /* CLASS */))
                    : createCommentVNode("v-if", true),
                  createBaseVNode("div", {
                    class: normalizeClass(["message", { 'is-warning': (!$setup.isObjectAttachedToOrder(object)), 'is-success': $setup.isObjectAttachedToOrder(object) }])
                  }, [
                    createBaseVNode("div", _hoisted_41$6, [
                      (object.wash_id)
                        ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                            _cache[0] || (_cache[0] = createBaseVNode("span", { class: "has-text-weight-bold" }, "Vask ID:", -1 /* CACHED */)),
                            createTextVNode(" " + toDisplayString(object.wash_id), 1 /* TEXT */)
                          ], 64 /* STABLE_FRAGMENT */))
                        : (openBlock(), createElementBlock("span", _hoisted_42$6, "Denne vask er muligvis allerede blevet trukket.")),
                      createCommentVNode(" Compare button "),
                      withDirectives(createBaseVNode("button", {
                        class: "button is-small is-light is-warning",
                        onClick: $event => ($setup.onClickCompareToggle(object))
                      }, [
                        (!$setup.isComparingOrders(object))
                          ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                              _cache[1] || (_cache[1] = createBaseVNode("span", { class: "icon is-small" }, [
                                createBaseVNode("i", { class: "fas fa-search-plus" })
                              ], -1 /* CACHED */)),
                              _cache[2] || (_cache[2] = createBaseVNode("span", null, "Vis match", -1 /* CACHED */))
                            ], 64 /* STABLE_FRAGMENT */))
                          : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
                              _cache[3] || (_cache[3] = createBaseVNode("span", { class: "icon is-small" }, [
                                createBaseVNode("i", { class: "fas fa-search-minus" })
                              ], -1 /* CACHED */)),
                              _cache[4] || (_cache[4] = createBaseVNode("span", null, "Skjul match", -1 /* CACHED */))
                            ], 64 /* STABLE_FRAGMENT */))
                      ], 8 /* PROPS */, _hoisted_43$6), [
                        [vShow, object.duplicates?.length && !$setup.isObjectAttachedToOrder(object)]
                      ]),
                      _cache[5] || (_cache[5] = createBaseVNode("br", null, null, -1 /* CACHED */)),
                      createCommentVNode(" Potential duplicates "),
                      (object.duplicates?.length)
                        ? (openBlock(), createElementBlock(Fragment, { key: 2 }, [
                            (object.duplicates.length > 0 && !$setup.isObjectAttachedToOrder(object))
                              ? (openBlock(), createElementBlock("p", _hoisted_44$6, [
                                  createBaseVNode("strong", null, toDisplayString($setup.SessionUser.objects.global.language.possible_duplicates) + ":", 1 /* TEXT */)
                                ]))
                              : createCommentVNode("v-if", true),
                            createBaseVNode("ul", null, [
                              (openBlock(true), createElementBlock(Fragment, null, renderList(object.duplicates, (duplicate) => {
                                return (openBlock(), createElementBlock("li", {
                                  key: duplicate.id
                                }, [
                                  createBaseVNode("a", {
                                    onClick: $event => ($setup.redirectDepartmentOrderPage(duplicate.id, duplicate.department_id))
                                  }, toDisplayString($setup.getDepartmentName(duplicate.department_id)) + " - " + toDisplayString(duplicate.created_at) + toDisplayString($setup.doesObjectPriceMatchPotentialDuplicate(object, duplicate) ? '' : ' (Pris matcher ikke)'), 9 /* TEXT, PROPS */, _hoisted_45$6)
                                ]))
                              }), 128 /* KEYED_FRAGMENT */))
                            ])
                          ], 64 /* STABLE_FRAGMENT */))
                        : createCommentVNode("v-if", true)
                    ])
                  ], 2 /* CLASS */),
                  (object.items)
                    ? (openBlock(), createElementBlock("div", _hoisted_46$6, [
                        createBaseVNode("div", {
                          class: normalizeClass(["column", { 'is-12': (!object.duplicates?.length && !$setup.isComparingOrders(object)), 'is-6': (object.duplicates?.length && $setup.isComparingOrders(object)) }])
                        }, [
                          createBaseVNode("div", _hoisted_47$6, [
                            createBaseVNode("input", {
                              class: "input",
                              type: "text",
                              readonly: "",
                              value: $setup.getDepartmentName(object.department_id) + ' - ' + object.created_at + ' (' + $setup.SessionUser.objects.global.language.generated + ')'
                            }, null, 8 /* PROPS */, _hoisted_48$6)
                          ]),
                          createVNode($setup["OrderItemsTable"], {
                            "order-items": object.items,
                            "allow-edit": $setup.isObjectEditing(object),
                            "set-item-value": (item, value, key) => {
                      item[key] = value;
                    }
                          }, null, 8 /* PROPS */, ["order-items", "allow-edit", "set-item-value"]),
                          createCommentVNode(" Notes: Generated order "),
                          (object.notes)
                            ? (openBlock(), createElementBlock("div", _hoisted_49$5, [
                                _cache[6] || (_cache[6] = createBaseVNode("label", { class: "label" }, "Noter:", -1 /* CACHED */)),
                                createBaseVNode("textarea", _hoisted_50$5, toDisplayString(object.notes), 1 /* TEXT */)
                              ]))
                            : createCommentVNode("v-if", true),
                          createCommentVNode(" Reference: Generated order "),
                          (object.reference)
                            ? (openBlock(), createElementBlock("div", _hoisted_51$5, [
                                _cache[7] || (_cache[7] = createBaseVNode("label", { class: "label" }, "Reference:", -1 /* CACHED */)),
                                createBaseVNode("input", {
                                  class: "input",
                                  type: "text",
                                  readonly: "",
                                  value: object.reference
                                }, null, 8 /* PROPS */, _hoisted_52$5)
                              ]))
                            : createCommentVNode("v-if", true)
                        ], 2 /* CLASS */),
                        ((object.duplicates?.length && $setup.isComparingOrders(object)))
                          ? (openBlock(), createElementBlock("div", _hoisted_53$4, [
                              createBaseVNode("div", _hoisted_54$4, [
                                withDirectives(createBaseVNode("select", {
                                  class: "input select is-link",
                                  "onUpdate:modelValue": $event => ((object.selectedDuplicateId) = $event),
                                  onChange: $event => ($setup.setSelectedDuplicate($event.target.value, object))
                                }, [
                                  _cache[8] || (_cache[8] = createBaseVNode("option", {
                                    value: "",
                                    disabled: "",
                                    selected: ""
                                  }, "Vælg en duplikat", -1 /* CACHED */)),
                                  (openBlock(true), createElementBlock(Fragment, null, renderList(object.duplicates, (duplicate) => {
                                    return (openBlock(), createElementBlock("option", {
                                      key: duplicate.id,
                                      value: duplicate.id
                                    }, toDisplayString($setup.getDepartmentName(duplicate.department_id)) + " - " + toDisplayString(duplicate.created_at) + " (" + toDisplayString($setup.SessionUser.objects.global.language.possible_duplicates) + ") ", 9 /* TEXT, PROPS */, _hoisted_56$4))
                                  }), 128 /* KEYED_FRAGMENT */))
                                ], 40 /* PROPS, NEED_HYDRATION */, _hoisted_55$4), [
                                  [vModelSelect, object.selectedDuplicateId]
                                ])
                              ]),
                              (openBlock(true), createElementBlock(Fragment, null, renderList(object.duplicates, (duplicate) => {
                                return (openBlock(), createElementBlock(Fragment, {
                                  key: duplicate.id
                                }, [
                                  (object.selectedDuplicateId === duplicate.id)
                                    ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                                        createVNode($setup["OrderItemsTable"], {
                                          "order-items": duplicate.order_items
                                        }, null, 8 /* PROPS */, ["order-items"]),
                                        createCommentVNode(" Notes: Actual order "),
                                        (duplicate.notes)
                                          ? (openBlock(), createElementBlock("div", _hoisted_57$4, [
                                              _cache[9] || (_cache[9] = createBaseVNode("label", { class: "label" }, "Noter:", -1 /* CACHED */)),
                                              createBaseVNode("textarea", _hoisted_58$4, toDisplayString(duplicate.notes), 1 /* TEXT */)
                                            ]))
                                          : createCommentVNode("v-if", true),
                                        createCommentVNode(" Reference: Actual order "),
                                        (duplicate.reference)
                                          ? (openBlock(), createElementBlock("div", _hoisted_59$3, [
                                              _cache[10] || (_cache[10] = createBaseVNode("label", { class: "label" }, "Reference:", -1 /* CACHED */)),
                                              createBaseVNode("input", {
                                                class: "input",
                                                type: "text",
                                                readonly: "",
                                                value: duplicate.reference
                                              }, null, 8 /* PROPS */, _hoisted_60$3)
                                            ]))
                                          : createCommentVNode("v-if", true)
                                      ], 64 /* STABLE_FRAGMENT */))
                                    : createCommentVNode("v-if", true)
                                ], 64 /* STABLE_FRAGMENT */))
                              }), 128 /* KEYED_FRAGMENT */))
                            ]))
                          : createCommentVNode("v-if", true)
                      ]))
                    : createCommentVNode("v-if", true),
                  createBaseVNode("span", null, [
                    _cache[11] || (_cache[11] = createBaseVNode("br", null, null, -1 /* CACHED */)),
                    createTextVNode(toDisplayString(object.wash_id), 1 /* TEXT */)
                  ])
                ])
              ]),
              createBaseVNode("div", _hoisted_61$3, [
                createBaseVNode("div", _hoisted_62$3, [
                  createBaseVNode("div", _hoisted_63$2, [
                    ($setup.isObjectAttachedToOrder(object))
                      ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                          createCommentVNode(" Action buttons, when the object has a wash_id "),
                          createBaseVNode("div", _hoisted_64$1, toDisplayString($setup.SessionUser.objects.global.language.completed), 1 /* TEXT */)
                        ], 64 /* STABLE_FRAGMENT */))
                      : (!$setup.isComparingOrders(object))
                        ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [
                            createCommentVNode(" Action buttons, when not comparing orders "),
                            createBaseVNode("div", {
                              class: "button is-fullwidth is-success is-light",
                              onClick: $event => ($setup.actions.click.approval.accept(object))
                            }, toDisplayString($setup.SessionUser.objects.global.language.complete), 9 /* TEXT, PROPS */, _hoisted_65$1),
                            createBaseVNode("div", {
                              class: "button is-fullwidth is-warning is-light",
                              onClick: $event => ($setup.actions.click.approval.edit(object))
                            }, toDisplayString($setup.SessionUser.objects.global.language.edit), 9 /* TEXT, PROPS */, _hoisted_66$1),
                            createBaseVNode("div", {
                              class: "button is-fullwidth is-danger is-light",
                              onClick: $event => ($setup.actions.click.approval.reject(object))
                            }, toDisplayString($setup.SessionUser.objects.global.language.reject), 9 /* TEXT, PROPS */, _hoisted_67$1),
                            createBaseVNode("div", {
                              class: "button is-fullwidth is-light",
                              onClick: $event => ($setup.actions.click.approval.history(object))
                            }, toDisplayString($setup.SessionUser.objects.global.language.history), 9 /* TEXT, PROPS */, _hoisted_68$1)
                          ], 64 /* STABLE_FRAGMENT */))
                        : ($setup.isComparingOrders(object))
                          ? (openBlock(), createElementBlock(Fragment, { key: 2 }, [
                              createCommentVNode(" Action buttons, when comparing orders "),
                              createBaseVNode("div", {
                                class: "button is-fullwidth is-success is-light",
                                onClick: $event => ($setup.actions.click.comparison.isEqual(object))
                              }, " Disse ordrer er ens ", 8 /* PROPS */, _hoisted_69$1),
                              createBaseVNode("div", {
                                class: "button is-fullwidth is-warning is-light",
                                onClick: $event => ($setup.actions.click.comparison.isNotEqual(object))
                              }, toDisplayString($setup.SessionUser.objects.global.language.regret), 9 /* TEXT, PROPS */, _hoisted_70$1)
                            ], 64 /* STABLE_FRAGMENT */))
                          : createCommentVNode("v-if", true)
                  ])
                ])
              ])
            ])
          ]),
          _: 2 /* DYNAMIC */
        }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["loading", "class", "onMouseover", "onClick", "default-open"]),
        withDirectives(createBaseVNode("article", _hoisted_71$1, [
          _cache[12] || (_cache[12] = createBaseVNode("div", { class: "message-header" }, [
            createBaseVNode("p", null, "Info"),
            createBaseVNode("button", {
              class: "delete",
              "aria-label": "delete"
            })
          ], -1 /* CACHED */)),
          _cache[13] || (_cache[13] = createBaseVNode("div", { class: "message-body" }, [
            createTextVNode(" Lorem ipsum dolor sit amet, consectetur adipiscing elit. "),
            createBaseVNode("strong", null, "Pellentesque risus mi"),
            createTextVNode(", tempus quis placerat ut, porta nec nulla. Vestibulum rhoncus ac ex sit amet fringilla. Nullam gravida purus diam, et dictum "),
            createBaseVNode("a", null, "felis venenatis"),
            createTextVNode(" efficitur. Aenean ac "),
            createBaseVNode("em", null, "eleifend lacus"),
            createTextVNode(", in mollis lectus. Donec sodales, arcu et sollicitudin porttitor, tortor urna tempor ligula, id porttitor mi magna a neque. Donec dui urna, vehicula et sem eget, facilisis sodales sem. ")
          ], -1 /* CACHED */)),
          createBaseVNode("div", _hoisted_72$1, [
            createBaseVNode("button", {
              class: "card-footer-item",
              onClick: $event => ($setup.redirectDepartmentOrderPage(object.order_id, object.department_id))
            }, " Gå til ordre ", 8 /* PROPS */, _hoisted_73$1)
          ])
        ], 512 /* NEED_PATCH */), [
          [vShow, false]
        ])
      ], 64 /* STABLE_FRAGMENT */))
    }), 128 /* KEYED_FRAGMENT */))
  ], 64 /* STABLE_FRAGMENT */))
}
const XlvaskUsageOrdersTable = /*#__PURE__*/_export_sfc(_sfc_main$1d, [['render',_sfc_render$G],['__scopeId',"data-v-62b5f8a0"],['__file',"xlvaskUsageOrdersTable.vue"]]);

const { width } = useWindowSize();
const _sfc_main$1c = defineComponent({
  name: "PaginationDisplayIsSmall",
  props: {
    isSmall: {
      type: Boolean,
      default: false
    }
  }
});
const isSmall = computed(() => width.value < 1024);

const PaginationDisplayIsSmall = /* @__PURE__ */ _export_sfc(_sfc_main$1c, [["__file", "PaginationDisplayIsSmall.vue"]]);

const _sfc_main$1b = /* @__PURE__ */ defineComponent({
  __name: "PaginationDisplayItemColumn",
  props: {
    label: {
      type: String,
      default: "",
      required: true
    }
  },
  setup(__props, { expose: __expose }) {
    __expose();
    const props = __props;
    const __returned__ = { props, isSmall };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$y = { class: "label" };
const _hoisted_2$q = { class: "control" };
function _sfc_render$F(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock(
    "div",
    {
      class: normalizeClass(["column is-narrow my-3", { "is-hidden": $setup.isSmall }])
    },
    [
      createBaseVNode(
        "label",
        _hoisted_1$y,
        toDisplayString($setup.props.label),
        1
        /* TEXT */
      ),
      createBaseVNode("div", _hoisted_2$q, [
        renderSlot(_ctx.$slots, "control")
      ])
    ],
    2
    /* CLASS */
  );
}
const PaginationDisplayItemColumn = /* @__PURE__ */ _export_sfc(_sfc_main$1b, [["render", _sfc_render$F], ["__file", "PaginationDisplayItemColumn.vue"]]);

const DATE_ONLY_PATTERN$3 = /^(\d{4})-(\d{2})-(\d{2})$/;
const DATE_ONLY_PREFIX_PATTERN = /^(\d{4}-\d{2}-\d{2})/;

const padDatePart$1 = (value) => String(value).padStart(2, "0");

const isValidDate = (value) => value instanceof Date && !Number.isNaN(value.getTime());

const formatLocalDateOnly = (value = new Date()) => {
  if (value === null) {
    return "";
  }

  if (typeof value === "string") {
    const directMatch = value.trim().match(DATE_ONLY_PREFIX_PATTERN);
    if (directMatch) {
      return directMatch[1];
    }
  }

  const date = value instanceof Date ? value : new Date(value);
  if (!isValidDate(date)) {
    return "";
  }

  return [
    date.getFullYear(),
    padDatePart$1(date.getMonth() + 1),
    padDatePart$1(date.getDate()),
  ].join("-");
};

const parseLocalDateOnly = (value) => {
  if (value instanceof Date) {
    return isValidDate(value)
      ? new Date(value.getFullYear(), value.getMonth(), value.getDate())
      : new Date(Number.NaN);
  }

  const stringValue = String(value ?? "").trim();
  const match = DATE_ONLY_PATTERN$3.exec(stringValue);
  if (match) {
    const year = Number(match[1]);
    const month = Number(match[2]);
    const day = Number(match[3]);
    const parsed = new Date(year, month - 1, day);

    if (
      parsed.getFullYear() === year
      && parsed.getMonth() === month - 1
      && parsed.getDate() === day
    ) {
      return parsed;
    }

    return new Date(Number.NaN);
  }

  const parsed = new Date(stringValue);
  return isValidDate(parsed)
    ? new Date(parsed.getFullYear(), parsed.getMonth(), parsed.getDate())
    : parsed;
};

const todayLocalDateOnly = () => formatLocalDateOnly(new Date());

const yesterdayLocalDateOnly = () => {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  return formatLocalDateOnly(yesterday);
};

const startOfLocalDate = (value) => {
  const date = parseLocalDateOnly(value);
  if (!isValidDate(date)) {
    return date;
  }
  date.setHours(0, 0, 0, 0);
  return date;
};

const endOfLocalDate = (value) => {
  const date = parseLocalDateOnly(value);
  if (!isValidDate(date)) {
    return date;
  }
  date.setHours(23, 59, 59, 999);
  return date;
};

const DATE_ONLY_PATTERN$2 = /^(\d{4})-(\d{2})-(\d{2})$/;
const MONTH_ONLY_PATTERN = /^(\d{4})-(\d{2})$/;

const normalizeLocale = (locale) => String(locale || "da").trim() || "da";

const padDatePart = (value) => String(value).padStart(2, "0");

const normalizeDatepickerDate = (value) => {
  if (value instanceof Date) {
    return Number.isNaN(value.getTime())
      ? null
      : new Date(value.getFullYear(), value.getMonth(), value.getDate());
  }

  const stringValue = String(value ?? "").trim();
  if (!stringValue) {
    return null;
  }

  const parsed = parseLocalDateOnly(stringValue);
  return Number.isNaN(parsed.getTime()) ? null : parsed;
};

const normalizeDatepickerMonth = (value) => {
  if (value instanceof Date) {
    return Number.isNaN(value.getTime())
      ? null
      : new Date(value.getFullYear(), value.getMonth(), 1);
  }

  const stringValue = String(value ?? "").trim();
  if (!stringValue) {
    return null;
  }

  const monthMatch = MONTH_ONLY_PATTERN.exec(stringValue);
  if (monthMatch) {
    const year = Number(monthMatch[1]);
    const month = Number(monthMatch[2]);
    const parsed = new Date(year, month - 1, 1);
    return parsed.getFullYear() === year && parsed.getMonth() === month - 1 ? parsed : null;
  }

  const dateMatch = DATE_ONLY_PATTERN$2.exec(stringValue);
  if (dateMatch) {
    return normalizeDatepickerDate(stringValue);
  }

  const parsed = new Date(stringValue);
  return Number.isNaN(parsed.getTime()) ? null : new Date(parsed.getFullYear(), parsed.getMonth(), 1);
};

const formatDatepickerDateForApi = (value) => {
  const date = normalizeDatepickerDate(value);
  return date ? formatLocalDateOnly(date) : "";
};

const formatDatepickerMonthForApi = (value) => {
  const date = normalizeDatepickerMonth(value);
  if (!date) {
    return "";
  }

  return `${date.getFullYear()}-${padDatePart(date.getMonth() + 1)}`;
};

const formatDatepickerDateForLocale = (value, locale) => {
  const date = normalizeDatepickerDate(value);
  if (!date) {
    return "";
  }

  return new Intl.DateTimeFormat(normalizeLocale(locale), {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  }).format(date);
};

const formatDatepickerMonthForLocale = (value, locale) => {
  const date = normalizeDatepickerMonth(value);
  if (!date) {
    return "";
  }

  return new Intl.DateTimeFormat(normalizeLocale(locale), {
    year: "numeric",
    month: "long",
  }).format(date);
};

const parseDatepickerInput = (value, locale) => {
  const stringValue = String(value ?? "").trim();
  if (!stringValue) {
    return null;
  }

  const direct = normalizeDatepickerDate(stringValue);
  if (direct) {
    return direct;
  }

  const parts = new Intl.DateTimeFormat(normalizeLocale(locale))
    .formatToParts(new Date(2000, 11, 25))
    .filter((part) => part.type !== "literal")
    .map((part) => part.type);
  const numbers = stringValue.match(/\d+/g)?.map(Number) || [];
  if (numbers.length < 3) {
    return null;
  }

  const values = {};
  parts.forEach((type, index) => {
    values[type] = numbers[index];
  });

  const year = values.year;
  const month = values.month;
  const day = values.day;
  if (!year || !month || !day) {
    return null;
  }

  const parsed = new Date(year, month - 1, day);
  return parsed.getFullYear() === year && parsed.getMonth() === month - 1 && parsed.getDate() === day
    ? parsed
    : null;
};

const parseMonthpickerInput = (value, locale) => {
  const direct = normalizeDatepickerMonth(value);
  if (direct) {
    return direct;
  }

  const parsed = new Date(String(value ?? ""));
  return Number.isNaN(parsed.getTime()) ? null : new Date(parsed.getFullYear(), parsed.getMonth(), 1);
};

const _sfc_main$1a = /*@__PURE__*/Object.assign({
  inheritAttrs: false,
}, {
  __name: 'BuefyDateField',
  props: {
  modelValue: {
    type: [String, Date],
    default: "",
  },
  valueType: {
    type: String,
    default: "string",
    validator: (value) => ["string", "date", "nullable-string"].includes(value),
  },
  placeholder: {
    type: String,
    default: "",
  },
  icon: {
    type: String,
    default: "calendar",
  },
  disabled: Boolean,
  readonly: Boolean,
  required: Boolean,
  expanded: {
    type: Boolean,
    default: true,
  },
  appendToBody: {
    type: Boolean,
    default: true,
  },
  position: {
    type: String,
    default: "is-bottom-left",
  },
  openOnFocus: {
    type: Boolean,
    default: true,
  },
  clearable: Boolean,
  minDate: {
    type: Date,
    default: null,
  },
  maxDate: {
    type: Date,
    default: null,
  },
  unselectableDates: {
    type: [Array, Function],
    default: null,
  },
  selectableDates: {
    type: [Array, Function],
    default: null,
  },
  events: {
    type: Array,
    default: () => [],
  },
  indicators: {
    type: String,
    default: "dots",
  },
  dataTestid: {
    type: String,
    default: "",
  },
},
  emits: ["update:modelValue", "change"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();



const props = __props;

const emit = __emit;
const { locale } = useI18n({ useScope: "global" });
const attrs = useAttrs();
const datepickerTestId = computed(() => props.dataTestid || attrs["data-testid"] || undefined);

const selectedDate = computed({
  get: () => normalizeDatepickerDate(props.modelValue),
  set: (value) => {
    const normalized = normalizeDatepickerDate(value);
    let nextValue = "";

    if (props.valueType === "date") {
      nextValue = normalized;
    } else if (props.valueType === "nullable-string") {
      nextValue = normalized ? formatDatepickerDateForApi(normalized) : null;
    } else {
      nextValue = normalized ? formatDatepickerDateForApi(normalized) : "";
    }

    emit("update:modelValue", nextValue);
    emit("change", nextValue);
  },
});

const showClearIcon = computed(() => (
  props.clearable
  && selectedDate.value !== null
  && !props.disabled
  && !props.readonly
));

const clearSelectedDate = (event) => {
  event?.preventDefault?.();
  event?.stopPropagation?.();
  selectedDate.value = null;
};

const formatter = (value) => formatDatepickerDateForLocale(value, locale.value);
const parser = (value) => parseDatepickerInput(value, locale.value);

const __returned__ = { props, emit, locale, attrs, datepickerTestId, selectedDate, showClearIcon, clearSelectedDate, formatter, parser, computed, useAttrs, get useI18n() { return useI18n }, get BDatepicker() { return BDatepicker }, get formatDatepickerDateForApi() { return formatDatepickerDateForApi }, get formatDatepickerDateForLocale() { return formatDatepickerDateForLocale }, get normalizeDatepickerDate() { return normalizeDatepickerDate }, get parseDatepickerInput() { return parseDatepickerInput } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

});

const _hoisted_1$x = ["data-testid"];

function _sfc_render$E(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", { "data-testid": $setup.datepickerTestId }, [
    createVNode($setup["BDatepicker"], mergeProps($setup.attrs, {
      modelValue: $setup.selectedDate,
      "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (($setup.selectedDate) = $event)),
      "icon-pack": "fas",
      icon: $props.icon,
      locale: $setup.locale,
      placeholder: $props.placeholder,
      position: $props.position,
      "open-on-focus": $props.openOnFocus,
      disabled: $props.disabled,
      readonly: $props.readonly,
      required: $props.required,
      expanded: $props.expanded,
      "append-to-body": $props.appendToBody,
      "min-date": $props.minDate,
      "max-date": $props.maxDate,
      "unselectable-dates": $props.unselectableDates,
      "selectable-dates": $props.selectableDates,
      events: $props.events,
      indicators: $props.indicators,
      "icon-right": $setup.showClearIcon ? 'times-circle' : undefined,
      "icon-right-clickable": $setup.showClearIcon,
      "mobile-native": false,
      editable: true,
      "date-formatter": $setup.formatter,
      "date-parser": $setup.parser,
      onIconRightClick: $setup.clearSelectedDate
    }), null, 16 /* FULL_PROPS */, ["modelValue", "icon", "locale", "placeholder", "position", "open-on-focus", "disabled", "readonly", "required", "expanded", "append-to-body", "min-date", "max-date", "unselectable-dates", "selectable-dates", "events", "indicators", "icon-right", "icon-right-clickable"])
  ], 8 /* PROPS */, _hoisted_1$x))
}
const BuefyDateField = /*#__PURE__*/_export_sfc(_sfc_main$1a, [['render',_sfc_render$E],['__file',"BuefyDateField.vue"]]);

const _sfc_main$19 = /* @__PURE__ */ defineComponent({
  __name: "PaginationDisplayTemplateDate",
  props: /* @__PURE__ */ mergeModels({
    label: {
      type: String,
      required: true,
      default: "Date"
    },
    placeholder: {
      type: String,
      default: ""
    }
  }, {
    "modelValue": {
      type: Date,
      required: true,
      default: () => /* @__PURE__ */ new Date()
    },
    "modelModifiers": {}
  }),
  emits: /* @__PURE__ */ mergeModels(["update:date"], ["update:modelValue"]),
  setup(__props, { expose: __expose, emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const date = useModel(__props, "modelValue");
    __expose({
      date
    });
    const updateDate = (newDate) => {
      emit("update:date", newDate);
    };
    const __returned__ = { props, emit, date, updateDate, PaginationDisplayItemColumn, BuefyDateField };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

function _sfc_render$D(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createBlock($setup["PaginationDisplayItemColumn"], {
    label: $setup.props.label
  }, {
    control: withCtx(() => [
      createVNode($setup["BuefyDateField"], {
        modelValue: $setup.date,
        "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => $setup.date = $event),
        "value-type": "date",
        "data-testid": "pagination-date-picker",
        placeholder: $setup.props.placeholder,
        onChange: $setup.updateDate
      }, null, 8, ["modelValue", "placeholder"])
    ]),
    _: 1
    /* STABLE */
  }, 8, ["label"]);
}
const PaginationDisplayTemplateDate = /* @__PURE__ */ _export_sfc(_sfc_main$19, [["render", _sfc_render$D], ["__file", "PaginationDisplayTemplateDate.vue"]]);

const _sfc_main$18 = /* @__PURE__ */ defineComponent({
  __name: "PaginationDisplayTemplateButton",
  props: {
    label: {
      type: String,
      required: true,
      default: ""
    },
    isLoading: {
      type: Boolean,
      default: false
    },
    selected: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  emits: ["click"],
  setup(__props, { expose: __expose, emit: __emit }) {
    __expose();
    const props = __props;
    const emits = __emit;
    const handleClick = () => {
      if (!props.disabled) {
        emits("click");
      }
    };
    const __returned__ = { props, emits, handleClick, PaginationDisplayItemColumn };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$w = ["disabled"];
function _sfc_render$C(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createBlock($setup["PaginationDisplayItemColumn"], {
    label: $setup.props.label
  }, {
    control: withCtx(() => [
      createBaseVNode("button", {
        class: normalizeClass(["button is-fullwidth", { "is-loading": $setup.props.isLoading, "is-link": $setup.props.selected, "is-disabled": $setup.props.disabled }]),
        disabled: $setup.props.disabled,
        onClick: $setup.handleClick
      }, [
        createCommentVNode(" If there's no default slot content, use the label as button text "),
        _ctx.$slots.default ? renderSlot(_ctx.$slots, "default", { key: 0 }) : (openBlock(), createElementBlock(
          Fragment,
          { key: 1 },
          [
            createCommentVNode(" Display the label next to the icon "),
            createBaseVNode(
              "span",
              null,
              toDisplayString($setup.props.label),
              1
              /* TEXT */
            )
          ],
          64
          /* STABLE_FRAGMENT */
        ))
      ], 10, _hoisted_1$w)
    ]),
    _: 3
    /* FORWARDED */
  }, 8, ["label"]);
}
const PaginationDisplayTemplateButton = /* @__PURE__ */ _export_sfc(_sfc_main$18, [["render", _sfc_render$C], ["__file", "PaginationDisplayTemplateButton.vue"]]);

const datePresetFunctions = {
  week: {
    // Get the first day of the week (Monday) based on the provided date
    firstDayOfWeek: (date) => {
      const adjustedDate = new Date(date.getTime());
      const day = adjustedDate.getDay();
      const diff = (day === 0 ? -6 : 1) - day;
      adjustedDate.setDate(adjustedDate.getDate() + diff);
      return adjustedDate;
    },
    // Get the last day of the week (Sunday) based on the provided date
    lastDayOfWeek: (date) => {
      const adjustedDate = new Date(date.getTime());
      const day = adjustedDate.getDay();
      const diff = (day === 0 ? 0 : 7) - day;
      adjustedDate.setDate(adjustedDate.getDate() + diff);
      return adjustedDate;
    }
  },
  month: {
    // Get the first day of the month based on the provided date first day at 00:00:01
    firstDayOfMonth: (date) => {
      return new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0, 0);
    },
    // Get the last day of the month based on the provided date last day at 23:59:59
    lastDayOfMonth: (date) => {
      return new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59, 999);
    }
  },
  year: {
    // Get the first day of the year based on the provided date
    firstDayOfYear: (date) => {
      return new Date(date.getFullYear(), 0, 1);
    },
    // Get the last day of the year based on the provided date
    lastDayOfYear: (date) => {
      return new Date(date.getFullYear(), 11, 31, 23, 59, 59, 999);
    }
  },
  applyStringModifier: (date, modifier) => {
    const regex = /([+-]?\d+)\s*(day|days|week|weeks|month|months|year|years)/g;
    let modifiedDate = new Date(date.getTime());
    modifier = modifier.trim();
    let match;
    while ((match = regex.exec(modifier)) !== null) {
      const value = parseInt(match[1], 10);
      const unit = match[2];
      switch (unit) {
        case "day":
        case "days":
          modifiedDate.setDate(modifiedDate.getDate() + value);
          break;
        case "week":
        case "weeks":
          modifiedDate.setDate(modifiedDate.getDate() + value * 7);
          break;
        case "month":
        case "months":
          modifiedDate.setMonth(modifiedDate.getMonth() + value);
          break;
        case "year":
        case "years":
          modifiedDate.setFullYear(modifiedDate.getFullYear() + value);
          break;
      }
    }
    return modifiedDate;
  }
};
const today$1 = {
  labelKey: "global.text.today",
  getRange: () => {
    const today2 = /* @__PURE__ */ new Date();
    return { start: today2, end: new Date(today2.getTime()) };
  }
};
const yesterday = {
  labelKey: "global.text.yesterday",
  getRange: () => {
    const yesterday2 = datePresetFunctions.applyStringModifier(/* @__PURE__ */ new Date(), "-1 day");
    return { start: yesterday2, end: new Date(yesterday2.getTime()) };
  }
};
const thisWeek = {
  labelKey: "global.text.this_week",
  getRange: () => ({
    start: datePresetFunctions.week.firstDayOfWeek(/* @__PURE__ */ new Date()),
    end: datePresetFunctions.week.lastDayOfWeek(/* @__PURE__ */ new Date())
  })
};
const thisMonth = {
  labelKey: "global.text.this_month",
  getRange: () => ({
    start: datePresetFunctions.month.firstDayOfMonth(/* @__PURE__ */ new Date()),
    end: datePresetFunctions.month.lastDayOfMonth(/* @__PURE__ */ new Date())
  })
};
const datePresets = [
  ...[today$1, yesterday, thisWeek, thisMonth]
];
const convertToISO = (date) => {
  return formatLocalDateOnly(date);
};
const dateFunctions = {
  datePresetFunctions,
  dateComparison: {
    match: {
      dates: (date1, date2) => {
        return convertToISO(date1.start) === convertToISO(date2.start) && convertToISO(date1.end) === convertToISO(date2.end);
      },
      dateRange: (date, start, end) => {
        return date >= start && date <= end;
      }
    }
  }
};
const _sfc_main$17 = defineComponent({
  name: "PaginationDisplayDates",
  setup() {
    const { t } = useI18n();
    return {
      datePresets,
      dateFunctions,
      t
    };
  }
});

function _sfc_render$B(_ctx, _cache, $props, $setup, $data, $options) {
  return null;
}
const PaginationDisplayDates = /* @__PURE__ */ _export_sfc(_sfc_main$17, [["render", _sfc_render$B], ["__file", "PaginationDisplayDates.vue"]]);

const DATE_FILTER_PLACEHOLDER = "--.--.----";
const _sfc_main$16 = /* @__PURE__ */ defineComponent({
  __name: "PaginationDisplayTemplateDates",
  props: /* @__PURE__ */ mergeModels({
    startDate: {
      type: Date,
      required: true,
      default: () => /* @__PURE__ */ new Date()
      // Default to today
    },
    endDate: {
      type: Date,
      // Use Date or string type to allow for flexibility in date formats
      required: true,
      default: () => /* @__PURE__ */ new Date()
      // Default to today
    }
  }, {
    "startDate": {
      type: Date,
      required: true,
      default: () => /* @__PURE__ */ new Date()
    },
    "startDateModifiers": {},
    "endDate": {
      type: Date,
      required: true,
      default: () => /* @__PURE__ */ new Date()
    },
    "endDateModifiers": {}
  }),
  emits: /* @__PURE__ */ mergeModels(["update:startDate", "update:endDate"], ["update:startDate", "update:endDate"]),
  setup(__props, { expose: __expose, emit: __emit }) {
    __expose();
    const { t } = useI18n();
    const emits = __emit;
    const startDateModel = useModel(__props, "startDate");
    const endDateModel = useModel(__props, "endDate");
    function updateStartDate(date) {
      startDateModel.value = date;
      emits("update:startDate", date);
    }
    function updateEndDate(date) {
      endDateModel.value = date;
      emits("update:endDate", date);
    }
    function getPresetRange(preset) {
      return preset.getRange();
    }
    function isPresetSelected(preset) {
      return dateFunctions.dateComparison.match.dates(
        { start: startDateModel.value, end: endDateModel.value },
        getPresetRange(preset)
      );
    }
    function applyPreset(preset) {
      const range = getPresetRange(preset);
      updateStartDate(new Date(range.start.getTime()));
      updateEndDate(new Date(range.end.getTime()));
    }
    const __returned__ = { t, DATE_FILTER_PLACEHOLDER, emits, startDateModel, endDateModel, updateStartDate, updateEndDate, getPresetRange, isPresetSelected, applyPreset, SessionUser, PaginationDisplayTemplateDate, PaginationDisplayTemplateButton, datePresets };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

function _sfc_render$A(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock(
    Fragment,
    null,
    [
      createVNode($setup["PaginationDisplayTemplateDate"], {
        label: $setup.SessionUser.objects.global.language.date_from,
        "onUpdate:date": $setup.updateStartDate,
        "model-value": $setup.startDateModel,
        placeholder: $setup.DATE_FILTER_PLACEHOLDER
      }, null, 8, ["label", "model-value"]),
      createVNode($setup["PaginationDisplayTemplateDate"], {
        label: $setup.SessionUser.objects.global.language.date_to,
        "onUpdate:date": $setup.updateEndDate,
        "model-value": $setup.endDateModel,
        placeholder: $setup.DATE_FILTER_PLACEHOLDER
      }, null, 8, ["label", "model-value"]),
      (openBlock(true), createElementBlock(
        Fragment,
        null,
        renderList($setup.datePresets, (preset) => {
          return openBlock(), createBlock($setup["PaginationDisplayTemplateButton"], {
            key: preset.labelKey,
            label: $setup.t(preset.labelKey),
            selected: $setup.isPresetSelected(preset),
            onClick: ($event) => $setup.applyPreset(preset)
          }, null, 8, ["label", "selected", "onClick"]);
        }),
        128
        /* KEYED_FRAGMENT */
      ))
    ],
    64
    /* STABLE_FRAGMENT */
  );
}
const PaginationDisplayTemplateDates = /* @__PURE__ */ _export_sfc(_sfc_main$16, [["render", _sfc_render$A], ["__file", "PaginationDisplayTemplateDates.vue"]]);

const SELFWASH_PERIOD_ALL_LIMIT = 10000;

const _sfc_main$15 = {
  __name: 'XLVaskUsagePagination',
  props: {
  autoLoad: {
    type: Boolean, default: true
  }, setCustomerFilter: {
    type: Number, default: 0
  }, hideSearch: {
    type: Boolean, default: false
  }, title: {
    type: String, default: ""
  }, initialDateFrom: {
    type: String, default: ""
  }, initialDateTo: {
    type: String, default: ""
  }, inheritPeriodFilters: {
    type: Boolean, default: false
  }, loadAllAtOnce: {
    type: Boolean, default: false
  }, highlightUsageLogId: {
    type: Number, default: 0
  }
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;
const { t } = useI18n();
const router = useRouter();
const paginatedList = usePaginatedList();
provide(PaginatedListKey, paginatedList);

const {
  isLoading,
  list,
  loadList,
  metaCurrentPage,
  metaItemsPerPage,
  metaTotalItems,
  setEndpoint,
  setMetaItemsPerPage,
  setPage,
  search,
  setFilter,
  setOrder,
  hideSearchField,
  setHideSearchField,
} = paginatedList;

setEndpoint("/modules/xlvask/services/usage/orders", false);
if (props.loadAllAtOnce) {
  setMetaItemsPerPage(SELFWASH_PERIOD_ALL_LIMIT, false);
}
const parseInitialDate = (value) => {
  if (!value) {
    return new Date();
  }

  const parsed = parseLocalDateOnly(value);
  return Number.isNaN(parsed.getTime()) ? new Date() : parsed;
};

const applyInitialPeriodFilters = () => {
  if (props.initialDateFrom) {
    setFilter("StartTime-date_from", props.initialDateFrom, false);
  }

  if (props.initialDateTo) {
    setFilter("StartTime-date_to", props.initialDateTo, false);
  }
};

const shouldShowLocalFilters = computed(() => !props.inheritPeriodFilters);

const titleText = computed(() => props.title || SessionUser.objects.orders.meta.title);
// If the customer filter is set, filter the orders by the customer number
if (props.setCustomerFilter > 0) {
  setFilter("customer_number", props.setCustomerFilter);
  console.log("Setting customer filter to: " + props.setCustomerFilter);
}

// Hide the search field
if (props.hideSearch) {
  setHideSearchField(true);
  console.log("Hiding search field");
} else {
  setHideSearchField(false);
}

// If the departmentId is set, in the route, filter the orders by the departmentId
if (router.currentRoute.value.params.departmentId) {
  setOrder("StartTime", "desc");
  //setFilter("department", router.currentRoute.value.params.departmentId, false);
} else {
  setOrder("StartTime", "desc");
}
const isImportLoading = ref(false);

const buildImportUsageParams = () => {
  if (!props.inheritPeriodFilters) {
    return {};
  }

  return {
    ...(props.initialDateFrom ? { dateFrom: props.initialDateFrom } : {}),
    ...(props.initialDateTo ? { dateTo: props.initialDateTo } : {}),
  };
};

const importUsageButton = async () => {
  isImportLoading.value = true;
  try {
    await SessionUser.request(
        '/modules/xlvask/tasks/import-usage',
        'GET',
        buildImportUsageParams(),
        function (error) {
          // This function is called when the request fails
          console.error("Failed to import orders.", error);
        },
        function (response) {
          // This function is called when the request succeeds
          console.log("Orders imported successfully.", response);
          // Reload the list after import
          loadList();
        }
    );
  } finally {
    isImportLoading.value = false;
  }
};
const dateFrom = ref(parseInitialDate(props.initialDateFrom));
const dateTo = ref(parseInitialDate(props.initialDateTo));

const parsedDate = (date) => {
  return parseLocalDateOnly(date);
};

const reloadScheduled = ref(false);
const scheduleReload = () => {
  if (!reloadScheduled.value) {
    reloadScheduled.value = true;
    setTimeout(() => {
      reloadScheduled.value = false;
      loadList();
    }, 20);
  }
};

const actions = {
  date: {
    from: {
      select: (date) => {
        dateFrom.value = parsedDate(date);
        setFilter("StartTime-date_from", formatLocalDateOnly(date), false);
        scheduleReload();
      }
    },
    to: {
      select: (date) => {
        dateTo.value = parsedDate(date);
        setFilter("StartTime-date_to", formatLocalDateOnly(date), false);
        scheduleReload();
      }
    },
  }
};

applyInitialPeriodFilters();
// Load the list automatically if the autoLoad prop is set
if (props.autoLoad) {
  loadList();
}

watch(
  () => [props.initialDateFrom, props.initialDateTo],
  ([nextDateFrom, nextDateTo], [previousDateFrom, previousDateTo]) => {
    if (nextDateFrom === previousDateFrom && nextDateTo === previousDateTo) {
      return;
    }

    dateFrom.value = parseInitialDate(nextDateFrom);
    dateTo.value = parseInitialDate(nextDateTo);
    applyInitialPeriodFilters();

    if (props.autoLoad) {
      loadList();
    }
  }
);

const showOnlyUnattachedVehicle = ref(false);
const visibleObjectsCount = computed(() => {
  const currentList = Array.isArray(list.value) ? list.value : [];
  if (!showOnlyUnattachedVehicle.value) {
    return currentList.length;
  }

  return currentList.filter((object) => !isUsageOrderAttachedToOrder(object)).length;
});

const __returned__ = { props, t, router, paginatedList, isLoading, list, loadList, metaCurrentPage, metaItemsPerPage, metaTotalItems, setEndpoint, setMetaItemsPerPage, setPage, search, setFilter, setOrder, hideSearchField, setHideSearchField, parseInitialDate, applyInitialPeriodFilters, shouldShowLocalFilters, titleText, isImportLoading, buildImportUsageParams, importUsageButton, dateFrom, dateTo, parsedDate, reloadScheduled, scheduleReload, actions, showOnlyUnattachedVehicle, visibleObjectsCount, SessionUser, computed, provide, ref, watch, get useRouter() { return useRouter }, PaginatedListKey, usePaginatedList, PaginationNavigation, LoadButtonWhileAwait, PaginationDisplay, XlvaskUsageOrdersTable, PaginationDisplayTemplateDates, ShowErrorField, get useI18n() { return useI18n }, get BSwitch() { return Switch }, get isUsageOrderAttachedToOrder() { return isUsageOrderAttachedToOrder }, get SELFWASH_PERIOD_ALL_LIMIT() { return SELFWASH_PERIOD_ALL_LIMIT }, get formatLocalDateOnly() { return formatLocalDateOnly }, get parseLocalDateOnly() { return parseLocalDateOnly } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$v = { class: "level mb-3" };
const _hoisted_2$p = { class: "level-left" };
const _hoisted_3$n = { class: "level-item" };
const _hoisted_4$n = { class: "title is-4" };
const _hoisted_5$m = { class: "level-item" };
const _hoisted_6$m = { class: "subtitle is-6" };
const _hoisted_7$l = { class: "level-right" };
const _hoisted_8$l = { class: "level-item" };
const _hoisted_9$j = { class: "level-item" };
const _hoisted_10$i = ["placeholder"];
const _hoisted_11$e = { class: "column is-narrow my-3" };
const _hoisted_12$d = { class: "label" };
const _hoisted_13$c = { class: "control" };
const _hoisted_14$c = { class: "select" };
const _hoisted_15$c = { value: "asc" };
const _hoisted_16$c = {
  value: "desc",
  selected: ""
};
const _hoisted_17$a = { class: "column is-narrow my-3" };
const _hoisted_18$a = { class: "control" };

function _sfc_render$z(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock(Fragment, null, [
    createBaseVNode("div", _hoisted_1$v, [
      createBaseVNode("div", _hoisted_2$p, [
        createBaseVNode("div", _hoisted_3$n, [
          createBaseVNode("h1", _hoisted_4$n, toDisplayString($setup.titleText) + " (" + toDisplayString($setup.SessionUser.objects.global.language.synchronized) + ")", 1 /* TEXT */)
        ]),
        createBaseVNode("div", _hoisted_5$m, [
          createBaseVNode("h2", _hoisted_6$m, toDisplayString($setup.SessionUser.objects.global.language.showing) + " " + toDisplayString($setup.visibleObjectsCount) + " " + toDisplayString($setup.SessionUser.objects.global.language.showing_of_separator) + " " + toDisplayString($setup.metaTotalItems) + " " + toDisplayString($setup.SessionUser.objects.orders.meta.title.toLowerCase()), 1 /* TEXT */)
        ])
      ]),
      createBaseVNode("div", _hoisted_7$l, [
        createBaseVNode("div", _hoisted_8$l, [
          createVNode($setup["LoadButtonWhileAwait"], {
            class: "is-dark",
            isLoading: $setup.isImportLoading,
            loadFunction: $setup.importUsageButton,
            icon: "fas fa-file-import"
          }, {
            default: withCtx(() => [
              createTextVNode(toDisplayString($setup.SessionUser.objects.global.language.import), 1 /* TEXT */)
            ]),
            _: 1 /* STABLE */
          }, 8 /* PROPS */, ["isLoading"])
        ]),
        createBaseVNode("div", _hoisted_9$j, [
          createVNode($setup["LoadButtonWhileAwait"], {
            class: "is-dark",
            isLoading: $setup.isLoading,
            loadFunction: $setup.loadList,
            icon: "fas fa-sync-alt"
          }, {
            default: withCtx(() => [
              createTextVNode(toDisplayString($setup.SessionUser.objects.global.language.reload), 1 /* TEXT */)
            ]),
            _: 1 /* STABLE */
          }, 8 /* PROPS */, ["isLoading", "loadFunction"])
        ])
      ])
    ]),
    (!$setup.hideSearchField && $setup.shouldShowLocalFilters)
      ? (openBlock(), createElementBlock("input", {
          key: 0,
          onInput: _cache[0] || (_cache[0] = $event => ($setup.search($event.target.value))),
          class: "input",
          type: "text",
          placeholder: _ctx.$t('global.search_transactions')
        }, null, 40 /* PROPS, NEED_HYDRATION */, _hoisted_10$i))
      : createCommentVNode("v-if", true),
    ($setup.shouldShowLocalFilters)
      ? (openBlock(), createBlock($setup["PaginationDisplay"], {
          key: 1,
          metaItemsPerPage: $setup.metaItemsPerPage,
          loadFunction: $setup.loadList,
          isLoading: $setup.isLoading,
          setMetaItemsPerPage: $setup.setMetaItemsPerPage
        }, {
          paginationColumns: withCtx(() => [
            createCommentVNode(" Sort by created_at "),
            createBaseVNode("div", _hoisted_11$e, [
              createBaseVNode("label", _hoisted_12$d, toDisplayString($setup.t('pagination.order_direction')), 1 /* TEXT */),
              createBaseVNode("div", _hoisted_13$c, [
                createBaseVNode("div", _hoisted_14$c, [
                  createBaseVNode("select", {
                    onChange: _cache[1] || (_cache[1] = $event => {$setup.setOrder('created_at', $event.target.value); $setup.loadList();})
                  }, [
                    createBaseVNode("option", _hoisted_15$c, toDisplayString($setup.t('pagination.ascending')), 1 /* TEXT */),
                    createBaseVNode("option", _hoisted_16$c, toDisplayString($setup.t('pagination.descending')), 1 /* TEXT */)
                  ], 32 /* NEED_HYDRATION */)
                ])
              ])
            ]),
            createVNode($setup["PaginationDisplayTemplateDates"], {
              "end-date": $setup.dateTo,
              "start-date": $setup.dateFrom,
              "onUpdate:startDate": $setup.actions.date.from.select,
              "onUpdate:endDate": $setup.actions.date.to.select
            }, null, 8 /* PROPS */, ["end-date", "start-date", "onUpdate:startDate", "onUpdate:endDate"]),
            createBaseVNode("div", _hoisted_17$a, [
              _cache[4] || (_cache[4] = createBaseVNode("label", { class: "label" }, "Filtre", -1 /* CACHED */)),
              createBaseVNode("div", _hoisted_18$a, [
                createVNode($setup["BSwitch"], {
                  size: "is-small",
                  type: "is-link",
                  modelValue: $setup.showOnlyUnattachedVehicle,
                  "onUpdate:modelValue": _cache[2] || (_cache[2] = $event => (($setup.showOnlyUnattachedVehicle) = $event))
                }, {
                  default: withCtx(() => [...(_cache[3] || (_cache[3] = [
                    createTextVNode(" Vis kun ikke tilknyttede vaske ", -1 /* CACHED */)
                  ]))]),
                  _: 1 /* STABLE */
                }, 8 /* PROPS */, ["modelValue"])
              ])
            ]),
            createCommentVNode("\n      <PaginationDisplayTemplateDate\n          :label=\"SessionUser.objects.global.language.date_from\"\n          @update:date=\"actions.date.from.select\"\n          v-bind:model-value=\"dateFrom\"\n      />\n      <PaginationDisplayTemplateDate\n          :label=\"SessionUser.objects.global.language.date_to\"\n          @update:date=\"actions.date.to.select\"\n          v-bind:model-value=\"dateTo\"\n      />\n      ")
          ]),
          _: 1 /* STABLE */
        }, 8 /* PROPS */, ["metaItemsPerPage", "loadFunction", "isLoading", "setMetaItemsPerPage"]))
      : (openBlock(), createBlock($setup["ShowErrorField"], {
          key: 2,
          error: "paginatedGetRequest"
        })),
    createVNode($setup["XlvaskUsageOrdersTable"], {
      objects: $setup.list,
      "show-only-unattached-vehicle": $setup.showOnlyUnattachedVehicle,
      "highlight-usage-log-id": $setup.props.highlightUsageLogId
    }, null, 8 /* PROPS */, ["objects", "show-only-unattached-vehicle", "highlight-usage-log-id"]),
    (!$setup.props.loadAllAtOnce)
      ? (openBlock(), createBlock($setup["PaginationNavigation"], {
          key: 3,
          currentPage: $setup.metaCurrentPage,
          totalPages: Math.ceil($setup.metaTotalItems / $setup.metaItemsPerPage),
          loadFunction: $setup.loadList,
          setPage: $setup.setPage,
          isLoading: $setup.isLoading
        }, null, 8 /* PROPS */, ["currentPage", "totalPages", "loadFunction", "setPage", "isLoading"]))
      : createCommentVNode("v-if", true)
  ], 64 /* STABLE_FRAGMENT */))
}
const XLVaskUsagePagination = /*#__PURE__*/_export_sfc(_sfc_main$15, [['render',_sfc_render$z],['__file',"XLVaskUsagePagination.vue"]]);

const _sfc_main$14 = /* @__PURE__ */ defineComponent({
  __name: "InvoicingBillingPeriodViewSelfWash",
  setup(__props, { expose: __expose }) {
    __expose();
    const route = useRoute();
    const highlightedUsageLogId = computed(() => {
      const parsedId = Number.parseInt(String(route.query.xlvaskUsageLogId || ""), 10);
      return Number.isInteger(parsedId) && parsedId > 0 ? parsedId : 0;
    });
    const __returned__ = { route, highlightedUsageLogId, XLVaskUsagePagination, dates };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$u = { "data-testid": "invoicing-period-self-wash-view" };
function _sfc_render$y(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock("section", _hoisted_1$u, [
    createVNode($setup["XLVaskUsagePagination"], {
      title: "Selvvask",
      "initial-date-from": $setup.dates.computed.formattedStartDate.value,
      "initial-date-to": $setup.dates.computed.formattedEndDate.value,
      "inherit-period-filters": true,
      "load-all-at-once": true,
      "highlight-usage-log-id": $setup.highlightedUsageLogId
    }, null, 8, ["initial-date-from", "initial-date-to", "highlight-usage-log-id"])
  ]);
}
const InvoicingBillingPeriodViewSelfWash = /* @__PURE__ */ _export_sfc(_sfc_main$14, [["render", _sfc_render$y], ["__file", "InvoicingBillingPeriodViewSelfWash.vue"]]);

const toNumber$1 = (value) => {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : 0;
};

const sumTransactions$1 = (transactions = [], options = {}) => {
  const { bookedOnly = false, excludeExcluded = true } = options;
  return (Array.isArray(transactions) ? transactions : []).reduce((sum, transaction) => {
    if (excludeExcluded && transaction?.excluded) {
      return sum;
    }
    if (bookedOnly && !transaction?.booked) {
      return sum;
    }
    return sum + toNumber$1(transaction?.amount);
  }, 0);
};

const getCustomerNetAmount = (customer = {}, options = {}, fixedPricingCustomer = null) => {
  const settings = {
    includeFixedPricing: false,
    includeTransactions: true,
    includeVehicleSubscriptions: false,
    ...options,
  };

  if (settings.includeFixedPricing) {
    const fixedPrice = fixedPricingCustomer?.meta?.fixed_pricing?.price;
    if (fixedPrice !== undefined && fixedPrice !== null) {
      return toNumber$1(fixedPrice).toFixed(2);
    }
  }

  if (settings.includeVehicleSubscriptions) {
    // Placeholder for future vehicle-subscription specific logic.
  }

  if (settings.includeTransactions) {
    return sumTransactions$1(customer?.transactions).toFixed(2);
  }

  return "0.00";
};

const getViewTotals = (customers = []) => {
  const safeCustomers = Array.isArray(customers) ? customers : [];
  const total = safeCustomers.reduce((sum, customer) => {
    if (customer?.meta?.fixed_pricing?.price !== undefined && customer?.meta?.fixed_pricing?.price !== null) {
      return sum + toNumber$1(customer.meta.fixed_pricing.price);
    }
    return sum + sumTransactions$1(customer?.transactions);
  }, 0);

  const booked = safeCustomers.reduce((sum, customer) => {
    return sum + sumTransactions$1(customer?.transactions, { bookedOnly: true });
  }, 0);

  return {
    total,
    booked,
    notBooked: total - booked,
  };
};

const availableViews = {
  home: InvoicingBillingPeriodViewHome,
  fixed_pricing: InvoicingBillingPeriodViewAll,
  vehicle_subscriptions: InvoicingBillingPeriodViewAll,
  tank_cleaning: InvoicingBillingPeriodViewAll,
  all: InvoicingBillingPeriodViewAll,
  special_arrangements: InvoicingBillingPeriodViewAll,
  invoice_per_order: InvoicingBillingPeriodViewAll,
  possible_duplicates: InvoicingBillingPeriodViewAll,
  self_wash: InvoicingBillingPeriodViewSelfWash
  // Add more views as needed
};
const availableViewNames = ref();
const currentView = ref("home");
const sharedVariables = ref(null);
const getSharedTypes = () => sharedVariables.value?.types ?? {};
const toFiniteNumber = (value) => {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : 0;
};
const getCurrentViewBackendTotals = () => {
  const totals = sharedVariables.value?.type_totals?.[currentView.value];
  if (!totals || typeof totals !== "object") {
    return null;
  }
  return {
    total: toFiniteNumber(totals.total),
    booked: toFiniteNumber(totals.booked),
    notBooked: toFiniteNumber(totals.not_booked ?? toFiniteNumber(totals.total) - toFiniteNumber(totals.booked))
  };
};
const getCurrentViewTotals = () => {
  const backendTotals = getCurrentViewBackendTotals();
  if (backendTotals) {
    return backendTotals;
  }
  const sharedTypes = getSharedTypes();
  if (!currentView.value || !sharedTypes[currentView.value]) {
    return {
      total: 0,
      booked: 0,
      notBooked: 0
    };
  }
  return getViewTotals(sharedTypes[currentView.value]);
};
const variablesView = {
  currentView,
  availableViews,
  sharedVariables,
  availableViewNames
};
const setCurrentView = (view2) => {
  if (availableViews[view2]) {
    currentView.value = view2;
  } else {
    console.warn(`View "${view2}" does not exist in available views.`);
  }
};
const isViewAvailable = (view2) => {
  return Object.keys(availableViews).includes(view2);
};
const doesViewContainCustomer = (customer = { customer_number: Number }, targetView) => {
  return getSharedTypes()[targetView.value]?.some(
    (c) => c.customer_number === customer.customer_number
  );
};
const getViewCustomer = (customer = { customer_number: Number }, targetView) => {
  return getSharedTypes()[targetView.value]?.find(
    (c) => c.customer_number === customer.customer_number
  );
};
const addViewCustomerTransaction = (customer, transaction) => {
  const viewCustomer = getViewCustomer(customer, currentView);
  if (viewCustomer && !transaction.excluded) {
    viewCustomer.transactions.push(transaction);
  } else {
    console.warn(`Customer "${customer.customer_number}" not found in view "${currentView.value}".`);
  }
};
const updateViewCustomerTransaction = (customer, transaction) => {
  const viewCustomer = getViewCustomer(customer, currentView);
  if (viewCustomer) {
    const transactionIndex = viewCustomer.transactions.findIndex((t) => t.id === transaction.id);
    if (transactionIndex !== -1 && !transaction.excluded) {
      viewCustomer.transactions[transactionIndex] = transaction;
    } else if (transactionIndex !== -1 && transaction.excluded) {
      console.warn(`Transaction "${transaction.id}" is excluded. Removing it from view "${currentView.value}".`);
      viewCustomer.transactions.splice(transactionIndex, 1);
    } else {
      console.warn(`Transaction "${transaction.id}" not found in view "${currentView.value}". Adding it.`);
      viewCustomer.transactions.push(transaction);
    }
  } else {
    console.warn(`Customer "${customer.customer_number}" not found in view "${currentView.value}". Cannot update transaction.`);
  }
};
const getCustomerViewTotalNetAmount = (customer, options) => {
  const fixedPricingCustomer = options.includeFixedPricing ? getViewCustomer(customer, { value: "fixed_pricing" }) ?? (customer?.meta?.fixed_pricing ? customer : null) : null;
  return getCustomerNetAmount(customer, options, fixedPricingCustomer);
};
const filterExcluded = (transactions) => transactions.filter((transaction) => !transaction.excluded);
const functionsViews = {
  setCurrentView,
  isViewAvailable,
  doesViewContainCustomer,
  getCustomerViewTotalNetAmount,
  getViewCustomer,
  addViewCustomerTransaction,
  updateViewCustomerTransaction,
  filterExcluded,
  // Transaction filter function
  isCurrentView: (view2) => currentView.value === view2
  // Function to check if a view is the current view
};
const componentName = computed(() => {
  return currentView.value;
});
const isCurrentView = computed(() => {
  return (view2) => currentView.value === view2;
});
const currentViewComponent = computed(() => {
  return availableViews[currentView.value];
});
const getViewFriendlyName = (view2) => {
  if (!availableViewNames.value) {
    return view2;
  }
  const viewName = availableViewNames.value[view2];
  if (viewName) {
    return viewName;
  } else {
    console.warn(`View "${view2}" does not have a friendly name defined.`);
    return view2;
  }
};
const computedViews = {
  componentName,
  isCurrentView,
  currentViewComponent,
  currentViewTotalNetAmount: computed(() => {
    return getCurrentViewTotals().total;
  }),
  currentViewTotalNetAmountBooked: computed(() => {
    return getCurrentViewTotals().booked;
  }),
  currentViewTotalNetAmountNotBooked: computed(() => {
    return getCurrentViewTotals().notBooked;
  }),
  isLoaded: computed(() => {
    return sharedVariables.value !== void 0 && sharedVariables.value !== null;
  }),
  getViewFriendlyName
};
const view = {
  variables: variablesView,
  functions: functionsViews,
  computed: computedViews
};
const _sfc_main$13 = {
  name: "InvoicingBillingPeriodImportView",
  components: {
    InvoicingBillingPeriodViewHome
  },
  setup() {
    return {
      view
    };
  }
};

const InvoicingBillingPeriodImportView = /* @__PURE__ */ _export_sfc(_sfc_main$13, [["__file", "InvoicingBillingPeriodImportView.vue"]]);

const DRAFT_STATUS_REFRESH_INTERVAL_MS = 13e4;
const PERIOD_CACHE_WARM_DELAY_MS = 100;
const _sfc_main$12 = /* @__PURE__ */ defineComponent({
  __name: "Right",
  setup(__props, { expose: __expose }) {
    __expose();
    const period_result = ref(null);
    const route = useRoute();
    const router = useRouter();
    let draftStatusRefreshTimer = null;
    let draftStatusRefreshInFlight = false;
    let periodRequestSequence = 0;
    let hasMountedPeriodState = false;
    let isApplyingRoutePeriodState = false;
    let isApplyingRoutePeriodDates = false;
    let isSyncingRouteFromState = false;
    let lastSyncedRouteSignature = "";
    let periodCacheWarmTimers = /* @__PURE__ */ new Set();
    let isPeriodComponentUnmounted = false;
    let isCommittingPendingPeriodView = false;
    let periodDateLoadSequence = 0;
    const periodCacheRequestInFlight = /* @__PURE__ */ new Set();
    const pendingPeriodView = ref(null);
    const normalizePeriodResult = (data = {}) => ({
      ...data,
      types: data?.types ?? {},
      type_counts: data?.type_counts ?? {},
      type_totals: data?.type_totals ?? {}
    });
    const normalizeCustomerNumbers = (customerNumbers = []) => Array.from(
      new Set(
        (Array.isArray(customerNumbers) ? customerNumbers : []).map((customerNumber) => Number.parseInt(String(customerNumber), 10)).filter((customerNumber) => Number.isInteger(customerNumber) && customerNumber > 0)
      )
    );
    const serializeCustomerNumbers = (customerNumbers) => customerNumbers.join(",");
    const getCustomerNumber = (customer) => Number.parseInt(String(customer?.customer_number ?? ""), 10);
    const mergePeriodResultForCustomers = (currentPeriodResult, partialPeriodResult, customerNumbers) => {
      const normalizedCustomerNumbers = normalizeCustomerNumbers(customerNumbers);
      if (normalizedCustomerNumbers.length === 0) {
        return currentPeriodResult;
      }
      const customerNumberSet = new Set(normalizedCustomerNumbers);
      const currentTypes = currentPeriodResult?.types ?? {};
      const partialTypes = partialPeriodResult?.types ?? {};
      const nextTypes = {};
      const typeNames = Array.from(/* @__PURE__ */ new Set([
        ...Object.keys(currentTypes),
        ...Object.keys(partialTypes)
      ]));
      typeNames.forEach((typeName) => {
        const existingCustomers = Array.isArray(currentTypes[typeName]) ? currentTypes[typeName] : [];
        const partialCustomers = Array.isArray(partialTypes[typeName]) ? partialTypes[typeName] : [];
        const expandedStateByCustomerNumber = /* @__PURE__ */ new Map();
        existingCustomers.forEach((customer) => {
          const customerNumber = getCustomerNumber(customer);
          if (customerNumberSet.has(customerNumber) && customer?.expanded !== void 0) {
            expandedStateByCustomerNumber.set(customerNumber, customer.expanded === true);
          }
        });
        const incomingCustomersByCustomerNumber = /* @__PURE__ */ new Map();
        partialCustomers.filter((customer) => customerNumberSet.has(getCustomerNumber(customer))).forEach((customer) => {
          const customerNumber = getCustomerNumber(customer);
          let incomingCustomer = customer;
          if (expandedStateByCustomerNumber.has(customerNumber)) {
            incomingCustomer = {
              ...customer,
              expanded: expandedStateByCustomerNumber.get(customerNumber)
            };
          }
          incomingCustomersByCustomerNumber.set(customerNumber, incomingCustomer);
        });
        const mergedCustomers = [];
        const mergedCustomerNumbers = /* @__PURE__ */ new Set();
        existingCustomers.forEach((customer) => {
          const customerNumber = getCustomerNumber(customer);
          if (!customerNumberSet.has(customerNumber)) {
            mergedCustomers.push(customer);
            return;
          }
          if (incomingCustomersByCustomerNumber.has(customerNumber)) {
            mergedCustomers.push(incomingCustomersByCustomerNumber.get(customerNumber));
            mergedCustomerNumbers.add(customerNumber);
          }
        });
        incomingCustomersByCustomerNumber.forEach((customer, customerNumber) => {
          if (!mergedCustomerNumbers.has(customerNumber)) {
            mergedCustomers.push(customer);
          }
        });
        nextTypes[typeName] = mergedCustomers;
      });
      return normalizePeriodResult({
        ...currentPeriodResult ?? {},
        ...partialPeriodResult,
        types: nextTypes
      });
    };
    const status = reactive({
      loaded: false,
      loading: false,
      error: false,
      errorMessage: "",
      isEmpty: false
    });
    const emptySelectorCounts = () => ({
      requires_action: 0,
      draft: 0,
      manual_flags: 0,
      automatic_flags: 0,
      completed: 0,
      total: 0
    });
    const selfWashCounts = ref(emptySelectorCounts());
    let selfWashCountsRequestSequence = 0;
    const isViewActive = computed(() => (type) => {
      if (!view.variables.currentView) {
        return false;
      }
      return (pendingPeriodView.value ?? view.variables.currentView.value) === type.view;
    });
    const onClickType = (type) => {
      if (view.variables.currentView.value === type.view && pendingPeriodView.value === null) {
        return;
      }
      pendingPeriodView.value = type.view;
      const didResetPage = periodPaging.page !== 1;
      periodPaging.page = 1;
      if (!didResetPage && isPeriodTabActive.value) {
        void getPeriod();
      }
    };
    const applyRoutePeriodView = () => {
      const requestedView = String(route.query.periodView || "");
      if (requestedView && types.some((type) => type.view === requestedView && isViewAvailable.value(type))) {
        if (hasMountedPeriodState && period_result.value !== null && requestedView !== view.variables.currentView.value) {
          pendingPeriodView.value = requestedView;
          return;
        }
        view.variables.currentView.value = requestedView;
      }
    };
    const parseRouteString = (value) => Array.isArray(value) ? String(value[0] ?? "") : String(value ?? "");
    const PERIOD_FLAG_TABS = /* @__PURE__ */ new Set(["all", "red", "yellow", "none", "filters"]);
    const normalizePeriodFlagTab = (value) => {
      const tab = parseRouteString(value).trim();
      return PERIOD_FLAG_TABS.has(tab) ? tab : "all";
    };
    const parseRouteDate = (value) => {
      const routeDate = parseRouteString(value).trim();
      const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(routeDate);
      if (!match) {
        return null;
      }
      const year = Number(match[1]);
      const month = Number(match[2]);
      const day = Number(match[3]);
      const parsedDate = new Date(year, month - 1, day);
      if (parsedDate.getFullYear() !== year || parsedDate.getMonth() !== month - 1 || parsedDate.getDate() !== day) {
        return null;
      }
      return parsedDate;
    };
    const applyRoutePeriodDates = () => {
      const requestedStartDate = parseRouteDate(route.query.startDate);
      const requestedEndDate = parseRouteDate(route.query.endDate);
      const routeStartDate = parseRouteString(route.query.startDate).trim();
      const routeEndDate = parseRouteString(route.query.endDate).trim();
      if (!requestedStartDate || !requestedEndDate || requestedStartDate > requestedEndDate || typeof dates.functions?.setSelection !== "function") {
        return false;
      }
      if (dates.computed.formattedStartDate.value === routeStartDate && dates.computed.formattedEndDate.value === routeEndDate) {
        return false;
      }
      isApplyingRoutePeriodDates = true;
      try {
        dates.functions.setSelection(requestedStartDate, requestedEndDate);
      } finally {
        queueMicrotask(() => {
          isApplyingRoutePeriodDates = false;
        });
      }
      return true;
    };
    const getPeriodRouteSignature = (query) => JSON.stringify({
      startDate: parseRouteString(query.startDate),
      endDate: parseRouteString(query.endDate),
      periodView: parseRouteString(query.periodView),
      periodSearch: parseRouteString(query.periodSearch),
      periodPage: parseRouteString(query.periodPage),
      periodLimit: parseRouteString(query.periodLimit),
      periodFlagTab: normalizePeriodFlagTab(query.periodFlagTab)
    });
    const applyRoutePeriodPaging = () => {
      isApplyingRoutePeriodState = true;
      try {
        const requestedSearch = parseRouteString(route.query.periodSearch).trim();
        periodPaging.search = requestedSearch;
        periodPaging.page = normalizePeriodPage(route.query.periodPage ?? 1);
        periodPaging.limit = normalizePeriodLimit(route.query.periodLimit ?? periodPaging.limit);
        periodPaging.flagTab = normalizePeriodFlagTab(route.query.periodFlagTab ?? periodPaging.flagTab);
      } finally {
        queueMicrotask(() => {
          isApplyingRoutePeriodState = false;
        });
      }
    };
    const getBackendPeriodView = (periodView = null) => {
      const currentView = String(periodView || view.variables.currentView?.value || "");
      if (currentView === "self_wash") {
        return "all";
      }
      return types.some((type) => type.view === currentView && type.name !== "self_wash") ? currentView : "all";
    };
    const syncPeriodRouteQuery = () => {
      if (!isPeriodTabActive.value || isApplyingRoutePeriodState) {
        return;
      }
      const nextQuery = {
        ...route.query,
        activeTab: "period",
        startDate: dates.computed.formattedStartDate.value,
        endDate: dates.computed.formattedEndDate.value,
        periodView: pendingPeriodView.value ?? view.variables.currentView.value,
        periodPage: String(periodPaging.page),
        periodLimit: String(periodPaging.limit),
        periodFlagTab: normalizePeriodFlagTab(periodPaging.flagTab)
      };
      if (periodPaging.search.trim() !== "") {
        nextQuery.periodSearch = periodPaging.search.trim();
      } else {
        delete nextQuery.periodSearch;
      }
      lastSyncedRouteSignature = getPeriodRouteSignature(nextQuery);
      isSyncingRouteFromState = true;
      void router.replace({ query: nextQuery }).catch(() => {
      }).finally(() => {
        isSyncingRouteFromState = false;
      });
    };
    const types = [
      {
        name: "all",
        displayName: SessionUser.objects.global.language.all,
        description: "Alle kunder.",
        view: "all",
        isAvailable: computed(() => true)
      },
      {
        name: "invoice_per_order",
        displayName: SessionUser.objects.global.language.invoice_per_order,
        description: "Kunder med fakturering pr. ordre.",
        view: "invoice_per_order",
        isAvailable: computed(() => true)
      },
      {
        name: "fixed_pricing",
        displayName: SessionUser.objects.global.language.fixed_price_arrangements,
        description: "Kunder med fastprisaftaler.",
        view: "fixed_pricing",
        isAvailable: computed(() => {
          return dates.computed.isEntireMonth.value;
        })
      },
      {
        name: "tank_cleaning",
        displayName: SessionUser.objects.global.language.only_tank_cleaning,
        description: "Kunder med tankcleaning.",
        view: "tank_cleaning",
        isAvailable: computed(() => true)
      },
      {
        name: "special_arrangements",
        displayName: SessionUser.objects.global.language.special_arrangements,
        description: "Kunder med specialaftaler.",
        view: "special_arrangements",
        isAvailable: computed(() => true)
      },
      {
        name: "vehicle_subscriptions",
        displayName: SessionUser.objects.vehicles.columns.wash_subscription.label,
        description: "Kunder med aktive vaskeabonnementer.",
        view: "vehicle_subscriptions",
        // dates.computed.isEntireMonth.value
        isAvailable: computed(() => {
          return dates.computed.isEntireMonth.value;
        })
      },
      {
        name: "possible_duplicates",
        displayName: SessionUser.objects.global.language.possible_duplicates,
        description: "Kunder med mulige dubletter.",
        view: "possible_duplicates",
        isAvailable: computed(() => true)
      },
      {
        name: "self_wash",
        displayName: "Selvvask",
        description: "Import og tilknytning af selvvaske.",
        view: "self_wash",
        iconClass: "fas fa-link",
        isAvailable: computed(() => true)
      }
    ];
    const buildSelfWashPeriodFilters = () => [
      `StartTime-date_from:${dates.computed.formattedStartDate.value}`,
      `StartTime-date_to:${dates.computed.formattedEndDate.value}`
    ].join(",");
    const loadSelfWashCounts = async ({ forceRefresh = false } = {}) => {
      const requestSequence = ++selfWashCountsRequestSequence;
      const dateFrom = dates.computed.formattedStartDate.value;
      const dateTo = dates.computed.formattedEndDate.value;
      const filters = buildSelfWashPeriodFilters();
      const cacheKey = buildSelfWashCountsCacheKey({ dateFrom, dateTo, filters });
      const cachedCounts = forceRefresh ? null : getCachedSelfWashCounts(cacheKey);
      if (cachedCounts) {
        selfWashCounts.value = {
          ...emptySelectorCounts(),
          ...cachedCounts
        };
        return;
      }
      selfWashCounts.value = emptySelectorCounts();
      try {
        const response = await SessionUser.request(
          "/modules/xlvask/services/usage/orders",
          "GET",
          {
            page: 1,
            limit: SELFWASH_PERIOD_ALL_LIMIT,
            filters,
            order: "StartTime:desc"
          }
        );
        if (requestSequence !== selfWashCountsRequestSequence || dateFrom !== dates.computed.formattedStartDate.value || dateTo !== dates.computed.formattedEndDate.value) {
          return;
        }
        const rows = Array.isArray(response?.data?.data) ? response.data.data : [];
        const total = Number(response?.data?.meta?.pagination?.total ?? rows.length);
        const completed = Math.min(total, rows.filter((row) => isUsageOrderAttachedToOrder(row)).length);
        const nextCounts = {
          ...emptySelectorCounts(),
          total,
          completed,
          requires_action: Math.max(0, total - completed)
        };
        selfWashCounts.value = nextCounts;
        setCachedSelfWashCounts(cacheKey, nextCounts);
      } catch {
        if (requestSequence === selfWashCountsRequestSequence) {
          selfWashCounts.value = emptySelectorCounts();
        }
      }
    };
    const getPeriodRequestParameters = () => ({
      dateFrom: dates.computed.formattedStartDate.value,
      dateTo: dates.computed.formattedEndDate.value,
      periodView: getBackendPeriodView(pendingPeriodView.value),
      page: periodPaging.page,
      limit: periodPaging.limit,
      search: periodPaging.search.trim(),
      flagTab: normalizePeriodFlagTab(periodPaging.flagTab),
      includeRequiresAction: periodPaging.includeRequiresAction ? 1 : 0,
      includeBooked: periodPaging.includeBooked ? 1 : 0
    });
    const buildFallbackPaginationMeta = (requestParameters, periodResult = {}) => ({
      page: normalizePeriodPage(requestParameters.page ?? 1),
      per_page: normalizePeriodLimit(requestParameters.limit ?? periodPaging.limit),
      total: periodResult?.types?.[requestParameters.periodView]?.length ?? 0,
      search: String(requestParameters.search ?? ""),
      filters: {
        includeRequiresAction: Boolean(Number(requestParameters.includeRequiresAction ?? 1)),
        includeBooked: Boolean(Number(requestParameters.includeBooked ?? 1))
      },
      order: null
    });
    const schedulePeriodCacheWarm = (callback) => {
      if (isPeriodComponentUnmounted) {
        return;
      }
      const timer = setTimeout(() => {
        periodCacheWarmTimers.delete(timer);
        if (isPeriodComponentUnmounted) {
          return;
        }
        void callback();
      }, PERIOD_CACHE_WARM_DELAY_MS);
      periodCacheWarmTimers.add(timer);
    };
    const clearPeriodCacheWarmTimers = () => {
      periodCacheWarmTimers.forEach((timer) => clearTimeout(timer));
      periodCacheWarmTimers.clear();
    };
    const fetchAndCachePeriodPage = async (requestParameters) => {
      const cacheKey = buildPeriodCacheKey(requestParameters);
      if (getCachedPeriodPage(cacheKey) || periodCacheRequestInFlight.has(cacheKey)) {
        return;
      }
      periodCacheRequestInFlight.add(cacheKey);
      try {
        const response = await SessionUser.request(
          "/superuser/invoicing/period",
          "GET",
          requestParameters
        );
        const normalizedPeriodResult = normalizePeriodResult(response?.data?.data);
        const paginationMeta = response?.data?.meta?.pagination ?? buildFallbackPaginationMeta(requestParameters, normalizedPeriodResult);
        setCachedPeriodPage(cacheKey, normalizedPeriodResult, paginationMeta);
      } catch {
      } finally {
        periodCacheRequestInFlight.delete(cacheKey);
      }
    };
    const getPaginationPageCount = (paginationMeta) => {
      const perPageValue = normalizePeriodLimit(paginationMeta?.per_page ?? periodPaging.limit);
      if (perPageValue === "all") {
        return 1;
      }
      const total = Math.max(0, Number.parseInt(String(paginationMeta?.total ?? 0), 10) || 0);
      return Math.max(1, Math.ceil(total / Math.max(1, Number(perPageValue))));
    };
    const preloadAdjacentPeriodPages = (requestParameters, paginationMeta) => {
      if (normalizePeriodLimit(requestParameters.limit) === "all") {
        return;
      }
      const page = normalizePeriodPage(paginationMeta?.page ?? requestParameters.page);
      const pageCount = getPaginationPageCount(paginationMeta);
      [page - 1, page + 1].filter((nextPage, index, pages) => nextPage >= 1 && nextPage <= pageCount && pages.indexOf(nextPage) === index).forEach((nextPage) => {
        schedulePeriodCacheWarm(() => fetchAndCachePeriodPage({
          ...requestParameters,
          page: nextPage,
          periodWarm: 1
        }));
      });
    };
    const formatLocalDate = (date) => [
      date.getFullYear(),
      String(date.getMonth() + 1).padStart(2, "0"),
      String(date.getDate()).padStart(2, "0")
    ].join("-");
    const getMonthDateRange = (date) => {
      const start = new Date(date.getFullYear(), date.getMonth(), 1);
      const end = new Date(date.getFullYear(), date.getMonth() + 1, 0);
      return {
        dateFrom: formatLocalDate(start),
        dateTo: formatLocalDate(end)
      };
    };
    const warmCurrentAndPreviousPeriodMonths = () => {
      const now = /* @__PURE__ */ new Date();
      const previousMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      const monthRanges = [getMonthDateRange(now), getMonthDateRange(previousMonth)];
      const periodViews = Array.from(/* @__PURE__ */ new Set(["all", getBackendPeriodView()]));
      const warmLimit = normalizePeriodLimit(periodPaging.limit) === "all" ? 100 : periodPaging.limit;
      monthRanges.forEach((dateRange) => {
        periodViews.forEach((periodView) => {
          schedulePeriodCacheWarm(() => fetchAndCachePeriodPage({
            ...dateRange,
            periodView,
            page: 1,
            limit: warmLimit,
            search: "",
            includeRequiresAction: periodPaging.includeRequiresAction ? 1 : 0,
            includeBooked: periodPaging.includeBooked ? 1 : 0,
            periodWarm: 1
          }));
        });
      });
    };
    const applyPeriodResult = (periodResult, paginationMeta, {
      fromCache = false,
      cacheUpdatedAt = null,
      periodView = null
    } = {}) => {
      const viewToCommit = periodView ?? pendingPeriodView.value;
      let didCommitView = false;
      if (viewToCommit !== null && viewToCommit !== view.variables.currentView.value) {
        didCommitView = true;
        isCommittingPendingPeriodView = true;
        view.variables.currentView.value = viewToCommit;
        queueMicrotask(() => {
          isCommittingPendingPeriodView = false;
          if (didCommitView && isPeriodTabActive.value) {
            syncPeriodRouteQuery();
          }
        });
      }
      if (viewToCommit !== null && pendingPeriodView.value === viewToCommit) {
        pendingPeriodView.value = null;
      }
      const normalizedPeriodResult = normalizePeriodResult(periodResult);
      view.variables.sharedVariables.value = normalizedPeriodResult;
      period_result.value = normalizedPeriodResult;
      setPeriodPagingMeta(paginationMeta, normalizedPeriodResult.type_counts || {});
      periodPaging.isFromCache = fromCache;
      periodPaging.cacheUpdatedAt = cacheUpdatedAt;
      status.loaded = true;
      status.isEmpty = Number(periodPaging.meta?.total ?? 0) === 0;
    };
    const getPeriod = async ({ forceRefresh = false, showLoading = false } = {}) => {
      const requestParameters = getPeriodRequestParameters();
      const cacheKey = buildPeriodCacheKey(requestParameters);
      const cachedPage = forceRefresh ? null : getCachedPeriodPage(cacheKey);
      const requestSequence = ++periodRequestSequence;
      const requestedView = pendingPeriodView.value;
      periodCacheRequestInFlight.add(cacheKey);
      status.error = false;
      status.errorMessage = "";
      void loadSelfWashCounts({ forceRefresh });
      if (cachedPage) {
        applyPeriodResult(cachedPage.data, cachedPage.pagination, {
          fromCache: true,
          cacheUpdatedAt: cachedPage.storedAt,
          periodView: requestedView
        });
        status.loading = false;
        periodPaging.isRefreshing = true;
        preloadAdjacentPeriodPages(requestParameters, cachedPage.pagination);
      } else if (period_result.value !== null) {
        status.loading = showLoading;
        status.loaded = true;
        status.isEmpty = false;
        periodPaging.isRefreshing = true;
        periodPaging.isFromCache = false;
        periodPaging.cacheUpdatedAt = null;
      } else {
        view.variables.sharedVariables.value = null;
        period_result.value = null;
        status.loading = true;
        status.loaded = false;
        status.isEmpty = false;
        periodPaging.isRefreshing = false;
        periodPaging.isFromCache = false;
        periodPaging.cacheUpdatedAt = null;
      }
      try {
        const response = await SessionUser.request(
          "/superuser/invoicing/period",
          "GET",
          requestParameters
        );
        if (requestSequence !== periodRequestSequence || cacheKey !== buildPeriodCacheKey(getPeriodRequestParameters())) {
          return;
        }
        const normalizedPeriodResult = normalizePeriodResult(response?.data?.data);
        const paginationMeta = response?.data?.meta?.pagination ?? {
          page: periodPaging.page,
          per_page: periodPaging.limit,
          total: normalizedPeriodResult?.types?.[requestParameters.periodView]?.length ?? 0,
          search: requestParameters.search,
          filters: {
            includeRequiresAction: periodPaging.includeRequiresAction,
            includeBooked: periodPaging.includeBooked
          },
          order: null
        };
        applyPeriodResult(normalizedPeriodResult, paginationMeta, {
          fromCache: false,
          cacheUpdatedAt: null,
          periodView: requestedView
        });
        setCachedPeriodPage(cacheKey, normalizedPeriodResult, paginationMeta);
        preloadAdjacentPeriodPages(requestParameters, paginationMeta);
      } catch (error) {
        if (requestSequence !== periodRequestSequence || cacheKey !== buildPeriodCacheKey(getPeriodRequestParameters())) {
          return;
        }
        if (requestedView !== null && pendingPeriodView.value === requestedView) {
          pendingPeriodView.value = null;
          queueMicrotask(() => {
            syncPeriodRouteQuery();
          });
        }
        status.error = true;
        status.errorMessage = error?.message || "Unknown error";
      } finally {
        periodCacheRequestInFlight.delete(cacheKey);
        if (requestSequence === periodRequestSequence) {
          status.loading = false;
          periodPaging.isRefreshing = false;
        }
        if (!isPeriodComponentUnmounted) {
          warmCurrentAndPreviousPeriodMonths();
        }
      }
    };
    const refreshPeriodCustomers = async (customerNumbers, invoiceCollectionIds = []) => {
      const normalizedCustomerNumbers = normalizeCustomerNumbers(customerNumbers);
      if (normalizedCustomerNumbers.length === 0) {
        invoiceQueue.finishPeriodRefresh?.(customerNumbers, invoiceCollectionIds);
        return;
      }
      const dateFrom = dates.computed.formattedStartDate.value;
      const dateTo = dates.computed.formattedEndDate.value;
      try {
        const response = await SessionUser.request(
          "/superuser/invoicing/period",
          "GET",
          {
            dateFrom,
            dateTo,
            customerNumbers: serializeCustomerNumbers(normalizedCustomerNumbers)
          }
        );
        if (dateFrom !== dates.computed.formattedStartDate.value || dateTo !== dates.computed.formattedEndDate.value) {
          return;
        }
        const normalizedPeriodResult = normalizePeriodResult(response?.data?.data);
        const mergedPeriodResult = mergePeriodResultForCustomers(
          period_result.value,
          normalizedPeriodResult,
          normalizedCustomerNumbers
        );
        view.variables.sharedVariables.value = mergedPeriodResult;
        period_result.value = mergedPeriodResult;
        status.loaded = true;
        status.isEmpty = Object.keys(period_result.value?.types || {}).length === 0;
      } catch (error) {
        status.error = true;
        status.errorMessage = error?.message || "Unknown error";
      } finally {
        invoiceQueue.finishPeriodRefresh?.(normalizedCustomerNumbers, invoiceCollectionIds);
      }
    };
    const reloadCurrentPeriodPageForRefresh = async (customerNumbers = [], invoiceCollectionIds = []) => {
      const normalizedCustomerNumbers = normalizeCustomerNumbers(customerNumbers);
      clearPeriodCache();
      try {
        await getPeriod({ forceRefresh: true });
      } finally {
        invoiceQueue.finishPeriodRefresh?.(normalizedCustomerNumbers, invoiceCollectionIds);
      }
    };
    const isLoading = computed(() => {
      return period_result.value === null || status.loading;
    });
    const getCountEntriesForType = (typeName) => {
      const entries = period_result.value?.types?.[typeName] || [];
      if (typeName !== "possible_duplicates") {
        return entries;
      }
      return buildPossibleDuplicateGroups(entries);
    };
    const isActiveFlag = (flag) => String(flag?.status || "active") === "active";
    const getActiveFlagCounts = (entry) => {
      const flags = Array.isArray(entry?.flags) ? entry.flags.filter((flag) => isActiveFlag(flag)) : null;
      if (flags !== null) {
        const manual = flags.filter((flag) => flag?.source === "manual").length;
        const automatic = flags.filter((flag) => flag?.source === "automatic").length;
        return {
          manual,
          automatic,
          total: manual + automatic
        };
      }
      return {
        manual: Number(entry?.flag_counts?.manual ?? 0),
        automatic: Number(entry?.flag_counts?.automatic ?? 0),
        total: Number(entry?.flag_counts?.total ?? 0)
      };
    };
    const counts = computed(() => (type) => {
      if (type.name === "self_wash") {
        return selfWashCounts.value;
      }
      if (!period_result.value) {
        return emptySelectorCounts();
      }
      const backendCounts = period_result.value?.type_counts?.[type.name] ?? periodPaging.typeCounts?.[type.name];
      if (backendCounts) {
        return {
          ...emptySelectorCounts(),
          ...backendCounts
        };
      }
      const entries = getCountEntriesForType(type.name);
      const requires_action = entries.filter((entry) => entry.requires_action).length;
      const draft = entries.filter((entry) => isCustomerDraftBlocked(entry)).length;
      const manual_flags = entries.filter((entry) => getActiveFlagCounts(entry).manual > 0).length;
      const automatic_flags = entries.filter((entry) => getActiveFlagCounts(entry).automatic > 0).length;
      const completed = Math.max(0, entries.length - requires_action - draft);
      return {
        total: entries.length,
        requires_action,
        draft,
        manual_flags,
        automatic_flags,
        completed
      };
    });
    const isCustomerDraftBlocked = (customer) => {
      return customer?.draft?.is_action_blocked === true;
    };
    const getSelectorStatusClass = (type) => {
      if (!isViewAvailable.value(type)) {
        return "has-text-grey";
      }
      const typeCounts = counts.value(type);
      if (typeCounts.manual_flags > 0) {
        return "has-text-danger";
      }
      if (typeCounts.automatic_flags > 0) {
        return "has-text-warning";
      }
      if (typeCounts.requires_action > 0) {
        return "has-text-danger";
      }
      if (typeCounts.draft > 0) {
        return "has-text-warning";
      }
      return "has-text-success";
    };
    const getSelectorIconClass = (type) => {
      if (type.iconClass) {
        return type.iconClass;
      }
      const typeCounts = counts.value(type);
      if (typeCounts.manual_flags > 0 || typeCounts.automatic_flags > 0) {
        return "fas fa-flag";
      }
      return "fas fa-circle";
    };
    const getProgressWidth = (count, total) => {
      if (total < 1) {
        return 0;
      }
      return Math.max(0, Math.min(100, count / total * 100));
    };
    const selectorProgressStyle = computed(() => (type) => {
      const typeCounts = counts.value(type);
      const completedWidth = getProgressWidth(typeCounts.completed, typeCounts.total);
      const draftWidth = getProgressWidth(typeCounts.draft, typeCounts.total);
      return {
        "--completed-width": `${completedWidth}%`,
        "--draft-left": `${completedWidth}%`,
        "--draft-width": `${draftWidth}%`
      };
    });
    const isViewAvailable = computed(() => (type) => {
      return type.isAvailable ? type.isAvailable.value : true;
    });
    const shouldShowSelectorCounts = (_type) => true;
    const shouldShowSelectorProgress = (_type) => true;
    const getSelectorLabelText = (type) => {
      if (!isViewAvailable.value(type) || !shouldShowSelectorCounts(type)) {
        return type.displayName;
      }
      const typeCounts = counts.value(type);
      return `${type.displayName} (${typeCounts.completed}/${typeCounts.total})`;
    };
    const isPeriodTabActive = computed(() => route.query.activeTab === "period");
    const getVisiblePeriodCustomerNumbers = () => {
      const currentViewName = view.variables.currentView?.value;
      const customers = currentViewName ? period_result.value?.types?.[currentViewName] : [];
      if (!Array.isArray(customers)) {
        return [];
      }
      return normalizeCustomerNumbers(customers.map((customer) => getCustomerNumber(customer)));
    };
    const refreshVisiblePeriodCustomers = async () => {
      if (!isPeriodTabActive.value || status.loading || draftStatusRefreshInFlight) {
        return;
      }
      const customerNumbers = getVisiblePeriodCustomerNumbers();
      if (customerNumbers.length === 0) {
        return;
      }
      draftStatusRefreshInFlight = true;
      try {
        await reloadCurrentPeriodPageForRefresh(customerNumbers);
      } finally {
        draftStatusRefreshInFlight = false;
      }
    };
    const startDraftStatusRefreshTimer = () => {
      if (draftStatusRefreshTimer !== null || !isPeriodTabActive.value) {
        return;
      }
      draftStatusRefreshTimer = setInterval(() => {
        void refreshVisiblePeriodCustomers();
      }, DRAFT_STATUS_REFRESH_INTERVAL_MS);
    };
    const stopDraftStatusRefreshTimer = () => {
      if (draftStatusRefreshTimer === null) {
        return;
      }
      clearInterval(draftStatusRefreshTimer);
      draftStatusRefreshTimer = null;
    };
    const syncDraftStatusRefreshTimer = () => {
      if (isPeriodTabActive.value) {
        startDraftStatusRefreshTimer();
        return;
      }
      stopDraftStatusRefreshTimer();
    };
    const handleSelfWashUsageOrderUpdated = () => {
      clearSelfWashCountsCache();
      if (isPeriodTabActive.value) {
        void loadSelfWashCounts({ forceRefresh: true });
      }
    };
    const loadPeriodForDateChange = () => {
      const loadSequence = ++periodDateLoadSequence;
      clearPeriodCache();
      periodPaging.page = 1;
      periodPaging.isDateLoading = true;
      void getPeriod({ forceRefresh: true, showLoading: true }).finally(() => {
        if (loadSequence === periodDateLoadSequence) {
          periodPaging.isDateLoading = false;
        }
      });
    };
    onMounted(() => {
      isPeriodComponentUnmounted = false;
      view.variables.availableViewNames.value = types.reduce((acc, type) => {
        acc[type.name] = type.displayName;
        return acc;
      }, {});
      applyRoutePeriodDates();
      applyRoutePeriodView();
      applyRoutePeriodPaging();
      hasMountedPeriodState = true;
      queueMicrotask(() => {
        syncPeriodRouteQuery();
      });
      getPeriod();
      syncDraftStatusRefreshTimer();
      window.addEventListener("xlvask-usage-order-updated", handleSelfWashUsageOrderUpdated);
    });
    onUnmounted(() => {
      isPeriodComponentUnmounted = true;
      clearPeriodCacheWarmTimers();
      stopDraftStatusRefreshTimer();
      periodPaging.isDateLoading = false;
      window.removeEventListener("xlvask-usage-order-updated", handleSelfWashUsageOrderUpdated);
    });
    watch(
      [() => dates.variables.start.value, () => dates.variables.end.value],
      () => {
        if (isApplyingRoutePeriodDates) {
          return;
        }
        loadPeriodForDateChange();
      }
    );
    watch(
      () => route.query.activeTab,
      (newTab, oldTab) => {
        if (newTab === "period" && oldTab !== "period") {
          getPeriod();
        }
        syncDraftStatusRefreshTimer();
      }
    );
    watch(
      () => [
        route.query.startDate,
        route.query.endDate,
        route.query.periodView,
        route.query.periodSearch,
        route.query.periodPage,
        route.query.periodLimit,
        route.query.periodFlagTab
      ],
      () => {
        const routeSignature = getPeriodRouteSignature(route.query);
        applyRoutePeriodDates();
        applyRoutePeriodView();
        applyRoutePeriodPaging();
        if (isSyncingRouteFromState || routeSignature === lastSyncedRouteSignature) {
          if (routeSignature === lastSyncedRouteSignature) {
            lastSyncedRouteSignature = "";
          }
          return;
        }
        if (hasMountedPeriodState && isPeriodTabActive.value) {
          getPeriod();
        }
      }
    );
    watch(
      () => [
        view.variables.currentView.value,
        periodPaging.page,
        periodPaging.limit,
        periodPaging.search,
        periodPaging.flagTab,
        periodPaging.includeRequiresAction,
        periodPaging.includeBooked
      ],
      () => {
        if (!hasMountedPeriodState || isApplyingRoutePeriodState || isCommittingPendingPeriodView) {
          return;
        }
        syncPeriodRouteQuery();
        if (isPeriodTabActive.value) {
          getPeriod();
        }
      }
    );
    watch(
      () => periodPaging.reloadSequence,
      () => {
        if (!hasMountedPeriodState || !isPeriodTabActive.value) {
          return;
        }
        clearPeriodCache();
        getPeriod({ forceRefresh: true });
      }
    );
    watch(
      () => invoiceQueue.periodRefreshSignal.value,
      (nextSignal, previousSignal) => {
        if (nextSignal?.sequence === previousSignal?.sequence) {
          return;
        }
        if (!isPeriodTabActive.value) {
          return;
        }
        void reloadCurrentPeriodPageForRefresh(
          normalizeCustomerNumbers(nextSignal?.customerNumbers ?? []),
          normalizeCustomerNumbers(nextSignal?.invoiceCollectionIds ?? [])
        );
      }
    );
    const __returned__ = { period_result, route, router, DRAFT_STATUS_REFRESH_INTERVAL_MS, get draftStatusRefreshTimer() {
      return draftStatusRefreshTimer;
    }, set draftStatusRefreshTimer(v) {
      draftStatusRefreshTimer = v;
    }, get draftStatusRefreshInFlight() {
      return draftStatusRefreshInFlight;
    }, set draftStatusRefreshInFlight(v) {
      draftStatusRefreshInFlight = v;
    }, get periodRequestSequence() {
      return periodRequestSequence;
    }, set periodRequestSequence(v) {
      periodRequestSequence = v;
    }, get hasMountedPeriodState() {
      return hasMountedPeriodState;
    }, set hasMountedPeriodState(v) {
      hasMountedPeriodState = v;
    }, get isApplyingRoutePeriodState() {
      return isApplyingRoutePeriodState;
    }, set isApplyingRoutePeriodState(v) {
      isApplyingRoutePeriodState = v;
    }, get isApplyingRoutePeriodDates() {
      return isApplyingRoutePeriodDates;
    }, set isApplyingRoutePeriodDates(v) {
      isApplyingRoutePeriodDates = v;
    }, get isSyncingRouteFromState() {
      return isSyncingRouteFromState;
    }, set isSyncingRouteFromState(v) {
      isSyncingRouteFromState = v;
    }, get lastSyncedRouteSignature() {
      return lastSyncedRouteSignature;
    }, set lastSyncedRouteSignature(v) {
      lastSyncedRouteSignature = v;
    }, get periodCacheWarmTimers() {
      return periodCacheWarmTimers;
    }, set periodCacheWarmTimers(v) {
      periodCacheWarmTimers = v;
    }, get isPeriodComponentUnmounted() {
      return isPeriodComponentUnmounted;
    }, set isPeriodComponentUnmounted(v) {
      isPeriodComponentUnmounted = v;
    }, get isCommittingPendingPeriodView() {
      return isCommittingPendingPeriodView;
    }, set isCommittingPendingPeriodView(v) {
      isCommittingPendingPeriodView = v;
    }, get periodDateLoadSequence() {
      return periodDateLoadSequence;
    }, set periodDateLoadSequence(v) {
      periodDateLoadSequence = v;
    }, periodCacheRequestInFlight, PERIOD_CACHE_WARM_DELAY_MS, pendingPeriodView, normalizePeriodResult, normalizeCustomerNumbers, serializeCustomerNumbers, getCustomerNumber, mergePeriodResultForCustomers, status, emptySelectorCounts, selfWashCounts, get selfWashCountsRequestSequence() {
      return selfWashCountsRequestSequence;
    }, set selfWashCountsRequestSequence(v) {
      selfWashCountsRequestSequence = v;
    }, isViewActive, onClickType, applyRoutePeriodView, parseRouteString, PERIOD_FLAG_TABS, normalizePeriodFlagTab, parseRouteDate, applyRoutePeriodDates, getPeriodRouteSignature, applyRoutePeriodPaging, getBackendPeriodView, syncPeriodRouteQuery, types, buildSelfWashPeriodFilters, loadSelfWashCounts, getPeriodRequestParameters, buildFallbackPaginationMeta, schedulePeriodCacheWarm, clearPeriodCacheWarmTimers, fetchAndCachePeriodPage, getPaginationPageCount, preloadAdjacentPeriodPages, formatLocalDate, getMonthDateRange, warmCurrentAndPreviousPeriodMonths, applyPeriodResult, getPeriod, refreshPeriodCustomers, reloadCurrentPeriodPageForRefresh, isLoading, getCountEntriesForType, isActiveFlag, getActiveFlagCounts, counts, isCustomerDraftBlocked, getSelectorStatusClass, getSelectorIconClass, getProgressWidth, selectorProgressStyle, isViewAvailable, shouldShowSelectorCounts, shouldShowSelectorProgress, getSelectorLabelText, isPeriodTabActive, getVisiblePeriodCustomerNumbers, refreshVisiblePeriodCustomers, startDraftStatusRefreshTimer, stopDraftStatusRefreshTimer, syncDraftStatusRefreshTimer, handleSelfWashUsageOrderUpdated, loadPeriodForDateChange, WhiteBox, ColorIndicator };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$t = {
  class: "columns is-multiline is-mobile",
  "data-testid": "invoicing-period-view-selectors"
};
const _hoisted_2$o = { class: "level is-mobile is-align-items-center" };
const _hoisted_3$m = { class: "level-left" };
const _hoisted_4$m = { class: "level-item" };
const _hoisted_5$l = { class: "level-right" };
const _hoisted_6$l = {
  class: "level-item",
  style: { "width": "100px" }
};
const _hoisted_7$k = {
  key: 0,
  class: "progress is-small",
  max: 1
};
const _hoisted_8$k = ["data-testid"];
const _hoisted_9$i = ["data-testid"];
const _hoisted_10$h = {
  key: 2,
  class: "progress",
  value: 0,
  max: 1
};
function _sfc_render$x(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock("div", _hoisted_1$t, [
    createCommentVNode('\n    <div class="column is-12">\n      <h1 class="title is-3">Dashboard Right Display</h1>\n      <button class="button is-primary" @click="getPeriod">Fetch Period Data</button>\n    </div>\n    '),
    (openBlock(), createElementBlock(
      Fragment,
      null,
      renderList($setup.types, (type) => {
        return createBaseVNode("div", {
          key: type.name,
          class: "column is-12 p-1"
        }, [
          createVNode($setup["WhiteBox"], {
            class: normalizeClass(["is-selector-view", {
              "is-selected-view": $setup.isViewActive(type),
              "is-clickable": $setup.isViewAvailable(type)
            }]),
            "data-testid": `invoicing-period-view-selector-${type.name}`,
            onClick: ($event) => $setup.isViewAvailable(type) ? $setup.onClickType(type) : () => {
            }
          }, {
            default: withCtx(() => [
              createBaseVNode("div", _hoisted_2$o, [
                createBaseVNode("div", _hoisted_3$m, [
                  createBaseVNode("div", _hoisted_4$m, [
                    createVNode($setup["ColorIndicator"], {
                      label: {
                        text: $setup.getSelectorLabelText(type),
                        classes: []
                      },
                      color_class: $setup.getSelectorStatusClass(type),
                      icon_class: $setup.getSelectorIconClass(type),
                      visibility: {
                        icon: true,
                        dropdown: false
                      },
                      is_loading: $setup.isLoading
                    }, null, 8, ["label", "color_class", "icon_class", "is_loading"])
                  ])
                ]),
                createBaseVNode("div", _hoisted_5$l, [
                  createBaseVNode("div", _hoisted_6$l, [
                    $setup.isLoading ? (openBlock(), createElementBlock("progress", _hoisted_7$k)) : $setup.isViewAvailable(type) && $setup.shouldShowSelectorProgress(type) ? (openBlock(), createElementBlock("div", {
                      key: 1,
                      class: "period-selector-progress",
                      style: normalizeStyle($setup.selectorProgressStyle(type)),
                      "data-testid": `invoicing-period-view-selector-progress-${type.name}`
                    }, [
                      _cache[0] || (_cache[0] = createBaseVNode(
                        "span",
                        { class: "period-selector-progress__completed" },
                        null,
                        -1
                        /* CACHED */
                      )),
                      createBaseVNode("span", {
                        class: "period-selector-progress__draft",
                        "data-testid": `invoicing-period-view-selector-progress-draft-${type.name}`
                      }, null, 8, _hoisted_9$i)
                    ], 12, _hoisted_8$k)) : !$setup.isViewAvailable(type) ? (openBlock(), createElementBlock("progress", _hoisted_10$h)) : createCommentVNode("v-if", true)
                  ]),
                  _cache[1] || (_cache[1] = createBaseVNode(
                    "div",
                    { class: "level-item" },
                    [
                      createBaseVNode("span", { class: "icon is-small" }, [
                        createBaseVNode("i", { class: "fas fa-chevron-right" })
                      ])
                    ],
                    -1
                    /* CACHED */
                  ))
                ])
              ])
            ]),
            _: 2
            /* DYNAMIC */
          }, 1032, ["data-testid", "class", "onClick"])
        ]);
      }),
      64
      /* STABLE_FRAGMENT */
    ))
  ]);
}
const Right = /* @__PURE__ */ _export_sfc(_sfc_main$12, [["render", _sfc_render$x], ["__scopeId", "data-v-e8442fa3"], ["__file", "Right.vue"]]);

const _sfc_main$11 = /* @__PURE__ */ defineComponent({
  __name: "Left",
  setup(__props, { expose: __expose }) {
    __expose();
    const __returned__ = { view };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

function _sfc_render$w(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createBlock(resolveDynamicComponent($setup.view.computed.currentViewComponent.value));
}
const Left = /* @__PURE__ */ _export_sfc(_sfc_main$11, [["render", _sfc_render$w], ["__file", "Left.vue"]]);

const _sfc_main$10 = {  };

function _sfc_render$v(_ctx, _cache) {
  return null
}
const Bottom = /*#__PURE__*/_export_sfc(_sfc_main$10, [['render',_sfc_render$v],['__file',"Bottom.vue"]]);

const _sfc_main$$ = /* @__PURE__ */ defineComponent({
  __name: "InvoicingBillingPeriodDatePeriodSelector",
  setup(__props, { expose: __expose }) {
    __expose();
    const { t } = useI18n();
    const concreteDateShortcutIds = [
      "today",
      "yesterday",
      "last_seven_days",
      "this_week",
      "last_week",
      "this_month",
      "last_month",
      "same_week_last_year",
      "same_month_last_year"
    ];
    const onSelectionChange = (startDate, endDate) => {
      console.log("Selection changed:", startDate, endDate);
      showReloadAnimation();
      dates.functions.setSelection(startDate, endDate);
    };
    const isReloadAnimationActive = ref(false);
    const isMonthlySplitInProgress = ref(false);
    const isReloadButtonLoading = computed(() => isReloadAnimationActive.value || periodPaging.isDateLoading);
    const shouldShowTopReloadButton = computed(() => view.variables.currentView.value === "home");
    const showReloadAnimation = () => {
      isReloadAnimationActive.value = true;
    };
    const local_departments = ref([
      { id: "0", name: SessionUser.objects.global.language.loading }
      // Add more departments as needed
    ]);
    const local_selectedDepartments = ref([]);
    watch(() => [view.computed.isLoaded.value, periodPaging.isDateLoading], ([isLoaded, isDateLoading]) => {
      if (isLoaded && !isDateLoading) {
        isReloadAnimationActive.value = false;
      }
    }, { immediate: true });
    getDepartments();
    watch(() => departments.value, (newDepartments) => {
      local_departments.value = newDepartments.map((department) => ({
        id: department.id,
        name: department.name
      }));
    }, { immediate: true });
    const escapeHtml = (value) => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
    const getSplitResponsePayload = (response = {}) => response?.data?.data ?? response?.data ?? {};
    const buildMonthlySplitPreviewHtml = (preview = {}) => {
      const changed = Array.isArray(preview.changed) ? preview.changed : [];
      const skipped = Array.isArray(preview.skipped) ? preview.skipped : [];
      const changedHtml = changed.map((item) => {
        const months = Array.isArray(item.months) ? item.months : [];
        const monthRows = months.map((month) => {
          const target = month?.will_create_collection ? t("invoicing_period.monthly_split.preview_create_new") : t("invoicing_period.monthly_split.preview_existing", {
            id: month?.target_invoice_collection_id ?? month?.invoice_collection_id ?? item.invoice_collection_id
          });
          return `
        <tr>
          <td>${escapeHtml(month?.month)}</td>
          <td>${escapeHtml(t("invoicing_period.monthly_split.preview_orders", { count: month?.order_count ?? 0 }))}</td>
          <td>${escapeHtml(target)}</td>
        </tr>
      `;
        }).join("");
        return `
      <section class="monthly-split-preview__collection">
        <strong>${escapeHtml(t("invoicing_period.monthly_split.preview_collection_title", { id: item.invoice_collection_id }))}</strong>
        <table class="table is-fullwidth is-narrow monthly-split-preview__table">
          <tbody>${monthRows}</tbody>
        </table>
      </section>
    `;
      }).join("");
      const skippedHtml = skipped.length > 0 ? `
      <section class="monthly-split-preview__skipped">
        <strong>${escapeHtml(t("invoicing_period.monthly_split.preview_skipped_title"))}</strong>
        <ul>
          ${skipped.slice(0, 8).map((item) => `
            <li>#${escapeHtml(item.invoice_collection_id)}: ${escapeHtml(item.message || item.reason || "")}</li>
          `).join("")}
        </ul>
      </section>
    ` : "";
      return `
    <div class="monthly-split-preview" style="text-align: left;">
      <p>${escapeHtml(t("invoicing_period.monthly_split.preview_summary", {
        processed: preview.processed_count ?? 0,
        changed: preview.changed_count ?? 0,
        skipped: preview.skipped_count ?? 0
      }))}</p>
      ${changedHtml}
      ${skippedHtml}
    </div>
  `;
    };
    const onSplitCollectedInvoicesByMonth = async () => {
      isMonthlySplitInProgress.value = true;
      try {
        const dateFrom = dates.computed.formattedStartDate.value;
        const dateTo = dates.computed.formattedEndDate.value;
        const previewResponse = await SessionUser.objects.collectedOrderInvoices.functions.split_by_month(dateFrom, dateTo, { preview: true });
        const previewResult = getSplitResponsePayload(previewResponse);
        if ((previewResult.changed_count ?? 0) < 1) {
          await Swal.fire({
            icon: "info",
            title: t("invoicing_period.monthly_split.preview_no_changes_title"),
            html: buildMonthlySplitPreviewHtml(previewResult) || escapeHtml(t("invoicing_period.monthly_split.preview_no_changes_text"))
          });
          return;
        }
        const confirmation = await Swal.fire({
          title: t("invoicing_period.monthly_split.preview_title"),
          html: buildMonthlySplitPreviewHtml(previewResult),
          icon: "info",
          showCancelButton: true,
          confirmButtonText: t("invoicing_period.monthly_split.preview_apply"),
          cancelButtonText: t("common.cancel"),
          width: "56rem"
        });
        if (!confirmation.isConfirmed) {
          return;
        }
        const response = await SessionUser.objects.collectedOrderInvoices.functions.split_by_month(dateFrom, dateTo, { preview: false });
        const result = getSplitResponsePayload(response);
        await Swal.fire({
          icon: "success",
          title: t("invoicing_period.monthly_split.success_title"),
          text: t("invoicing_period.monthly_split.success_text", {
            processed: result.processed_count ?? 0,
            changed: result.changed_count ?? 0,
            skipped: result.skipped_count ?? 0
          })
        });
        onSelectionChange(dates.variables.start.value, dates.variables.end.value);
        showReloadAnimation();
      } catch (error) {
        await Swal.fire({
          icon: "error",
          title: t("invoicing_period.monthly_split.error_title"),
          text: SessionUser.functions.parseErrorMessage(error)
        });
      } finally {
        isMonthlySplitInProgress.value = false;
      }
    };
    const __returned__ = { t, concreteDateShortcutIds, onSelectionChange, isReloadAnimationActive, isMonthlySplitInProgress, isReloadButtonLoading, shouldShowTopReloadButton, showReloadAnimation, local_departments, local_selectedDepartments, escapeHtml, getSplitResponsePayload, buildMonthlySplitPreviewHtml, onSplitCollectedInvoicesByMonth, dates, SessionUser, DatePeriodSelector, ColorIndicator };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$s = { class: "level-item" };
const _hoisted_2$n = { class: "dropdown-item" };
const _hoisted_3$l = { class: "select is-multiple is-fullwidth" };
const _hoisted_4$l = ["value"];
const _hoisted_5$k = { class: "level-item" };
const _hoisted_6$k = ["disabled"];
const _hoisted_7$j = {
  key: 0,
  class: "level-item"
};
const _hoisted_8$j = ["disabled"];
function _sfc_render$u(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createBlock($setup["DatePeriodSelector"], {
    selection: {
      startDate: $setup.dates.variables.start.value,
      endDate: $setup.dates.variables.end.value
    },
    visibility: {
      showUpdateButton: false,
      showSelectionValidity: true
    },
    "shortcut-ids": $setup.concreteDateShortcutIds,
    "on-selection-change": $setup.onSelectionChange,
    "auto-emit-change": true
  }, {
    left: withCtx(() => [
      createCommentVNode(" Departments selector (multiple checkbox) "),
      withDirectives(createBaseVNode(
        "div",
        _hoisted_1$s,
        [
          createVNode($setup["ColorIndicator"], {
            label: {
              text: $setup.SessionUser.functions.ucFirst($setup.SessionUser.objects.departments.meta.labels.multiple) + " (" + $setup.local_selectedDepartments.length + ")",
              classes: []
            },
            dropdown_direction: "down",
            color_class: "has-text-link",
            icon_class: "fas fa-building",
            name: $setup.SessionUser.objects.departments.meta.labels.multiple
          }, {
            content: withCtx(() => [
              createBaseVNode("div", _hoisted_2$n, [
                createCommentVNode(" Checkbox for each department "),
                createBaseVNode("div", _hoisted_3$l, [
                  withDirectives(createBaseVNode(
                    "select",
                    {
                      "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => $setup.local_selectedDepartments = $event),
                      multiple: "",
                      class: "is-fullwidth"
                    },
                    [
                      (openBlock(true), createElementBlock(
                        Fragment,
                        null,
                        renderList($setup.local_departments, (department) => {
                          return openBlock(), createElementBlock("option", {
                            key: department.id,
                            value: department.name
                          }, toDisplayString(department.name), 9, _hoisted_4$l);
                        }),
                        128
                        /* KEYED_FRAGMENT */
                      ))
                    ],
                    512
                    /* NEED_PATCH */
                  ), [
                    [vModelSelect, $setup.local_selectedDepartments]
                  ])
                ])
              ])
            ]),
            _: 1
            /* STABLE */
          }, 8, ["label", "name"])
        ],
        512
        /* NEED_PATCH */
      ), [
        [vShow, false]
      ])
    ]),
    right: withCtx(() => [
      createBaseVNode("div", _hoisted_5$k, [
        createBaseVNode("button", {
          class: normalizeClass(["button is-dark is-inverted", { "is-loading": $setup.isMonthlySplitInProgress }]),
          disabled: $setup.isMonthlySplitInProgress,
          onClick: $setup.onSplitCollectedInvoicesByMonth,
          "data-testid": "invoicing-period-split-by-month-button"
        }, [
          _cache[2] || (_cache[2] = createBaseVNode(
            "span",
            { class: "icon is-small" },
            [
              createBaseVNode("i", { class: "fas fa-calendar-alt" })
            ],
            -1
            /* CACHED */
          )),
          createBaseVNode(
            "span",
            null,
            toDisplayString($setup.t("invoicing_period.monthly_split.button")),
            1
            /* TEXT */
          )
        ], 10, _hoisted_6$k)
      ]),
      createCommentVNode(" Reload button with animation "),
      $setup.shouldShowTopReloadButton ? (openBlock(), createElementBlock("div", _hoisted_7$j, [
        createBaseVNode("button", {
          class: normalizeClass(["button is-dark is-inverted", { "is-loading": $setup.isReloadButtonLoading }]),
          disabled: $setup.isReloadButtonLoading,
          onClick: _cache[1] || (_cache[1] = ($event) => {
            $setup.onSelectionChange($setup.dates.variables.start.value, $setup.dates.variables.end.value);
            $setup.showReloadAnimation();
          }),
          "data-testid": "invoicing-period-reload-button"
        }, [
          _cache[3] || (_cache[3] = createBaseVNode(
            "span",
            { class: "icon is-small" },
            [
              createBaseVNode("span", { class: "icon is-small" }, [
                createBaseVNode("i", { class: "fas fa-sync-alt" })
              ])
            ],
            -1
            /* CACHED */
          )),
          createBaseVNode(
            "span",
            null,
            toDisplayString($setup.SessionUser.objects.global.language.update),
            1
            /* TEXT */
          )
        ], 10, _hoisted_8$j)
      ])) : createCommentVNode("v-if", true)
    ]),
    _: 1
    /* STABLE */
  }, 8, ["selection"]);
}
const InvoicingBillingPeriodDatePeriodSelector = /* @__PURE__ */ _export_sfc(_sfc_main$$, [["render", _sfc_render$u], ["__file", "InvoicingBillingPeriodDatePeriodSelector.vue"]]);

const _sfc_main$_ = /* @__PURE__ */ defineComponent({
  __name: "Top",
  setup(__props, { expose: __expose }) {
    __expose();
    const __returned__ = { InvoicingBillingPeriodDatePeriodSelector };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

function _sfc_render$t(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock(
    Fragment,
    null,
    [
      createCommentVNode(" Time / Period selection "),
      createVNode($setup["InvoicingBillingPeriodDatePeriodSelector"])
    ],
    2112
    /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
  );
}
const Top = /* @__PURE__ */ _export_sfc(_sfc_main$_, [["render", _sfc_render$t], ["__file", "Top.vue"]]);

const _sfc_main$Z = /* @__PURE__ */ defineComponent({
  __name: "InvoicingBillingPeriod",
  setup(__props, { expose: __expose }) {
    __expose();
    const __returned__ = { InvoicingBillingPeriodLayoutDefault, Right, Left, Bottom, Top };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$r = { "data-testid": "invoicing-period-view" };
function _sfc_render$s(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock("div", _hoisted_1$r, [
    createVNode($setup["InvoicingBillingPeriodLayoutDefault"], null, {
      "content-top": withCtx(() => [
        createVNode($setup["Top"])
      ]),
      "content-right": withCtx(() => [
        createVNode($setup["Right"])
      ]),
      "content-bottom": withCtx(() => [
        createVNode($setup["Bottom"])
      ]),
      "content-left": withCtx(() => [
        createVNode($setup["Left"])
      ]),
      _: 1
      /* STABLE */
    })
  ]);
}
const InvoicingBillingPeriod = /* @__PURE__ */ _export_sfc(_sfc_main$Z, [["render", _sfc_render$s], ["__file", "InvoicingBillingPeriod.vue"]]);

const _sfc_main$Y = {  };

const _hoisted_1$q = { class: "card" };
const _hoisted_2$m = { class: "card-content" };

function _sfc_render$r(_ctx, _cache) {
  return (openBlock(), createElementBlock("div", _hoisted_1$q, [
    createBaseVNode("div", _hoisted_2$m, [
      renderSlot(_ctx.$slots, "default")
    ])
  ]))
}
const InvoiceDistributionCard = /*#__PURE__*/_export_sfc(_sfc_main$Y, [['render',_sfc_render$r],['__file',"InvoiceDistributionCard.vue"]]);

const DEFAULT_LOCALE = 'da-DK';
const DISTRIBUTION_COMPARE_MODES = ['invoice_total', 'line_by_line'];
const DISTRIBUTION_COMPARE_VISIBILITY_OPTIONS = ['all', 'mismatches', 'warnings', 'matches'];
const DEFAULT_DISTRIBUTION_QUERY_STATE = {
  compareMonth: null,
  compareMode: 'invoice_total',
  compareVisibility: 'all',
  customerSearch: '',
  customerSource: 'all',
  customerDepartment: 'all',
  departmentSearch: '',
};

const CUSTOMER_SOURCES = ['all', 'fixed_pricing', 'vehicle_subscriptions', 'customer_prices'];

const getQueryValue = (value) => {
  if (Array.isArray(value)) {
    return value[0];
  }
  return value;
};

const normalizeQueryText = (value) => {
  return String(value || '').trim();
};

const asArray = (value) => (Array.isArray(value) ? value : []);

const readFirstFiniteNumber = (...values) => {
  for (const value of values) {
    const parsed = Number(value);
    if (Number.isFinite(parsed)) {
      return parsed;
    }
  }
  return null;
};

const readFirstNumberFromObject = (source = {}, keys = []) => {
  if (!source || typeof source !== 'object' || Array.isArray(source)) {
    return null;
  }
  for (const key of keys) {
    const parsed = Number(source?.[key]);
    if (Number.isFinite(parsed)) {
      return parsed;
    }
  }
  return null;
};

const uniqueStrings$1 = (items = []) => {
  return Array.from(new Set(
    asArray(items)
      .map((item) => String(item || '').trim())
      .filter((item) => item.length > 0)
  ));
};

const toNumber = (value) => {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : 0;
};

const safeRoundCurrency = (value) => {
  return Math.round((toNumber(value) + Number.EPSILON) * 100) / 100;
};

const formatMonthKey = (year, month) => {
  const normalizedMonth = String(month).padStart(2, '0');
  return `${year}-${normalizedMonth}`;
};

const parseMonthKey = (monthKey) => {
  if (!monthKey || typeof monthKey !== 'string' || !monthKey.includes('-')) {
    return null;
  }
  const [yearRaw, monthRaw] = monthKey.split('-');
  const year = Number(yearRaw);
  const month = Number(monthRaw);
  if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12) {
    return null;
  }
  return { year, month };
};

const normalizeDistributionQueryState = (query = {}) => {
  const compareMonthCandidate = normalizeQueryText(getQueryValue(query.compareMonth));
  const compareMonth = parseMonthKey(compareMonthCandidate) ? compareMonthCandidate : null;

  const compareModeCandidate = normalizeQueryText(getQueryValue(query.compareMode));
  const compareMode = DISTRIBUTION_COMPARE_MODES.includes(compareModeCandidate)
    ? compareModeCandidate
    : DEFAULT_DISTRIBUTION_QUERY_STATE.compareMode;

  const compareVisibilityCandidate = normalizeQueryText(getQueryValue(query.compareVisibility));
  const compareVisibility = DISTRIBUTION_COMPARE_VISIBILITY_OPTIONS.includes(compareVisibilityCandidate)
    ? compareVisibilityCandidate
    : DEFAULT_DISTRIBUTION_QUERY_STATE.compareVisibility;

  const customerSourceCandidate = normalizeQueryText(getQueryValue(query.customerSource));
  const customerSource = CUSTOMER_SOURCES.includes(customerSourceCandidate)
    ? customerSourceCandidate
    : DEFAULT_DISTRIBUTION_QUERY_STATE.customerSource;

  const customerDepartmentCandidate = normalizeQueryText(getQueryValue(query.customerDepartment));
  const customerDepartment = customerDepartmentCandidate || DEFAULT_DISTRIBUTION_QUERY_STATE.customerDepartment;

  return {
    compareMonth,
    compareMode,
    compareVisibility,
    customerSearch: normalizeQueryText(getQueryValue(query.customerSearch)),
    customerSource,
    customerDepartment,
    departmentSearch: normalizeQueryText(getQueryValue(query.departmentSearch)),
  };
};

const buildDistributionQueryState = (queryState = {}) => {
  const normalized = {
    ...DEFAULT_DISTRIBUTION_QUERY_STATE,
    ...normalizeDistributionQueryState(queryState),
  };

  const query = {};

  if (normalized.compareMonth) {
    query.compareMonth = normalized.compareMonth;
  }
  if (normalized.compareMode !== DEFAULT_DISTRIBUTION_QUERY_STATE.compareMode) {
    query.compareMode = normalized.compareMode;
  }
  if (normalized.compareVisibility !== DEFAULT_DISTRIBUTION_QUERY_STATE.compareVisibility) {
    query.compareVisibility = normalized.compareVisibility;
  }
  if (normalized.customerSearch) {
    query.customerSearch = normalized.customerSearch;
  }
  if (normalized.customerSource !== DEFAULT_DISTRIBUTION_QUERY_STATE.customerSource) {
    query.customerSource = normalized.customerSource;
  }
  if (normalized.customerDepartment !== DEFAULT_DISTRIBUTION_QUERY_STATE.customerDepartment) {
    query.customerDepartment = normalized.customerDepartment;
  }
  if (normalized.departmentSearch) {
    query.departmentSearch = normalized.departmentSearch;
  }

  return query;
};

const getMonthDateRange = (year, month) => {
  const start = new Date(Date.UTC(year, month - 1, 1, 0, 0, 0));
  const end = new Date(Date.UTC(year, month, 0, 23, 59, 59));
  return {
    start,
    end,
    dateFrom: start.toISOString().split('T')[0],
    dateTo: end.toISOString().split('T')[0],
  };
};

const getMonthRange = (fromDate, toDate = new Date(), descending = true) => {
  if (!(fromDate instanceof Date) || Number.isNaN(fromDate.getTime())) {
    return [];
  }
  if (!(toDate instanceof Date) || Number.isNaN(toDate.getTime())) {
    return [];
  }

  const start = new Date(Date.UTC(fromDate.getUTCFullYear(), fromDate.getUTCMonth(), 1));
  const end = new Date(Date.UTC(toDate.getUTCFullYear(), toDate.getUTCMonth(), 1));
  if (start > end) {
    return [];
  }

  const values = [];
  const cursor = new Date(start);
  while (cursor <= end) {
    values.push({
      year: cursor.getUTCFullYear(),
      month: cursor.getUTCMonth() + 1,
      key: formatMonthKey(cursor.getUTCFullYear(), cursor.getUTCMonth() + 1),
    });
    cursor.setUTCMonth(cursor.getUTCMonth() + 1);
  }

  return descending ? values.reverse() : values;
};

const getYearMonthLabel = (year, month, locale = DEFAULT_LOCALE) => {
  const date = new Date(Date.UTC(year, month - 1, 1));
  return new Intl.DateTimeFormat(locale, { month: 'long', year: 'numeric' }).format(date);
};

const sortMonthSummaries = (rows = [], sortKey = 'month', sortDirection = 'desc') => {
  const safeRows = Array.isArray(rows) ? [...rows] : [];
  const direction = sortDirection === 'asc' ? 1 : -1;

  return safeRows.sort((a, b) => {
    if (sortKey === 'total') {
      const totalDiff = (toNumber(a?.totalAmount) - toNumber(b?.totalAmount)) * direction;
      if (Math.abs(totalDiff) > 0.009) {
        return totalDiff;
      }
    }

    const aMonthWeight = (toNumber(a?.year) * 100) + toNumber(a?.month);
    const bMonthWeight = (toNumber(b?.year) * 100) + toNumber(b?.month);
    const monthDiff = (aMonthWeight - bMonthWeight) * direction;

    if (monthDiff !== 0) {
      return monthDiff;
    }

    const totalFallbackDiff = (toNumber(a?.totalAmount) - toNumber(b?.totalAmount)) * direction;
    if (Math.abs(totalFallbackDiff) > 0.009) {
      return totalFallbackDiff;
    }

    return String(a?.key || '').localeCompare(String(b?.key || '')) * direction;
  });
};

const sumTransactions = (transactions = [], options = {}) => {
  const { bookedOnly = false, includeExcluded = false } = options;
  return (Array.isArray(transactions) ? transactions : []).reduce((sum, transaction) => {
    if (!includeExcluded && transaction?.excluded) {
      return sum;
    }
    if (bookedOnly && !transaction?.booked) {
      return sum;
    }
    return sum + toNumber(transaction?.amount);
  }, 0);
};

const sumBookedTransactions = (customers = []) => {
  return asArray(customers).reduce((sum, customer) => {
    return sum + sumTransactions(customer?.transactions, { bookedOnly: true, includeExcluded: false });
  }, 0);
};

const sumAllTransactions = (customers = []) => {
  return asArray(customers).reduce((sum, customer) => {
    return sum + sumTransactions(customer?.transactions, { bookedOnly: false, includeExcluded: false });
  }, 0);
};

const getCategoryCustomers = (categoryResponse = {}) => {
  return asArray(categoryResponse?.customers || categoryResponse?.data);
};

const getCategoryCollectiveResults = (categoryResponse = {}, legacyKey = null) => {
  if (
    categoryResponse?.collective_results
    && typeof categoryResponse.collective_results === 'object'
    && !Array.isArray(categoryResponse.collective_results)
  ) {
    return categoryResponse.collective_results;
  }

  if (
    legacyKey
    && categoryResponse?.includes?.[legacyKey]
    && typeof categoryResponse.includes[legacyKey] === 'object'
    && !Array.isArray(categoryResponse.includes[legacyKey])
  ) {
    return categoryResponse.includes[legacyKey];
  }

  return {};
};

const getCollectiveDepartmentDistributionMap = (collective = {}, keys = []) => {
  for (const key of keys) {
    const candidate = normalizeObjectNumberMap(collective?.[key]);
    if (Object.keys(candidate).length > 0) {
      return candidate;
    }
  }

  return {};
};

const sumDistributionMap = (distributionMap = {}) => {
  return safeRoundCurrency(
    Object.values(distributionMap || {}).reduce((sum, value) => sum + toNumber(value), 0)
  );
};

const getCollectiveFixedResults = (fixedDistributionResponse = {}) => {
  return getCategoryCollectiveResults(fixedDistributionResponse, 'collective_fixed_pricing_results');
};

const getCollectiveSubscriptionResults = (subscriptionDistributionResponse = {}) => {
  return getCategoryCollectiveResults(subscriptionDistributionResponse, 'collective_subscription_results');
};

const getCollectiveCustomerPriceResults = (customerPriceDistributionResponse = {}) => {
  return getCategoryCollectiveResults(customerPriceDistributionResponse, 'collective_customer_price_results');
};

const getBookedAmountFromPeriod = (periodData = {}) => {
  const customers = periodData?.types?.all || [];
  return safeRoundCurrency(sumBookedTransactions(customers));
};

const getTotalAmountFromPeriod = (periodData = {}) => {
  const customers = periodData?.types?.all || [];
  return safeRoundCurrency(sumAllTransactions(customers));
};

const inferCategoryAmount = ({
  collective = {},
  customers = [],
  collectiveAmountKeys = [],
  metaAmountKeys = [],
}) => {
  const collectiveAmount = readFirstNumberFromObject(collective, collectiveAmountKeys);
  if (Number.isFinite(collectiveAmount)) {
    return safeRoundCurrency(collectiveAmount);
  }

  const metaTotal = asArray(customers).reduce((sum, customer) => {
    const metaCandidates = asArray([
      customer?.meta,
      customer?.meta?.fixed_pricing,
      customer?.meta?.wash_subscription,
      customer?.meta?.wash_subscriptions,
      customer?.meta?.subscription,
      customer?.meta?.vehicle_subscription,
      customer?.meta?.vehicle_subscriptions,
      customer?.meta?.customer_price,
      customer?.meta?.customer_prices,
      customer?.meta?.discount_override,
      customer?.meta?.discount,
      customer?.subscription,
      customer?.customer_price,
      customer?.discount_override,
    ]).filter(Boolean);

    const fromMeta = readFirstFiniteNumber(
      ...metaCandidates.map((candidate) => readFirstNumberFromObject(candidate, metaAmountKeys))
    );
    if (Number.isFinite(fromMeta)) {
      return sum + fromMeta;
    }

    return sum + sumTransactions(customer?.transactions, { bookedOnly: false, includeExcluded: false });
  }, 0);

  return safeRoundCurrency(metaTotal);
};

const buildMonthSummary = ({
  year,
  month,
  periodData = {},
  fixedDistribution = {},
  subscriptionDistribution = {},
  customerPriceDistribution = {},
}) => {
  const fixedCollective = getCollectiveFixedResults(fixedDistribution);
  const subscriptionCollective = getCollectiveSubscriptionResults(subscriptionDistribution);
  const customerPriceCollective = getCollectiveCustomerPriceResults(customerPriceDistribution);

  const fixedCustomers = getCategoryCustomers(fixedDistribution);
  const subscriptionCustomers = getCategoryCustomers(subscriptionDistribution);
  const customerPriceCustomers = getCategoryCustomers(customerPriceDistribution);
  const fixedDepartmentDistribution = getCollectiveDepartmentDistributionMap(fixedCollective, [
    'total_department_totals_relative_parsed',
    'total_department_totals_parsed',
    'department_distribution_parsed',
    'department_distribution',
    'department_totals_relative',
    'department_totals',
  ]);
  const subscriptionDepartmentDistribution = getCollectiveDepartmentDistributionMap(subscriptionCollective, [
    'subscription_price_department_distribution_parsed',
    'subscription_price_department_distribution',
    'total_department_totals_relative_parsed',
    'department_distribution_parsed',
    'department_distribution',
    'department_totals_relative',
    'department_totals',
  ]);

  const bookedAmount = getBookedAmountFromPeriod(periodData);
  const allTransactionsAmount = getTotalAmountFromPeriod(periodData);
  const fixedPricingAmount = Object.keys(fixedDepartmentDistribution).length > 0
    ? sumDistributionMap(fixedDepartmentDistribution)
    : inferCategoryAmount({
      collective: fixedCollective,
      customers: fixedCustomers,
      collectiveAmountKeys: ['total_fixed_price', 'total_price', 'total_amount', 'net_total'],
      metaAmountKeys: ['price', 'fixed_price', 'total_price', 'amount', 'total_amount'],
    });
  const subscriptionAmount = Object.keys(subscriptionDepartmentDistribution).length > 0
    ? sumDistributionMap(subscriptionDepartmentDistribution)
    : inferCategoryAmount({
      collective: subscriptionCollective,
      customers: subscriptionCustomers,
      collectiveAmountKeys: ['total_subscription_price', 'total_price', 'total_amount', 'net_total'],
      metaAmountKeys: ['price', 'subscription_price', 'total_price', 'amount', 'total_amount'],
    });
  const customerPriceAmount = inferCategoryAmount({
    collective: customerPriceCollective,
    customers: customerPriceCustomers,
    collectiveAmountKeys: [
      'total_customer_price',
      'total_customer_prices',
      'total_discount_price',
      'total_discount_amount',
      'total_price',
      'total_amount',
      'net_total',
    ],
    metaAmountKeys: [
      'price',
      'customer_price',
      'discount_price',
      'discount_amount',
      'total_price',
      'amount',
      'total_amount',
    ],
  });
  const distributionAmount = safeRoundCurrency(fixedPricingAmount + subscriptionAmount);
  const otherBookedAmount = safeRoundCurrency(
    Math.max(bookedAmount - distributionAmount - customerPriceAmount, 0)
  );

  return {
    year,
    month,
    key: formatMonthKey(year, month),
    bookedAmount,
    allTransactionsAmount,
    fixedPricingAmount,
    subscriptionAmount,
    customerPriceAmount,
    distributionAmount,
    otherBookedAmount,
    fixedCustomers: fixedCustomers.length,
    subscriptionCustomers: subscriptionCustomers.length,
    customerPriceCustomers: customerPriceCustomers.length,
    totalAmount: safeRoundCurrency(bookedAmount + distributionAmount),
  };
};

const buildSourceComposition = (summary = {}) => {
  const fixedAmount = safeRoundCurrency(summary?.fixedPricingAmount);
  const subscriptionAmount = safeRoundCurrency(summary?.subscriptionAmount);
  const customerPriceAmount = safeRoundCurrency(summary?.customerPriceAmount);
  const distributionAmount = safeRoundCurrency(summary?.distributionAmount || fixedAmount + subscriptionAmount);
  const sourceTotalAmount = safeRoundCurrency(fixedAmount + subscriptionAmount + customerPriceAmount);
  const fixedPercent = sourceTotalAmount > 0
    ? safeRoundCurrency((fixedAmount / sourceTotalAmount) * 100)
    : 0;
  const subscriptionPercent = sourceTotalAmount > 0
    ? safeRoundCurrency((subscriptionAmount / sourceTotalAmount) * 100)
    : 0;
  const customerPricePercent = sourceTotalAmount > 0
    ? safeRoundCurrency((customerPriceAmount / sourceTotalAmount) * 100)
    : 0;

  return {
    fixedAmount,
    subscriptionAmount,
    customerPriceAmount,
    distributionAmount,
    sourceTotalAmount,
    fixedPercent,
    subscriptionPercent,
    customerPricePercent,
  };
};

const normalizeObjectNumberMap = (value) => {
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
    return {};
  }
  return Object.keys(value).reduce((acc, key) => {
    acc[key] = safeRoundCurrency(value[key]);
    return acc;
  }, {});
};

const toDepartmentNameById = (departments = []) => {
  return (Array.isArray(departments) ? departments : []).reduce((acc, department) => {
    acc[String(department.id)] = department.name;
    return acc;
  }, {});
};

const buildDepartmentAllocations = ({
  departments = [],
  fixedDistribution = {},
  subscriptionDistribution = {},
  customerPriceDistribution = {},
  bookedAmount = 0,
}) => {
  const fixedCollective = getCollectiveFixedResults(fixedDistribution);
  const subscriptionCollective = getCollectiveSubscriptionResults(subscriptionDistribution);
  const customerPriceCollective = getCollectiveCustomerPriceResults(customerPriceDistribution);

  const fixedByName = normalizeDepartmentAllocationToNames(
    getCollectiveDepartmentDistributionMap(fixedCollective, [
      'total_department_totals_relative_parsed',
      'total_department_totals_parsed',
      'department_distribution_parsed',
      'department_distribution',
      'department_totals_relative',
      'department_totals',
    ]),
    departments
  );
  const subscriptionByName = normalizeDepartmentAllocationToNames(
    getCollectiveDepartmentDistributionMap(subscriptionCollective, [
      'subscription_price_department_distribution_parsed',
      'subscription_price_department_distribution',
      'total_department_totals_relative_parsed',
      'department_distribution_parsed',
      'department_distribution',
      'department_totals_relative',
      'department_totals',
    ]),
    departments
  );
  const customerPriceByName = normalizeDepartmentAllocationToNames(
    getCollectiveDepartmentDistributionMap(customerPriceCollective, [
      'customer_price_department_distribution_parsed',
      'customer_prices_department_distribution_parsed',
      'discount_department_distribution_parsed',
      'department_distribution_parsed',
      'department_distribution',
      'department_totals_relative',
      'department_totals',
    ]),
    departments
  );

  const byId = toDepartmentNameById(departments);
  const byName = (Array.isArray(departments) ? departments : []).reduce((acc, department) => {
    acc[department.name] = String(department.id);
    return acc;
  }, {});

  const allNames = new Set([
    ...Object.keys(fixedByName),
    ...Object.keys(subscriptionByName),
    ...Object.keys(customerPriceByName),
    ...Object.keys(byName),
  ]);

  const rows = [];
  const totalSharedAmount = safeRoundCurrency(
    Object.values(fixedByName).reduce((sum, value) => sum + value, 0)
    + Object.values(subscriptionByName).reduce((sum, value) => sum + value, 0)
  );

  allNames.forEach((name) => {
    const fixedAmount = safeRoundCurrency(fixedByName[name]);
    const subscriptionAmount = safeRoundCurrency(subscriptionByName[name]);
    const customerPriceAmount = safeRoundCurrency(customerPriceByName[name]);
    const totalAmount = safeRoundCurrency(fixedAmount + subscriptionAmount);
    const ratio = totalSharedAmount > 0 ? (totalAmount / totalSharedAmount) : 0;

    rows.push({
      departmentId: byName[name] || null,
      departmentName: name,
      fixedAmount,
      subscriptionAmount,
      customerPriceAmount,
      totalAmount,
      sharePercent: safeRoundCurrency(ratio * 100),
      estimatedBookedAllocation: safeRoundCurrency(toNumber(bookedAmount) * ratio),
      isKnownDepartment: Boolean(byName[name]) || Object.values(byId).includes(name),
    });
  });

  return rows.sort((a, b) => b.totalAmount - a.totalAmount);
};

const buildDepartmentAllocationFooterTotals = (rows = []) => {
  const safeRows = Array.isArray(rows) ? rows : [];
  const fixedAmount = safeRoundCurrency(
    safeRows.reduce((sum, row) => sum + toNumber(row?.fixedAmount), 0)
  );
  const subscriptionAmount = safeRoundCurrency(
    safeRows.reduce((sum, row) => sum + toNumber(row?.subscriptionAmount), 0)
  );
  const customerPriceAmount = safeRoundCurrency(
    safeRows.reduce((sum, row) => sum + toNumber(row?.customerPriceAmount), 0)
  );

  return {
    fixedAmount,
    subscriptionAmount,
    customerPriceAmount,
    totalAmount: safeRoundCurrency(fixedAmount + subscriptionAmount),
  };
};

const normalizeDepartmentAllocationMap = (value) => {
  return normalizeObjectNumberMap(value);
};

const normalizeDepartmentAllocationToNames = (departmentTotals = {}, departments = []) => {
  const byId = toDepartmentNameById(departments);
  const normalized = {};
  Object.keys(departmentTotals).forEach((key) => {
    const mappedName = byId[String(key)] || key;
    normalized[mappedName] = safeRoundCurrency(departmentTotals[key]);
  });
  return normalized;
};

const getSubscriptionCustomerMeta = (customer = {}) => {
  const candidates = [
    customer?.meta?.wash_subscription,
    customer?.meta?.wash_subscriptions,
    customer?.meta?.subscription,
    customer?.subscription,
    customer?.meta?.vehicle_subscription,
    customer?.meta?.vehicle_subscriptions,
  ];

  return candidates.find((candidate) => candidate && typeof candidate === 'object') || null;
};

const getFixedCustomerMeta = (customer = {}) => {
  return customer?.meta?.fixed_pricing || customer?.meta?.fixedPricing || customer?.fixed_pricing || null;
};

const getCustomerPriceMeta = (customer = {}) => {
  const candidates = [
    customer?.meta?.customer_price,
    customer?.meta?.customer_prices,
    customer?.meta?.discount_override,
    customer?.meta?.discount,
    customer?.customer_price,
    customer?.discount_override,
  ];
  return candidates.find((candidate) => candidate && typeof candidate === 'object') || null;
};

const getCustomerDepartmentTotals = (customer = {}, meta = {}) => {
  return normalizeDepartmentAllocationMap(
    meta?.department_totals_relative
    || meta?.department_totals
    || meta?.subscription_price_department_distribution
    || meta?.customer_price_department_distribution
    || meta?.discount_department_distribution
    || meta?.department_distribution
    || customer?.department_totals_relative
    || customer?.department_totals
    || customer?.department_distribution
    || {}
  );
};

const getCustomerCreatedAt = (customer = {}, meta = {}) => {
  return meta?.created_at || customer?.created_at || asArray(customer?.transactions)?.[0]?.date || null;
};

const getCustomerAmount = ({
  customer = {},
  meta = {},
  amountKeys = [],
}) => {
  const amount = readFirstFiniteNumber(
    readFirstNumberFromObject(meta, amountKeys),
    readFirstNumberFromObject(customer, amountKeys)
  );

  if (Number.isFinite(amount)) {
    return safeRoundCurrency(amount);
  }

  return safeRoundCurrency(sumTransactions(customer?.transactions, { bookedOnly: false, includeExcluded: false }));
};

const toIsoDateOnly = (dateLike) => {
  if (!dateLike) {
    return null;
  }
  const date = new Date(dateLike);
  if (Number.isNaN(date.getTime())) {
    return null;
  }
  return date.toISOString().split('T')[0];
};

const isCreatedOnOrBeforeMonthEnd = (createdAt, year, month) => {
  if (!createdAt) {
    return true;
  }
  const createdDate = new Date(createdAt);
  if (Number.isNaN(createdDate.getTime())) {
    return true;
  }
  const { end } = getMonthDateRange(year, month);
  return createdDate.getTime() <= end.getTime();
};

const formatDepartmentAllocationsText = (departmentAllocations = {}) => {
  const entries = Object.entries(departmentAllocations || {})
    .filter(([, value]) => toNumber(value) !== 0)
    .sort((a, b) => toNumber(b[1]) - toNumber(a[1]));

  if (!entries.length) {
    return '-';
  }

  return entries
    .map(([department, value]) => `${department}: ${safeRoundCurrency(value)}`)
    .join(', ');
};

const buildCustomerAllocationRows = ({
  fixedDistribution = {},
  subscriptionDistribution = {},
  customerPriceDistribution = {},
  year,
  month,
  departments = [],
}) => {
  const rows = [];

  const fixedCustomers = getCategoryCustomers(fixedDistribution);
  fixedCustomers.forEach((customer) => {
    const fixedPricing = getFixedCustomerMeta(customer) || {};
    const createdAt = getCustomerCreatedAt(customer, fixedPricing);
    const isWithinMonth = isCreatedOnOrBeforeMonthEnd(createdAt, year, month);
    if (!isWithinMonth) {
      return;
    }

    const departmentTotals = getCustomerDepartmentTotals(customer, fixedPricing);

    rows.push({
      source: 'fixed_pricing',
      customerId: customer?.id || null,
      customerNumber: customer?.customer_number || null,
      customerName: customer?.customer_name || customer?.name || '-',
      amount: getCustomerAmount({
        customer,
        meta: fixedPricing,
        amountKeys: ['price', 'fixed_price', 'total_price', 'amount', 'total_amount'],
      }),
      originalAmount: safeRoundCurrency(readFirstFiniteNumber(
        fixedPricing?.original_price,
        customer?.original_price
      )),
      createdAt: toIsoDateOnly(createdAt),
      departmentAllocations: normalizeDepartmentAllocationToNames(departmentTotals, departments),
      requiresAction: Boolean(customer?.requires_action),
    });
  });

  const subscriptionCustomers = getCategoryCustomers(subscriptionDistribution);
  subscriptionCustomers.forEach((customer) => {
    const subscriptionMeta = getSubscriptionCustomerMeta(customer) || {};
    const createdAt = getCustomerCreatedAt(customer, subscriptionMeta);
    const isWithinMonth = isCreatedOnOrBeforeMonthEnd(createdAt, year, month);
    if (!isWithinMonth) {
      return;
    }

    const departmentTotals = getCustomerDepartmentTotals(customer, subscriptionMeta);

    rows.push({
      source: 'vehicle_subscriptions',
      customerId: customer?.id || null,
      customerNumber: customer?.customer_number || null,
      customerName: customer?.customer_name || customer?.name || '-',
      amount: getCustomerAmount({
        customer,
        meta: subscriptionMeta,
        amountKeys: ['price', 'total_price', 'subscription_price', 'amount', 'total_amount'],
      }),
      originalAmount: safeRoundCurrency(readFirstFiniteNumber(
        subscriptionMeta?.original_price,
        customer?.original_price
      )),
      createdAt: toIsoDateOnly(createdAt),
      departmentAllocations: normalizeDepartmentAllocationToNames(departmentTotals, departments),
      requiresAction: Boolean(customer?.requires_action),
    });
  });

  const customerPriceCustomers = getCategoryCustomers(customerPriceDistribution);
  customerPriceCustomers.forEach((customer) => {
    const customerPriceMeta = getCustomerPriceMeta(customer) || {};
    const createdAt = getCustomerCreatedAt(customer, customerPriceMeta);
    const isWithinMonth = isCreatedOnOrBeforeMonthEnd(createdAt, year, month);
    if (!isWithinMonth) {
      return;
    }

    const departmentTotals = getCustomerDepartmentTotals(customer, customerPriceMeta);

    rows.push({
      source: 'customer_prices',
      customerId: customer?.id || null,
      customerNumber: customer?.customer_number || null,
      customerName: customer?.customer_name || customer?.name || '-',
      amount: getCustomerAmount({
        customer,
        meta: customerPriceMeta,
        amountKeys: [
          'price',
          'customer_price',
          'discount_price',
          'discount_amount',
          'total_price',
          'amount',
          'total_amount',
        ],
      }),
      originalAmount: safeRoundCurrency(readFirstFiniteNumber(
        customerPriceMeta?.original_price,
        customer?.original_price
      )),
      createdAt: toIsoDateOnly(createdAt),
      departmentAllocations: normalizeDepartmentAllocationToNames(departmentTotals, departments),
      requiresAction: Boolean(customer?.requires_action),
    });
  });

  return rows.sort((a, b) => b.amount - a.amount);
};

const filterDepartmentRows = ({ rows = [], search = '' }) => {
  const searchText = String(search || '').trim().toLowerCase();
  if (!searchText) {
    return rows;
  }
  return rows.filter((row) => {
    return String(row?.departmentName || '').toLowerCase().includes(searchText);
  });
};

const filterCustomerRows = ({
  rows = [],
  search = '',
  source = 'all',
  department = 'all',
}) => {
  const searchText = String(search || '').trim().toLowerCase();
  return rows.filter((row) => {
    const sourceMatches = source === 'all' || row.source === source;
    const nameMatches = !searchText
      || String(row?.customerName || '').toLowerCase().includes(searchText)
      || String(row?.customerNumber || '').toLowerCase().includes(searchText);
    const departmentMatches = department === 'all'
      || Object.keys(row?.departmentAllocations || {}).some((name) => name === department);

    return sourceMatches && nameMatches && departmentMatches;
  });
};

const buildMonthComparison = (baseSummary = {}, compareSummary = {}) => {
  const metricNames = [
    'bookedAmount',
    'fixedPricingAmount',
    'subscriptionAmount',
    'customerPriceAmount',
    'distributionAmount',
    'otherBookedAmount',
    'totalAmount',
  ];

  return metricNames.reduce((acc, metricName) => {
    const base = toNumber(baseSummary?.[metricName]);
    const target = toNumber(compareSummary?.[metricName]);
    const delta = safeRoundCurrency(base - target);
    const percentChange = target === 0 ? null : safeRoundCurrency((delta / target) * 100);
    acc[metricName] = {
      base,
      target,
      delta,
      percentChange,
      isIncrease: delta >= 0,
    };
    return acc;
  }, {});
};

const normalizeCompareResult = (invoice = {}, compareResponse = null, mode = 'invoice_total') => {
  const payload = compareResponse?.data || compareResponse || {};
  const draftTarget = payload?.comparison?.targets?.draft || null;
  const bookedTarget = payload?.comparison?.targets?.booked || null;

  const internalTotal = safeRoundCurrency(readFirstFiniteNumber(
    payload?.comparison?.totals?.internal_net_total,
    payload?.details?.internal?.normalized?.totals?.net_total,
    payload?.internal_total,
    invoice?.total_net_amount
  ));

  const draftTotal = (
    readFirstFiniteNumber(
      draftTarget?.totals?.target_net_total,
      draftTarget?.target_net_total,
      draftTarget?.net_total
    )
  );
  const bookedTotal = (
    readFirstFiniteNumber(
      bookedTarget?.totals?.target_net_total,
      bookedTarget?.target_net_total,
      bookedTarget?.net_total
    )
  );
  const normalizedDraftTotal = Number.isFinite(draftTotal)
    ? safeRoundCurrency(draftTotal)
    : (
      payload?.draft_total === null || payload?.draft_total === undefined
        ? null
        : safeRoundCurrency(payload?.draft_total)
    );
  const normalizedBookedTotal = Number.isFinite(bookedTotal)
    ? safeRoundCurrency(bookedTotal)
    : (
      payload?.booked_total === null || payload?.booked_total === undefined
        ? null
        : safeRoundCurrency(payload?.booked_total)
    );

  const selectedTargetName = bookedTarget ? 'booked' : (draftTarget ? 'draft' : null);
  const selectedTarget = selectedTargetName === 'booked' ? bookedTarget : draftTarget;
  const selectedTargetTotal = selectedTargetName === 'booked' ? normalizedBookedTotal : normalizedDraftTotal;

  let difference = payload?.difference;
  if (difference === null || difference === undefined) {
    const explicitTargetDifference = readFirstFiniteNumber(
      selectedTarget?.totals?.difference,
      selectedTarget?.difference
    );
    if (Number.isFinite(explicitTargetDifference)) {
      difference = safeRoundCurrency(explicitTargetDifference);
    } else if (selectedTargetTotal !== null && selectedTargetTotal !== undefined) {
      difference = safeRoundCurrency(internalTotal - selectedTargetTotal);
    } else if (normalizedBookedTotal !== null) {
      difference = safeRoundCurrency(internalTotal - normalizedBookedTotal);
    } else if (normalizedDraftTotal !== null) {
      difference = safeRoundCurrency(internalTotal - normalizedDraftTotal);
    } else {
      difference = null;
    }
  } else {
    difference = safeRoundCurrency(difference);
  }

  const mismatchReasons = uniqueStrings$1([
    ...(selectedTarget?.mismatch_reasons || []),
    ...(selectedTarget?.reasons || []),
  ]);
  const warnings = uniqueStrings$1([
    ...(payload?.warnings || []),
    ...(payload?.comparison?.warnings || []),
    ...(selectedTarget?.warnings || []),
    ...mismatchReasons,
  ]);
  const orderIds = asArray(payload?.details?.order_ids || payload?.order_ids);
  const compareStatus = selectedTarget?.status || null;

  const isTargetMismatch = selectedTarget
    ? (
      selectedTarget?.overall_match === false
      || ['partial_mismatch', 'total_mismatch', 'missing_target'].includes(compareStatus)
    )
    : false;
  const hasMismatch = isTargetMismatch || (difference !== null ? Math.abs(difference) > 0.009 : warnings.length > 0);
  const row = {
    invoiceId: invoice?.id ?? payload?.collected_invoice_id ?? null,
    customerNumber: invoice?.customer_number ?? payload?.details?.customer?.internal_customer_number ?? null,
    customerName: invoice?.customer_name || invoice?.name || payload?.details?.customer?.name || '-',
    internalTotal,
    bookedTotal: normalizedBookedTotal,
    draftTotal: normalizedDraftTotal,
    difference,
    warnings,
    warningCount: warnings.length,
    orderCount: orderIds.length,
    orderIds,
    mismatchReasons,
    compareTarget: selectedTargetName,
    compareStatus,
    mode,
    status: hasMismatch ? 'mismatch' : 'ok',
    checkedAt: new Date().toISOString(),
  };

  if (mode === 'line_by_line') {
    const localLineCount = readFirstFiniteNumber(
      payload?.details?.internal?.normalized?.totals?.billable_line_count,
      payload?.details?.internal?.normalized?.totals?.line_count,
      orderIds.length
    );
    const economicLineCount = readFirstFiniteNumber(
      selectedTarget?.lines?.summary?.target_billable_count,
      selectedTarget?.lines?.summary?.line_count
    );
    const selectedTargetDiffCount = selectedTarget
      ? asArray(selectedTarget?.lines?.diff).length
      : undefined;
    const lineMismatchCount = readFirstFiniteNumber(
      selectedTarget?.lines?.summary?.mismatch_count,
      selectedTargetDiffCount,
      warnings.filter((warning) => String(warning).toLowerCase().includes('line')).length
    );

    row.localLineCount = Number.isFinite(localLineCount) ? localLineCount : 0;
    row.economicLineCount = Number.isFinite(economicLineCount) ? economicLineCount : null;
    row.lineMismatchCount = Number.isFinite(lineMismatchCount) ? lineMismatchCount : 0;
  }

  return row;
};

const sortCompareRows = (rows = []) => {
  const safeRows = Array.isArray(rows) ? [...rows] : [];
  return safeRows.sort((a, b) => {
    const statusWeight = (row) => {
      if (row?.status === 'mismatch') {
        return 0;
      }
      if (toNumber(row?.warningCount) > 0) {
        return 1;
      }
      return 2;
    };

    const weightDiff = statusWeight(a) - statusWeight(b);
    if (weightDiff !== 0) {
      return weightDiff;
    }

    const warningDiff = toNumber(b?.warningCount) - toNumber(a?.warningCount);
    if (warningDiff !== 0) {
      return warningDiff;
    }

    const differenceDiff = Math.abs(toNumber(b?.difference)) - Math.abs(toNumber(a?.difference));
    if (differenceDiff !== 0) {
      return differenceDiff;
    }

    return toNumber(a?.invoiceId) - toNumber(b?.invoiceId);
  });
};

const aggregateCompareRows = (rows = []) => {
  const safeRows = Array.isArray(rows) ? rows : [];
  const mismatches = safeRows.filter((row) => row.status === 'mismatch').length;
  const matched = safeRows.filter((row) => row.status === 'ok').length;
  const warningCount = safeRows.reduce((sum, row) => sum + toNumber(row.warningCount), 0);
  const totalDifference = safeRows.reduce((sum, row) => sum + toNumber(row.difference), 0);

  return {
    total: safeRows.length,
    mismatches,
    matched,
    warningCount,
    totalDifference: safeRoundCurrency(totalDifference),
  };
};

const chunkArray = (items = [], size = 5) => {
  const safeItems = Array.isArray(items) ? items : [];
  const safeSize = Math.max(1, Number(size) || 1);
  const chunks = [];
  for (let index = 0; index < safeItems.length; index += safeSize) {
    chunks.push(safeItems.slice(index, index + safeSize));
  }
  return chunks;
};

const _sfc_main$X = {
  __name: 'InvoiceDistributionTrendChart',
  props: {
  months: {
    type: Array,
    default: () => [],
  },
  labels: {
    type: Object,
    default: () => ({
      total: 'Total',
      booked: 'Booked',
      distribution: 'Distribution',
      customerPrices: 'Customer prices',
    }),
  },
  locale: {
    type: String,
    default: 'da-DK',
  },
  ariaLabel: {
    type: String,
    default: 'Distribution trend chart',
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

Chart$1.register(plugin_title, plugin_tooltip, plugin_legend, LineElement, PointElement, CategoryScale, LinearScale);

const props = __props;

const sortedMonths = computed(() => {
  return [...(Array.isArray(props.months) ? props.months : [])]
    .sort((a, b) => {
      if (a.year !== b.year) {
        return a.year - b.year;
      }
      return a.month - b.month;
    });
});

const chartData = computed(() => {
  const labels = sortedMonths.value.map((month) => getYearMonthLabel(month.year, month.month, props.locale));
  return {
    labels,
    datasets: [
      {
        label: props.labels.total,
        borderColor: '#1f77b4',
        backgroundColor: 'rgba(31,119,180,0.18)',
        data: sortedMonths.value.map((month) => toNumber(month.totalAmount)),
        tension: 0.25,
      },
      {
        label: props.labels.booked,
        borderColor: '#2ca02c',
        backgroundColor: 'rgba(44,160,44,0.18)',
        data: sortedMonths.value.map((month) => toNumber(month.bookedAmount)),
        tension: 0.25,
      },
      {
        label: props.labels.distribution,
        borderColor: '#ff7f0e',
        backgroundColor: 'rgba(255,127,14,0.18)',
        data: sortedMonths.value.map((month) => toNumber(month.distributionAmount)),
        tension: 0.25,
      },
      {
        label: props.labels.customerPrices,
        borderColor: '#c44536',
        backgroundColor: 'rgba(196,69,54,0.18)',
        data: sortedMonths.value.map((month) => toNumber(month.customerPriceAmount)),
        tension: 0.25,
      },
    ],
  };
});

const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  interaction: {
    mode: 'index',
    intersect: false,
  },
  plugins: {
    legend: {
      position: 'bottom',
    },
  },
  scales: {
    y: {
      beginAtZero: true,
    },
  },
};

const __returned__ = { props, sortedMonths, chartData, chartOptions, computed, get Line() { return Line }, get ChartJS() { return Chart$1 }, get Title() { return plugin_title }, get Tooltip() { return plugin_tooltip }, get Legend() { return plugin_legend }, get LineElement() { return LineElement }, get PointElement() { return PointElement }, get CategoryScale() { return CategoryScale }, get LinearScale() { return LinearScale }, get getYearMonthLabel() { return getYearMonthLabel }, get toNumber() { return toNumber } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$p = ["aria-label"];
const _hoisted_2$l = {
  key: 1,
  class: "chart-empty has-text-grey"
};

function _sfc_render$q(_ctx, _cache, $props, $setup, $data, $options) {
  return ($setup.sortedMonths.length)
    ? (openBlock(), createElementBlock("div", {
        key: 0,
        class: "chart-wrapper",
        role: "img",
        "aria-label": $props.ariaLabel
      }, [
        createVNode($setup["Line"], {
          data: $setup.chartData,
          options: $setup.chartOptions
        }, null, 8 /* PROPS */, ["data"])
      ], 8 /* PROPS */, _hoisted_1$p))
    : (openBlock(), createElementBlock("div", _hoisted_2$l, "-"))
}
const InvoiceDistributionTrendChart = /*#__PURE__*/_export_sfc(_sfc_main$X, [['render',_sfc_render$q],['__scopeId',"data-v-c6181524"],['__file',"InvoiceDistributionTrendChart.vue"]]);

const _sfc_main$W = {
  __name: 'InvoiceDistributionSkeleton',
  props: {
  rows: {
    type: Number,
    default: 6,
  },
},
  setup(__props, { expose: __expose }) {
  __expose();



const __returned__ = {  };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$o = { class: "skeleton-list" };

function _sfc_render$p(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$o, [
    (openBlock(true), createElementBlock(Fragment, null, renderList($props.rows, (index) => {
      return (openBlock(), createElementBlock("div", {
        key: index,
        class: "skeleton-row"
      }, [...(_cache[0] || (_cache[0] = [
        createBaseVNode("div", { class: "skeleton-block w-30" }, null, -1 /* CACHED */),
        createBaseVNode("div", { class: "skeleton-block w-20" }, null, -1 /* CACHED */),
        createBaseVNode("div", { class: "skeleton-block w-20" }, null, -1 /* CACHED */),
        createBaseVNode("div", { class: "skeleton-block w-20" }, null, -1 /* CACHED */)
      ]))]))
    }), 128 /* KEYED_FRAGMENT */))
  ]))
}
const InvoiceDistributionSkeleton = /*#__PURE__*/_export_sfc(_sfc_main$W, [['render',_sfc_render$p],['__scopeId',"data-v-e705b1a6"],['__file',"InvoiceDistributionSkeleton.vue"]]);

const DISTRIBUTION_ENDPOINTS = {
  v2All: '/superuser/invoicing/period/distribution/v2/all',
  v2FixedPricing: '/superuser/invoicing/period/distribution/v2/fixed-pricing',
  v2WashSubscriptions: '/superuser/invoicing/period/distribution/v2/wash-subscriptions',
  v2CustomerPrices: '/superuser/invoicing/period/distribution/v2/customer-prices',
  legacyFixedPricing: '/superuser/invoicing/period/distribution/fixed-pricing',
  legacyWashSubscriptions: '/superuser/invoicing/period/distribution/wash-subscriptions',
};

const COMPARE_ENDPOINTS = {
  v2Bulk: '/collected-invoices/economic/v2/compare/bulk',
  v2Single: '/collected-invoices/economic/v2/compare',
  legacySingle: '/collected-invoices/economic/compare',
};

const safeArray = (value) => (Array.isArray(value) ? value : []);
const uniqueStrings = (items = []) => Array.from(new Set(
  safeArray(items)
    .map((item) => String(item || '').trim())
    .filter((item) => item.length > 0)
));

const getResponseData = (response) => {
  return response?.data?.data ?? response?.data ?? response;
};

const getPagination = (response) => {
  return response?.data?.meta?.pagination || response?.meta?.pagination || null;
};

const toErrorMessage = (error) => {
  return SessionUser.functions.parseErrorMessage(error) || String(error?.message || error || 'Unknown error');
};

const joinReasonMessages = (...reasons) => uniqueStrings(reasons).join(' | ');
const waitForNextUiTick = () => new Promise((resolve) => setTimeout(resolve, 0));

const normalizeCategoryResponse = (category = {}, legacyCollectiveKey = null) => {
  const customers = safeArray(category?.customers || category?.data);
  const collectiveResults = (
    category?.collective_results
    || category?.includes?.[legacyCollectiveKey]
    || category?.includes?.collective_results
    || {}
  );
  const warnings = safeArray(category?.warnings);

  return {
    customers,
    collective_results: collectiveResults,
    warnings,
    // Keep legacy-compatible aliases for existing calculations and UI call sites.
    data: customers,
    includes: {
      ...(category?.includes || {}),
      collective_results: collectiveResults,
      ...(legacyCollectiveKey ? { [legacyCollectiveKey]: collectiveResults } : {}),
    },
    meta: category?.meta || {},
  };
};

const normalizeV2DistributionPayload = (payload = {}) => {
  const rawFixed = payload?.fixed_pricing || payload?.fixedPricing;
  const rawSubscriptions = payload?.wash_subscriptions || payload?.washSubscriptions;
  const rawCustomerPrices = payload?.customer_prices || payload?.customerPrices;

  if (!rawFixed || !rawSubscriptions || !rawCustomerPrices) {
    throw new Error('V2 distribution payload is missing one or more required categories');
  }

  return {
    fixedDistribution: normalizeCategoryResponse(rawFixed, 'collective_fixed_pricing_results'),
    subscriptionDistribution: normalizeCategoryResponse(rawSubscriptions, 'collective_subscription_results'),
    customerPriceDistribution: normalizeCategoryResponse(rawCustomerPrices, 'collective_customer_price_results'),
  };
};

const fetchDistributionCategoryForMonth = async ({
  year,
  month,
  endpoint,
  legacyCollectiveKey,
}) => {
  const { dateFrom, dateTo } = getMonthDateRange(year, month);
  const response = await SessionUser.request(endpoint, 'GET', {
    dateFrom,
    dateTo,
  });
  return normalizeCategoryResponse(getResponseData(response), legacyCollectiveKey);
};

const fetchV2FixedPricingDistributionForMonth = async (year, month) => {
  return fetchDistributionCategoryForMonth({
    year,
    month,
    endpoint: DISTRIBUTION_ENDPOINTS.v2FixedPricing,
    legacyCollectiveKey: 'collective_fixed_pricing_results',
  });
};

const fetchV2WashSubscriptionsDistributionForMonth = async (year, month) => {
  return fetchDistributionCategoryForMonth({
    year,
    month,
    endpoint: DISTRIBUTION_ENDPOINTS.v2WashSubscriptions,
    legacyCollectiveKey: 'collective_subscription_results',
  });
};

const fetchV2CustomerPricesDistributionForMonth = async (year, month) => {
  return fetchDistributionCategoryForMonth({
    year,
    month,
    endpoint: DISTRIBUTION_ENDPOINTS.v2CustomerPrices,
    legacyCollectiveKey: 'collective_customer_price_results',
  });
};

const fetchV2DistributionAllForMonth = async (year, month) => {
  const { dateFrom, dateTo } = getMonthDateRange(year, month);
  const response = await SessionUser.request(DISTRIBUTION_ENDPOINTS.v2All, 'GET', {
    dateFrom,
    dateTo,
  });

  return normalizeV2DistributionPayload(getResponseData(response));
};

const fetchV2DistributionCategoriesForMonth = async (year, month) => {
  const [fixedDistribution, subscriptionDistribution, customerPriceDistribution] = await Promise.all([
    fetchV2FixedPricingDistributionForMonth(year, month),
    fetchV2WashSubscriptionsDistributionForMonth(year, month),
    fetchV2CustomerPricesDistributionForMonth(year, month),
  ]);

  return {
    fixedDistribution,
    subscriptionDistribution,
    customerPriceDistribution,
  };
};

const fetchLegacyFixedPricingDistributionForMonth = async (year, month) => {
  return fetchDistributionCategoryForMonth({
    year,
    month,
    endpoint: DISTRIBUTION_ENDPOINTS.legacyFixedPricing,
    legacyCollectiveKey: 'collective_fixed_pricing_results',
  });
};

const fetchLegacyWashSubscriptionsDistributionForMonth = async (year, month) => {
  return fetchDistributionCategoryForMonth({
    year,
    month,
    endpoint: DISTRIBUTION_ENDPOINTS.legacyWashSubscriptions,
    legacyCollectiveKey: 'collective_subscription_results',
  });
};

const fetchLegacyDistributionForMonth = async (year, month) => {
  const [fixedDistribution, subscriptionDistribution] = await Promise.all([
    fetchLegacyFixedPricingDistributionForMonth(year, month),
    fetchLegacyWashSubscriptionsDistributionForMonth(year, month),
  ]);

  return {
    fixedDistribution,
    subscriptionDistribution,
    customerPriceDistribution: normalizeCategoryResponse({}, 'collective_customer_price_results'),
  };
};

const fetchDistributionForMonth = async (year, month) => {
  let v2AllError = null;

  try {
    const data = await fetchV2DistributionAllForMonth(year, month);
    return {
      ...data,
      fallback: {
        usedLegacyDistribution: false,
        usedSplitV2Distribution: false,
        distributionFallbackReason: null,
      },
    };
  } catch (error) {
    v2AllError = error;
  }

  try {
    const splitData = await fetchV2DistributionCategoriesForMonth(year, month);
    return {
      ...splitData,
      fallback: {
        usedLegacyDistribution: false,
        usedSplitV2Distribution: true,
        distributionFallbackReason: toErrorMessage(v2AllError),
      },
    };
  } catch (splitError) {
    console.warn('Falling back to legacy distribution endpoints', splitError);
    const legacyData = await fetchLegacyDistributionForMonth(year, month);
    return {
      ...legacyData,
      fallback: {
        usedLegacyDistribution: true,
        usedSplitV2Distribution: false,
        distributionFallbackReason: joinReasonMessages(
          toErrorMessage(v2AllError),
          toErrorMessage(splitError)
        ),
      },
    };
  }
};

const fetchFirstOrderDate = async () => {
  try {
    const response = await SessionUser.request('/orders', 'GET', {
      page: 1,
      limit: 1,
      order: 'created_at:asc',
    });
    const firstOrder = safeArray(getResponseData(response))[0];
    const firstCreatedAt = firstOrder?.created_at || firstOrder?.date || null;
    if (!firstCreatedAt) {
      return new Date();
    }
    const parsed = new Date(firstCreatedAt);
    if (Number.isNaN(parsed.getTime())) {
      return new Date();
    }
    return parsed;
  } catch (error) {
    console.warn('Unable to fetch first order date, falling back to current month', error);
    return new Date();
  }
};

const fetchPeriodForMonth = async (year, month) => {
  const { dateFrom, dateTo } = getMonthDateRange(year, month);
  const response = await SessionUser.request('/superuser/invoicing/period', 'GET', {
    dateFrom,
    dateTo,
  });
  return getResponseData(response);
};

const fetchMonthData = async (year, month) => {
  const [periodData, distributionData] = await Promise.all([
    fetchPeriodForMonth(year, month),
    fetchDistributionForMonth(year, month),
  ]);

  const summary = buildMonthSummary({
    year,
    month,
    periodData,
    fixedDistribution: distributionData.fixedDistribution,
    subscriptionDistribution: distributionData.subscriptionDistribution,
    customerPriceDistribution: distributionData.customerPriceDistribution,
  });

  return {
    summary,
    periodData,
    fixedDistribution: distributionData.fixedDistribution,
    subscriptionDistribution: distributionData.subscriptionDistribution,
    customerPriceDistribution: distributionData.customerPriceDistribution,
    fallback: distributionData.fallback,
  };
};

const fetchDistributionOverviewMonths = async ({
  fromDate,
  toDate = new Date(),
  onProgress = null,
}) => {
  const months = getMonthRange(fromDate, toDate, true);
  const results = [];

  for (let index = 0; index < months.length; index += 1) {
    const month = months[index];
    const monthData = await fetchMonthData(month.year, month.month);
    results.push({
      ...monthData.summary,
      fallback: monthData.fallback,
    });

    if (typeof onProgress === 'function') {
      onProgress({
        total: months.length,
        loaded: index + 1,
        key: month.key,
      });
    }
  }

  return results;
};

const fetchDepartmentPage = async (page, limit) => {
  return SessionUser.request('/departments', 'GET', {
    page,
    limit,
    order: 'id:asc',
  });
};

const fetchDepartments = async () => {
  const limit = 100;
  let page = 1;
  let hasMore = true;
  const departments = [];

  while (hasMore) {
    const response = await fetchDepartmentPage(page, limit);
    const pageData = safeArray(getResponseData(response));
    departments.push(...pageData);

    const pagination = getPagination(response);
    if (!pagination) {
      hasMore = false;
      continue;
    }

    const totalPages = Math.ceil(Number(pagination.total || 0) / Math.max(1, Number(pagination.per_page || limit)));
    hasMore = page < totalPages;
    page += 1;
  }

  return departments;
};

const fetchCollectedInvoicesForMonth = async (year, month) => {
  const { dateFrom, dateTo } = getMonthDateRange(year, month);
  const limit = 100;
  let page = 1;
  let hasMore = true;
  const invoices = [];

  while (hasMore) {
    const response = await SessionUser.request('/collected-invoices', 'GET', {
      page,
      limit,
      filters: `closed_at-date_from:${dateFrom},closed_at-date_to:${dateTo}`,
      order: 'closed_at:asc',
    });

    invoices.push(...safeArray(getResponseData(response)));

    const pagination = getPagination(response);
    if (!pagination) {
      hasMore = false;
      continue;
    }

    const totalPages = Math.ceil(Number(pagination.total || 0) / Math.max(1, Number(pagination.per_page || limit)));
    hasMore = page < totalPages;
    page += 1;
  }

  return invoices;
};

const compareCollectedInvoicesLegacy = async ({
  invoices,
  mode,
  onProgress,
  onRows,
  batchSize,
}) => {
  const rows = [];
  let processed = 0;
  const chunks = chunkArray(invoices, batchSize);

  for (const chunk of chunks) {
    const chunkResults = await Promise.all(chunk.map(async (invoice) => {
      try {
        const response = await SessionUser.request(COMPARE_ENDPOINTS.legacySingle, 'GET', {
          collected_invoice_id: Number(invoice?.id),
        });
        return normalizeCompareResult(invoice, getResponseData(response), mode);
      } catch (error) {
        const fallbackPayload = {
          collected_invoice_id: invoice?.id,
          warnings: [toErrorMessage(error)],
          internal_total: invoice?.total_net_amount || 0,
          booked_total: null,
          draft_total: null,
          difference: null,
          order_ids: [],
        };
        const normalized = normalizeCompareResult(invoice, fallbackPayload, mode);
        normalized.status = 'mismatch';
        return normalized;
      }
    }));

    for (const row of chunkResults) {
      rows.push(row);
      processed += 1;

      if (typeof onRows === 'function') {
        onRows([row]);
        await waitForNextUiTick();
      }

      if (typeof onProgress === 'function') {
        onProgress({
          total: invoices.length,
          processed,
        });
      }
    }
  }

  return rows;
};

const createCompareFallbackRow = (invoice, mode, warningMessage) => {
  const fallbackPayload = {
    collected_invoice_id: Number(invoice?.id) || null,
    warnings: uniqueStrings([warningMessage || 'Unable to compare invoice']),
    internal_total: invoice?.total_net_amount || 0,
    booked_total: null,
    draft_total: null,
    difference: null,
    order_ids: [],
  };
  const normalized = normalizeCompareResult(invoice, fallbackPayload, mode);
  normalized.status = 'mismatch';
  return normalized;
};

const compareInvoiceWithV2Single = async ({
  invoice,
  mode,
  fallbackWarning,
}) => {
  try {
    const response = await SessionUser.request(COMPARE_ENDPOINTS.v2Single, 'GET', {
      collected_invoice_id: Number(invoice?.id),
    });
    return normalizeCompareResult(invoice, getResponseData(response), mode);
  } catch (error) {
    return createCompareFallbackRow(
      invoice,
      mode,
      joinReasonMessages(fallbackWarning, toErrorMessage(error))
    );
  }
};

const compareCollectedInvoicesV2 = async ({
  invoices,
  mode,
  onProgress,
  onRows,
  batchSize,
}) => {
  const rows = [];
  let processed = 0;
  let usedSingleCompareFallback = false;
  let singleCompareFallbackReason = null;
  const safeBatchSize = Math.min(200, Math.max(1, Number(batchSize) || 1));
  const chunks = chunkArray(invoices, safeBatchSize);

  for (const chunk of chunks) {
    const ids = chunk
      .map((invoice) => Number(invoice?.id))
      .filter((id) => Number.isInteger(id) && id > 0);

    const unresolved = [];
    const chunkRows = [];

    const response = await SessionUser.request(COMPARE_ENDPOINTS.v2Bulk, 'POST', {
      collected_invoice_ids: ids,
    });
    const payload = getResponseData(response) || {};
    const resultRows = safeArray(payload?.results);
    const errors = safeArray(payload?.errors);
    const resultMap = new Map(resultRows.map((result) => [Number(result?.collected_invoice_id), result]));
    const errorMap = new Map(errors.map((entry) => [Number(entry?.collected_invoice_id), entry]));

    for (const invoice of chunk) {
      const invoiceId = Number(invoice?.id);
      const comparePayload = resultMap.get(invoiceId);
      if (comparePayload) {
        chunkRows.push(normalizeCompareResult(invoice, comparePayload, mode));
        continue;
      }

      unresolved.push({
        invoice,
        warning: errorMap.get(invoiceId)?.error || 'Missing comparison result from v2 bulk response',
      });
    }

    if (unresolved.length) {
      usedSingleCompareFallback = true;
      singleCompareFallbackReason = singleCompareFallbackReason || unresolved[0]?.warning || null;

      const recoveredRows = await Promise.all(unresolved.map(async ({ invoice, warning }) => {
        return compareInvoiceWithV2Single({
          invoice,
          mode,
          fallbackWarning: warning,
        });
      }));

      chunkRows.push(...recoveredRows);
    }

    for (const row of chunkRows) {
      rows.push(row);
      processed += 1;

      if (typeof onRows === 'function') {
        onRows([row]);
        await waitForNextUiTick();
      }

      if (typeof onProgress === 'function') {
        onProgress({
          total: invoices.length,
          processed,
        });
      }
    }
  }

  return {
    rows,
    usedSingleCompareFallback,
    singleCompareFallbackReason,
  };
};

const compareCollectedInvoicesForMonth = async ({
  year,
  month,
  mode = 'invoice_total',
  onProgress = null,
  onRows = null,
  batchSize = 100,
  legacyBatchSize = 5,
}) => {
  const invoices = await fetchCollectedInvoicesForMonth(year, month);
  if (!invoices.length) {
    return {
      rows: [],
      summary: aggregateCompareRows([]),
      invoiceCount: 0,
      fallback: {
        usedLegacyCompare: false,
        usedSingleCompareFallback: false,
        compareFallbackReason: null,
      },
    };
  }

  if (typeof onProgress === 'function') {
    onProgress({
      total: invoices.length,
      processed: 0,
    });
  }

  try {
    const result = await compareCollectedInvoicesV2({
      invoices,
      mode,
      onProgress,
      onRows,
      batchSize,
    });

    return {
      rows: result.rows,
      summary: aggregateCompareRows(result.rows),
      invoiceCount: invoices.length,
      fallback: {
        usedLegacyCompare: false,
        usedSingleCompareFallback: result.usedSingleCompareFallback,
        compareFallbackReason: result.singleCompareFallbackReason,
      },
    };
  } catch (error) {
    console.warn('Falling back to legacy compare endpoint', error);
    const rows = await compareCollectedInvoicesLegacy({
      invoices,
      mode,
      onProgress,
      onRows,
      batchSize: legacyBatchSize,
    });

    return {
      rows,
      summary: aggregateCompareRows(rows),
      invoiceCount: invoices.length,
      fallback: {
        usedLegacyCompare: true,
        usedSingleCompareFallback: false,
        compareFallbackReason: toErrorMessage(error),
      },
    };
  }
};

const _sfc_main$V = {
  __name: 'InvoiceDistributionOverview',
  setup(__props, { expose: __expose }) {
  __expose();

const { t, locale } = useI18n();

const monthSummaries = ref([]);
const loading = ref(false);
const errorMessage = ref('');
const loadProgress = ref({ loaded: 0, total: 0 });

const search = ref('');
const yearFilter = ref('all');
const sortKey = ref('month');
const sortDirection = ref('desc');

const availableYears = computed(() => {
  const years = new Set(monthSummaries.value.map((summary) => String(summary.year)));
  return ['all', ...Array.from(years).sort((a, b) => Number(b) - Number(a))];
});

const filteredMonthSummaries = computed(() => {
  const normalizedSearch = String(search.value || '').trim().toLowerCase();
  return monthSummaries.value.filter((summary) => {
    const monthLabel = getYearMonthLabel(summary.year, summary.month, locale.value);
    const searchMatch = !normalizedSearch || monthLabel.toLowerCase().includes(normalizedSearch);
    const yearMatch = yearFilter.value === 'all' || String(summary.year) === yearFilter.value;
    return searchMatch && yearMatch;
  });
});

const sortedMonthSummaries = computed(() => {
  return sortMonthSummaries(filteredMonthSummaries.value, sortKey.value, sortDirection.value);
});

const totals = computed(() => {
  return sortedMonthSummaries.value.reduce((acc, summary) => {
    acc.bookedAmount += toNumber(summary.bookedAmount);
    acc.distributionAmount += toNumber(summary.distributionAmount);
    acc.fixedPricingAmount += toNumber(summary.fixedPricingAmount);
    acc.subscriptionAmount += toNumber(summary.subscriptionAmount);
    acc.customerPriceAmount += toNumber(summary.customerPriceAmount);
    acc.totalAmount += toNumber(summary.totalAmount);
    return acc;
  }, {
    bookedAmount: 0,
    distributionAmount: 0,
    fixedPricingAmount: 0,
    subscriptionAmount: 0,
    customerPriceAmount: 0,
    totalAmount: 0,
  });
});

const totalComposition = computed(() => buildSourceComposition(totals.value));
const monthsUsingLegacyDistribution = computed(() => {
  return sortedMonthSummaries.value.filter((summary) => summary?.fallback?.usedLegacyDistribution);
});
const latestDistributionFallbackReason = computed(() => {
  const last = monthsUsingLegacyDistribution.value[0];
  return last?.fallback?.distributionFallbackReason || '';
});

const topMonths = computed(() => {
  return sortMonthSummaries(sortedMonthSummaries.value, 'total', 'desc').slice(0, 3);
});

const formatCurrency = (value) => SessionUser.functions.currency.toLocal(toNumber(value));
const formatPercent = (value) => `${Math.round(toNumber(value))}%`;

const getMonthLabel = (summary) => {
  return getYearMonthLabel(summary.year, summary.month, locale.value);
};

const getSortIcon = (column) => {
  if (sortKey.value !== column) {
    return 'fa-sort';
  }
  return sortDirection.value === 'asc' ? 'fa-sort-up' : 'fa-sort-down';
};

const getAriaSort = (column) => {
  if (sortKey.value !== column) {
    return 'none';
  }
  return sortDirection.value === 'asc' ? 'ascending' : 'descending';
};

const setSort = (column) => {
  if (sortKey.value === column) {
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc';
    return;
  }
  sortKey.value = column;
  sortDirection.value = 'desc';
};

const openMonthDetails = (summary) => {
  window.open(`/superuser/invoices/distribution/${summary.year}/${summary.month}`, '_blank');
};

const resetFilters = () => {
  search.value = '';
  yearFilter.value = 'all';
  sortKey.value = 'month';
  sortDirection.value = 'desc';
};

const loadOverview = async () => {
  loading.value = true;
  errorMessage.value = '';
  loadProgress.value = { loaded: 0, total: 0 };

  try {
    const firstOrderDate = await fetchFirstOrderDate();
    const summaries = await fetchDistributionOverviewMonths({
      fromDate: firstOrderDate,
      onProgress: (progress) => {
        loadProgress.value = progress;
      },
    });
    monthSummaries.value = summaries;
  } catch (error) {
    errorMessage.value = SessionUser.functions.parseErrorMessage(error) || String(error?.message || error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadOverview();
});

const __returned__ = { t, locale, monthSummaries, loading, errorMessage, loadProgress, search, yearFilter, sortKey, sortDirection, availableYears, filteredMonthSummaries, sortedMonthSummaries, totals, totalComposition, monthsUsingLegacyDistribution, latestDistributionFallbackReason, topMonths, formatCurrency, formatPercent, getMonthLabel, getSortIcon, getAriaSort, setSort, openMonthDetails, resetFilters, loadOverview, computed, onMounted, ref, get useI18n() { return useI18n }, SessionUser, InvoiceDistributionCard, InvoiceDistributionTrendChart, InvoiceDistributionSkeleton, get fetchDistributionOverviewMonths() { return fetchDistributionOverviewMonths }, get fetchFirstOrderDate() { return fetchFirstOrderDate }, get buildSourceComposition() { return buildSourceComposition }, get getYearMonthLabel() { return getYearMonthLabel }, get sortMonthSummaries() { return sortMonthSummaries }, get toNumber() { return toNumber } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$n = {
  class: "distribution-overview distribution-overview-v2",
  "data-testid": "distribution-overview-page"
};
const _hoisted_2$k = { class: "overview-header__top hero-row" };
const _hoisted_3$k = { class: "title is-4 mb-1" };
const _hoisted_4$k = { class: "subtitle is-6 mb-0" };
const _hoisted_5$j = { class: "control-toolbar mt-4 overview-dock" };
const _hoisted_6$j = ["value"];
const _hoisted_7$i = {
  class: "toolbar-hint",
  role: "status",
  "aria-live": "polite"
};
const _hoisted_8$i = { class: "toolbar-hint__title" };
const _hoisted_9$h = { class: "toolbar-hint__subtitle" };
const _hoisted_10$g = { class: "error-state__content" };
const _hoisted_11$d = {
  class: "fallback-note",
  "data-testid": "distribution-overview-legacy-fallback-warning"
};
const _hoisted_12$c = {
  key: 0,
  class: "is-size-7"
};
const _hoisted_13$b = { class: "progress-meta mb-3" };
const _hoisted_14$b = {
  class: "kpi-strip",
  "aria-label": "KPI summary"
};
const _hoisted_15$b = { class: "metric-title" };
const _hoisted_16$b = { class: "metric-value" };
const _hoisted_17$9 = { class: "metric-title" };
const _hoisted_18$9 = { class: "metric-value" };
const _hoisted_19$8 = { class: "metric-title" };
const _hoisted_20$7 = { class: "metric-value" };
const _hoisted_21$7 = { class: "metric-title" };
const _hoisted_22$7 = { class: "metric-value" };
const _hoisted_23$7 = { class: "metric-title" };
const _hoisted_24$7 = { class: "metric-value" };
const _hoisted_25$7 = { class: "section-header" };
const _hoisted_26$7 = { class: "title is-6 mb-0" };
const _hoisted_27$7 = { class: "section-header" };
const _hoisted_28$7 = { class: "title is-6 mb-0" };
const _hoisted_29$6 = {
  key: 0,
  class: "empty-state has-text-centered"
};
const _hoisted_30$6 = { class: "has-text-grey mb-3" };
const _hoisted_31$6 = {
  key: 1,
  class: "table-container table-container--scroll"
};
const _hoisted_32$6 = { class: "table is-fullwidth is-hoverable is-striped distribution-table" };
const _hoisted_33$6 = ["aria-sort"];
const _hoisted_34$6 = { class: "icon is-small" };
const _hoisted_35$6 = {
  scope: "col",
  class: "has-text-right"
};
const _hoisted_36$5 = {
  scope: "col",
  class: "has-text-right"
};
const _hoisted_37$5 = {
  scope: "col",
  class: "has-text-right"
};
const _hoisted_38$5 = {
  scope: "col",
  class: "has-text-right"
};
const _hoisted_39$5 = {
  scope: "col",
  class: "has-text-right"
};
const _hoisted_40$5 = ["aria-sort"];
const _hoisted_41$5 = { class: "icon is-small" };
const _hoisted_42$5 = { scope: "col" };
const _hoisted_43$5 = { scope: "col" };
const _hoisted_44$5 = { scope: "row" };
const _hoisted_45$5 = { class: "has-text-right is-family-monospace" };
const _hoisted_46$5 = { class: "has-text-right is-family-monospace" };
const _hoisted_47$5 = { class: "has-text-right is-family-monospace" };
const _hoisted_48$5 = { class: "has-text-right is-family-monospace" };
const _hoisted_49$4 = { class: "has-text-right is-family-monospace" };
const _hoisted_50$4 = { class: "has-text-right is-family-monospace" };
const _hoisted_51$4 = { class: "source-composition" };
const _hoisted_52$4 = ["aria-label"];
const _hoisted_53$3 = { class: "is-size-7 has-text-grey" };
const _hoisted_54$3 = {
  class: "insights-grid",
  "aria-label": "Secondary insights"
};
const _hoisted_55$3 = { class: "title is-6 mb-3" };
const _hoisted_56$3 = { class: "insight-row" };
const _hoisted_57$3 = { class: "insight-row" };
const _hoisted_58$3 = { class: "insight-row" };
const _hoisted_59$2 = { class: "title is-6 mb-3" };
const _hoisted_60$2 = {
  key: 0,
  class: "top-month-list"
};
const _hoisted_61$2 = { class: "has-text-weight-semibold" };
const _hoisted_62$2 = {
  key: 1,
  class: "has-text-grey"
};

function _sfc_render$o(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_b_button = resolveComponent("b-button");
  const _component_b_input = resolveComponent("b-input");
  const _component_b_field = resolveComponent("b-field");
  const _component_b_select = resolveComponent("b-select");
  const _component_b_message = resolveComponent("b-message");
  const _component_b_progress = resolveComponent("b-progress");

  return (openBlock(), createElementBlock("div", _hoisted_1$n, [
    createVNode($setup["InvoiceDistributionCard"], { class: "overview-header hero-surface" }, {
      default: withCtx(() => [
        createBaseVNode("div", _hoisted_2$k, [
          createBaseVNode("div", null, [
            _cache[4] || (_cache[4] = createBaseVNode("p", { class: "eyebrow" }, "Superuser • Revenue Intelligence", -1 /* CACHED */)),
            createBaseVNode("h2", _hoisted_3$k, toDisplayString($setup.t('superuser_invoice_distribution.overview.title')), 1 /* TEXT */),
            createBaseVNode("p", _hoisted_4$k, toDisplayString($setup.t('superuser_invoice_distribution.overview.subtitle')), 1 /* TEXT */)
          ]),
          createVNode(_component_b_button, {
            type: "is-dark",
            class: "control-button",
            loading: $setup.loading,
            "aria-label": $setup.t('superuser_invoice_distribution.actions.reload'),
            onClick: $setup.loadOverview,
            "icon-pack": "fas",
            "icon-left": "sync-alt",
            "data-testid": "distribution-overview-refresh"
          }, {
            default: withCtx(() => [
              createTextVNode(toDisplayString($setup.t('superuser_invoice_distribution.actions.reload')), 1 /* TEXT */)
            ]),
            _: 1 /* STABLE */
          }, 8 /* PROPS */, ["loading", "aria-label"])
        ]),
        createBaseVNode("div", _hoisted_5$j, [
          createVNode(_component_b_field, {
            label: $setup.t('superuser_invoice_distribution.filters.search'),
            class: "toolbar-field"
          }, {
            default: withCtx(() => [
              createVNode(_component_b_input, {
                modelValue: $setup.search,
                "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (($setup.search) = $event)),
                placeholder: $setup.t('superuser_invoice_distribution.filters.search_placeholder'),
                icon: "search",
                "icon-pack": "fas",
                "aria-label": $setup.t('superuser_invoice_distribution.filters.search')
              }, null, 8 /* PROPS */, ["modelValue", "placeholder", "aria-label"])
            ]),
            _: 1 /* STABLE */
          }, 8 /* PROPS */, ["label"]),
          createVNode(_component_b_field, {
            label: $setup.t('superuser_invoice_distribution.filters.year'),
            class: "toolbar-field"
          }, {
            default: withCtx(() => [
              createVNode(_component_b_select, {
                modelValue: $setup.yearFilter,
                "onUpdate:modelValue": _cache[1] || (_cache[1] = $event => (($setup.yearFilter) = $event)),
                expanded: "",
                "aria-label": $setup.t('superuser_invoice_distribution.filters.year')
              }, {
                default: withCtx(() => [
                  (openBlock(true), createElementBlock(Fragment, null, renderList($setup.availableYears, (yearOption) => {
                    return (openBlock(), createElementBlock("option", {
                      key: yearOption,
                      value: yearOption
                    }, toDisplayString(yearOption === 'all' ? $setup.t('superuser_invoice_distribution.filters.all_years') : yearOption), 9 /* TEXT, PROPS */, _hoisted_6$j))
                  }), 128 /* KEYED_FRAGMENT */))
                ]),
                _: 1 /* STABLE */
              }, 8 /* PROPS */, ["modelValue", "aria-label"])
            ]),
            _: 1 /* STABLE */
          }, 8 /* PROPS */, ["label"]),
          createBaseVNode("div", _hoisted_7$i, [
            createBaseVNode("p", _hoisted_8$i, toDisplayString($setup.t('superuser_invoice_distribution.overview.loaded_months', { loaded: $setup.sortedMonthSummaries.length })), 1 /* TEXT */),
            createBaseVNode("p", _hoisted_9$h, toDisplayString($setup.t('superuser_invoice_distribution.tooltips.summary')), 1 /* TEXT */)
          ])
        ])
      ]),
      _: 1 /* STABLE */
    }),
    ($setup.errorMessage)
      ? (openBlock(), createBlock(_component_b_message, {
          key: 0,
          type: "is-danger",
          "has-icon": "",
          "icon-pack": "fas",
          class: "mb-0"
        }, {
          default: withCtx(() => [
            createBaseVNode("div", _hoisted_10$g, [
              createBaseVNode("p", null, toDisplayString($setup.t('superuser_invoice_distribution.errors.overview_load_failed')) + ": " + toDisplayString($setup.errorMessage), 1 /* TEXT */),
              createVNode(_component_b_button, {
                type: "is-danger",
                class: "control-button is-light",
                onClick: $setup.loadOverview
              }, {
                default: withCtx(() => [
                  createTextVNode(toDisplayString($setup.t('superuser_invoice_distribution.actions.try_again')), 1 /* TEXT */)
                ]),
                _: 1 /* STABLE */
              })
            ])
          ]),
          _: 1 /* STABLE */
        }))
      : createCommentVNode("v-if", true),
    (!$setup.loading && $setup.monthsUsingLegacyDistribution.length)
      ? (openBlock(), createBlock(_component_b_message, {
          key: 1,
          type: "is-warning",
          "has-icon": "",
          "icon-pack": "fas",
          class: "mb-0"
        }, {
          default: withCtx(() => [
            createBaseVNode("div", _hoisted_11$d, [
              createBaseVNode("p", null, toDisplayString($setup.t('superuser_invoice_distribution.warnings.legacy_distribution_fallback', { count: $setup.monthsUsingLegacyDistribution.length })), 1 /* TEXT */),
              ($setup.latestDistributionFallbackReason)
                ? (openBlock(), createElementBlock("p", _hoisted_12$c, toDisplayString($setup.latestDistributionFallbackReason), 1 /* TEXT */))
                : createCommentVNode("v-if", true)
            ])
          ]),
          _: 1 /* STABLE */
        }))
      : createCommentVNode("v-if", true),
    ($setup.loading)
      ? (openBlock(), createBlock($setup["InvoiceDistributionCard"], { key: 2 }, {
          default: withCtx(() => [
            createBaseVNode("div", _hoisted_13$b, [
              createBaseVNode("span", null, toDisplayString($setup.t('superuser_invoice_distribution.loading.loading_months', { loaded: $setup.loadProgress.loaded, total: $setup.loadProgress.total })), 1 /* TEXT */)
            ]),
            createVNode(_component_b_progress, {
              type: "is-primary",
              size: "is-small",
              value: $setup.loadProgress.loaded,
              max: Math.max($setup.loadProgress.total, 1),
              "aria-label": "Loading distribution overview"
            }, null, 8 /* PROPS */, ["value", "max"]),
            createVNode($setup["InvoiceDistributionSkeleton"], { rows: 7 })
          ]),
          _: 1 /* STABLE */
        }))
      : (openBlock(), createElementBlock(Fragment, { key: 3 }, [
          createBaseVNode("section", _hoisted_14$b, [
            createVNode($setup["InvoiceDistributionCard"], { class: "metric-card metric-total" }, {
              default: withCtx(() => [
                createBaseVNode("p", _hoisted_15$b, toDisplayString($setup.t('superuser_invoice_distribution.metrics.total')), 1 /* TEXT */),
                createBaseVNode("p", _hoisted_16$b, toDisplayString($setup.formatCurrency($setup.totals.totalAmount)), 1 /* TEXT */)
              ]),
              _: 1 /* STABLE */
            }),
            createVNode($setup["InvoiceDistributionCard"], { class: "metric-card metric-booked" }, {
              default: withCtx(() => [
                createBaseVNode("p", _hoisted_17$9, toDisplayString($setup.t('superuser_invoice_distribution.metrics.booked')), 1 /* TEXT */),
                createBaseVNode("p", _hoisted_18$9, toDisplayString($setup.formatCurrency($setup.totals.bookedAmount)), 1 /* TEXT */)
              ]),
              _: 1 /* STABLE */
            }),
            createVNode($setup["InvoiceDistributionCard"], { class: "metric-card metric-distribution" }, {
              default: withCtx(() => [
                createBaseVNode("p", _hoisted_19$8, toDisplayString($setup.t('superuser_invoice_distribution.metrics.distribution')), 1 /* TEXT */),
                createBaseVNode("p", _hoisted_20$7, toDisplayString($setup.formatCurrency($setup.totals.distributionAmount)), 1 /* TEXT */)
              ]),
              _: 1 /* STABLE */
            }),
            createVNode($setup["InvoiceDistributionCard"], { class: "metric-card metric-customer-prices" }, {
              default: withCtx(() => [
                createBaseVNode("p", _hoisted_21$7, toDisplayString($setup.t('superuser_invoice_distribution.metrics.customer_prices')), 1 /* TEXT */),
                createBaseVNode("p", _hoisted_22$7, toDisplayString($setup.formatCurrency($setup.totals.customerPriceAmount)), 1 /* TEXT */)
              ]),
              _: 1 /* STABLE */
            }),
            createVNode($setup["InvoiceDistributionCard"], { class: "metric-card metric-months" }, {
              default: withCtx(() => [
                createBaseVNode("p", _hoisted_23$7, toDisplayString($setup.t('superuser_invoice_distribution.metrics.months')), 1 /* TEXT */),
                createBaseVNode("p", _hoisted_24$7, toDisplayString($setup.sortedMonthSummaries.length), 1 /* TEXT */)
              ]),
              _: 1 /* STABLE */
            })
          ]),
          createVNode($setup["InvoiceDistributionCard"], { class: "chart-section" }, {
            default: withCtx(() => [
              createBaseVNode("div", _hoisted_25$7, [
                createBaseVNode("h3", _hoisted_26$7, toDisplayString($setup.t('superuser_invoice_distribution.sections.trend')), 1 /* TEXT */)
              ]),
              createVNode($setup["InvoiceDistributionTrendChart"], {
                months: $setup.sortedMonthSummaries,
                locale: $setup.locale,
                "aria-label": $setup.t('superuser_invoice_distribution.aria.trend_chart'),
                labels: {
            total: $setup.t('superuser_invoice_distribution.metrics.total'),
            booked: $setup.t('superuser_invoice_distribution.metrics.booked'),
            distribution: $setup.t('superuser_invoice_distribution.metrics.distribution'),
            customerPrices: $setup.t('superuser_invoice_distribution.metrics.customer_prices'),
          }
              }, null, 8 /* PROPS */, ["months", "locale", "aria-label", "labels"])
            ]),
            _: 1 /* STABLE */
          }),
          createVNode($setup["InvoiceDistributionCard"], null, {
            default: withCtx(() => [
              createBaseVNode("div", _hoisted_27$7, [
                createBaseVNode("h3", _hoisted_28$7, toDisplayString($setup.t('superuser_invoice_distribution.sections.month_table')), 1 /* TEXT */),
                createVNode(_component_b_button, {
                  size: "is-small",
                  type: "is-light",
                  class: "control-button",
                  onClick: $setup.resetFilters
                }, {
                  default: withCtx(() => [
                    createTextVNode(toDisplayString($setup.t('superuser_invoice_distribution.actions.reset_filters')), 1 /* TEXT */)
                  ]),
                  _: 1 /* STABLE */
                })
              ]),
              (!$setup.sortedMonthSummaries.length)
                ? (openBlock(), createElementBlock("div", _hoisted_29$6, [
                    createBaseVNode("p", _hoisted_30$6, toDisplayString($setup.t('superuser_invoice_distribution.empty.no_months')), 1 /* TEXT */),
                    createVNode(_component_b_button, {
                      type: "is-link",
                      class: "control-button is-light",
                      onClick: $setup.loadOverview
                    }, {
                      default: withCtx(() => [
                        createTextVNode(toDisplayString($setup.t('common.retry')), 1 /* TEXT */)
                      ]),
                      _: 1 /* STABLE */
                    })
                  ]))
                : (openBlock(), createElementBlock("div", _hoisted_31$6, [
                    createBaseVNode("table", _hoisted_32$6, [
                      createBaseVNode("caption", null, toDisplayString($setup.t('superuser_invoice_distribution.aria.month_table_caption')), 1 /* TEXT */),
                      createBaseVNode("thead", null, [
                        createBaseVNode("tr", null, [
                          createBaseVNode("th", {
                            scope: "col",
                            "aria-sort": $setup.getAriaSort('month')
                          }, [
                            createVNode(_component_b_button, {
                              type: "is-text",
                              size: "is-small",
                              class: "table-sort",
                              onClick: _cache[2] || (_cache[2] = $event => ($setup.setSort('month'))),
                              "aria-label": $setup.t('superuser_invoice_distribution.aria.sort_month')
                            }, {
                              default: withCtx(() => [
                                createBaseVNode("span", null, toDisplayString($setup.t('superuser_invoice_distribution.table.month')), 1 /* TEXT */),
                                createBaseVNode("span", _hoisted_34$6, [
                                  createBaseVNode("i", {
                                    class: normalizeClass(["fas", $setup.getSortIcon('month')])
                                  }, null, 2 /* CLASS */)
                                ])
                              ]),
                              _: 1 /* STABLE */
                            }, 8 /* PROPS */, ["aria-label"])
                          ], 8 /* PROPS */, _hoisted_33$6),
                          createBaseVNode("th", _hoisted_35$6, toDisplayString($setup.t('superuser_invoice_distribution.table.booked')), 1 /* TEXT */),
                          createBaseVNode("th", _hoisted_36$5, toDisplayString($setup.t('superuser_invoice_distribution.table.fixed_pricing')), 1 /* TEXT */),
                          createBaseVNode("th", _hoisted_37$5, toDisplayString($setup.t('superuser_invoice_distribution.table.subscriptions')), 1 /* TEXT */),
                          createBaseVNode("th", _hoisted_38$5, toDisplayString($setup.t('superuser_invoice_distribution.table.customer_prices')), 1 /* TEXT */),
                          createBaseVNode("th", _hoisted_39$5, toDisplayString($setup.t('superuser_invoice_distribution.table.distribution')), 1 /* TEXT */),
                          createBaseVNode("th", {
                            scope: "col",
                            "aria-sort": $setup.getAriaSort('total'),
                            class: "has-text-right"
                          }, [
                            createVNode(_component_b_button, {
                              type: "is-text",
                              size: "is-small",
                              class: "table-sort table-sort--right",
                              onClick: _cache[3] || (_cache[3] = $event => ($setup.setSort('total'))),
                              "aria-label": $setup.t('superuser_invoice_distribution.aria.sort_total')
                            }, {
                              default: withCtx(() => [
                                createBaseVNode("span", null, toDisplayString($setup.t('superuser_invoice_distribution.table.total')), 1 /* TEXT */),
                                createBaseVNode("span", _hoisted_41$5, [
                                  createBaseVNode("i", {
                                    class: normalizeClass(["fas", $setup.getSortIcon('total')])
                                  }, null, 2 /* CLASS */)
                                ])
                              ]),
                              _: 1 /* STABLE */
                            }, 8 /* PROPS */, ["aria-label"])
                          ], 8 /* PROPS */, _hoisted_40$5),
                          createBaseVNode("th", _hoisted_42$5, toDisplayString($setup.t('superuser_invoice_distribution.table.source_mix')), 1 /* TEXT */),
                          createBaseVNode("th", _hoisted_43$5, toDisplayString($setup.t('superuser_invoice_distribution.table.actions')), 1 /* TEXT */)
                        ])
                      ]),
                      createBaseVNode("tbody", null, [
                        (openBlock(true), createElementBlock(Fragment, null, renderList($setup.sortedMonthSummaries, (summary) => {
                          return (openBlock(), createElementBlock("tr", {
                            key: summary.key
                          }, [
                            createBaseVNode("th", _hoisted_44$5, toDisplayString($setup.getMonthLabel(summary)), 1 /* TEXT */),
                            createBaseVNode("td", _hoisted_45$5, toDisplayString($setup.formatCurrency(summary.bookedAmount)), 1 /* TEXT */),
                            createBaseVNode("td", _hoisted_46$5, toDisplayString($setup.formatCurrency(summary.fixedPricingAmount)), 1 /* TEXT */),
                            createBaseVNode("td", _hoisted_47$5, toDisplayString($setup.formatCurrency(summary.subscriptionAmount)), 1 /* TEXT */),
                            createBaseVNode("td", _hoisted_48$5, toDisplayString($setup.formatCurrency(summary.customerPriceAmount)), 1 /* TEXT */),
                            createBaseVNode("td", _hoisted_49$4, toDisplayString($setup.formatCurrency(summary.distributionAmount)), 1 /* TEXT */),
                            createBaseVNode("td", _hoisted_50$4, toDisplayString($setup.formatCurrency(summary.totalAmount)), 1 /* TEXT */),
                            createBaseVNode("td", null, [
                              createBaseVNode("div", _hoisted_51$4, [
                                createBaseVNode("div", {
                                  class: "source-composition__bar",
                                  "aria-label": $setup.t('superuser_invoice_distribution.aria.source_mix_row', { month: $setup.getMonthLabel(summary) })
                                }, [
                                  createBaseVNode("span", {
                                    class: "source-composition__segment source-composition__segment--fixed",
                                    style: normalizeStyle({ width: `${$setup.buildSourceComposition(summary).fixedPercent}%` })
                                  }, null, 4 /* STYLE */),
                                  createBaseVNode("span", {
                                    class: "source-composition__segment source-composition__segment--subscription",
                                    style: normalizeStyle({ width: `${$setup.buildSourceComposition(summary).subscriptionPercent}%` })
                                  }, null, 4 /* STYLE */),
                                  createBaseVNode("span", {
                                    class: "source-composition__segment source-composition__segment--customer-prices",
                                    style: normalizeStyle({ width: `${$setup.buildSourceComposition(summary).customerPricePercent}%` })
                                  }, null, 4 /* STYLE */)
                                ], 8 /* PROPS */, _hoisted_52$4),
                                createBaseVNode("span", _hoisted_53$3, toDisplayString($setup.formatPercent($setup.buildSourceComposition(summary).fixedPercent)) + " / " + toDisplayString($setup.formatPercent($setup.buildSourceComposition(summary).subscriptionPercent)) + " / " + toDisplayString($setup.formatPercent($setup.buildSourceComposition(summary).customerPricePercent)), 1 /* TEXT */)
                              ])
                            ]),
                            createBaseVNode("td", null, [
                              createVNode(_component_b_button, {
                                size: "is-small",
                                type: "is-link",
                                class: "control-button is-light",
                                onClick: $event => ($setup.openMonthDetails(summary)),
                                "aria-label": $setup.t('superuser_invoice_distribution.aria.open_month', { month: $setup.getMonthLabel(summary) }),
                                "icon-pack": "fas",
                                "icon-left": "external-link-alt",
                                "data-testid": "distribution-overview-open-month"
                              }, {
                                default: withCtx(() => [
                                  createTextVNode(toDisplayString($setup.t('superuser_invoice_distribution.actions.open_month')), 1 /* TEXT */)
                                ]),
                                _: 1 /* STABLE */
                              }, 8 /* PROPS */, ["onClick", "aria-label"])
                            ])
                          ]))
                        }), 128 /* KEYED_FRAGMENT */))
                      ])
                    ])
                  ]))
            ]),
            _: 1 /* STABLE */
          }),
          createBaseVNode("section", _hoisted_54$3, [
            createVNode($setup["InvoiceDistributionCard"], { class: "insight-card" }, {
              default: withCtx(() => [
                createBaseVNode("h3", _hoisted_55$3, toDisplayString($setup.t('superuser_invoice_distribution.sections.source_blend')), 1 /* TEXT */),
                createBaseVNode("div", _hoisted_56$3, [
                  createBaseVNode("span", null, toDisplayString($setup.t('superuser_invoice_distribution.metrics.fixed_pricing')), 1 /* TEXT */),
                  createBaseVNode("strong", null, toDisplayString($setup.formatCurrency($setup.totalComposition.fixedAmount)) + " (" + toDisplayString($setup.formatPercent($setup.totalComposition.fixedPercent)) + ")", 1 /* TEXT */)
                ]),
                createBaseVNode("div", _hoisted_57$3, [
                  createBaseVNode("span", null, toDisplayString($setup.t('superuser_invoice_distribution.metrics.subscriptions')), 1 /* TEXT */),
                  createBaseVNode("strong", null, toDisplayString($setup.formatCurrency($setup.totalComposition.subscriptionAmount)) + " (" + toDisplayString($setup.formatPercent($setup.totalComposition.subscriptionPercent)) + ")", 1 /* TEXT */)
                ]),
                createBaseVNode("div", _hoisted_58$3, [
                  createBaseVNode("span", null, toDisplayString($setup.t('superuser_invoice_distribution.metrics.customer_prices')), 1 /* TEXT */),
                  createBaseVNode("strong", null, toDisplayString($setup.formatCurrency($setup.totalComposition.customerPriceAmount)) + " (" + toDisplayString($setup.formatPercent($setup.totalComposition.customerPricePercent)) + ")", 1 /* TEXT */)
                ])
              ]),
              _: 1 /* STABLE */
            }),
            createVNode($setup["InvoiceDistributionCard"], { class: "insight-card" }, {
              default: withCtx(() => [
                createBaseVNode("h3", _hoisted_59$2, toDisplayString($setup.t('superuser_invoice_distribution.sections.top_months')), 1 /* TEXT */),
                ($setup.topMonths.length)
                  ? (openBlock(), createElementBlock("div", _hoisted_60$2, [
                      (openBlock(true), createElementBlock(Fragment, null, renderList($setup.topMonths, (summary) => {
                        return (openBlock(), createBlock(_component_b_button, {
                          key: summary.key,
                          size: "is-small",
                          type: "is-light",
                          class: "top-month-button control-button",
                          onClick: $event => ($setup.openMonthDetails(summary))
                        }, {
                          default: withCtx(() => [
                            createBaseVNode("span", null, toDisplayString($setup.getMonthLabel(summary)), 1 /* TEXT */),
                            createBaseVNode("span", _hoisted_61$2, toDisplayString($setup.formatCurrency(summary.totalAmount)), 1 /* TEXT */)
                          ]),
                          _: 2 /* DYNAMIC */
                        }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["onClick"]))
                      }), 128 /* KEYED_FRAGMENT */))
                    ]))
                  : (openBlock(), createElementBlock("p", _hoisted_62$2, toDisplayString($setup.t('superuser_invoice_distribution.empty.no_months')), 1 /* TEXT */))
              ]),
              _: 1 /* STABLE */
            })
          ])
        ], 64 /* STABLE_FRAGMENT */))
  ]))
}
const InvoiceDistributionOverview = /*#__PURE__*/_export_sfc(_sfc_main$V, [['render',_sfc_render$o],['__scopeId',"data-v-f7525089"],['__file',"InvoiceDistributionOverview.vue"]]);

const DEFAULT_LIMIT = 50;
const MANUAL_RUN_LIMIT = 10;
const POLL_INTERVAL_MS = 4000;


const _sfc_main$U = {
  __name: 'CollectedOrderInvoicesQueueHistory',
  setup(__props, { expose: __expose }) {
  __expose();

const ACTIVE_STATUSES = new Set([
  ECONOMIC_QUEUE_STATUS.QUEUED,
  ECONOMIC_QUEUE_STATUS.PROCESSING,
]);
const statusFilter = ref("");
const limitFilter = ref(DEFAULT_LIMIT);
const offsetFilter = ref(0);

const jobs = ref([]);
const total = ref(0);
const hasMore = ref(false);
const loading = ref(false);
const refreshing = ref(false);
const runningQueue = ref(false);
const errorMessage = ref("");
const pollErrorMessage = ref("");
const manualRunUnavailable = ref(false);
const runSummary = ref(null);
const retryingJobIds = ref([]);
const selectedJob = ref(null);

let pollTimer = null;
let loadPromise = null;
let isMounted = false;
let pendingLoadAfterCurrent = false;
let pendingLoadSilent = true;
let pendingLoadIsPoll = true;

const queuePendingLoad = ({ silent = false, isPoll = false } = {}) => {
  pendingLoadAfterCurrent = true;
  pendingLoadSilent = pendingLoadSilent && silent;
  pendingLoadIsPoll = pendingLoadIsPoll && isPoll;
};

const takePendingLoad = () => {
  if (!pendingLoadAfterCurrent || !isMounted) {
    pendingLoadAfterCurrent = false;
    pendingLoadSilent = true;
    pendingLoadIsPoll = true;
    return null;
  }

  const pendingLoad = {
    silent: pendingLoadSilent,
    isPoll: pendingLoadIsPoll,
  };

  pendingLoadAfterCurrent = false;
  pendingLoadSilent = true;
  pendingLoadIsPoll = true;

  return pendingLoad;
};

const toPositiveInt = (value, fallback = null) => {
  const parsed = Number.parseInt(String(value), 10);
  if (!Number.isInteger(parsed) || parsed < 1) {
    return fallback;
  }
  return parsed;
};

const toNonNegativeInt = (value, fallback = 0) => {
  const parsed = Number.parseInt(String(value), 10);
  if (!Number.isInteger(parsed) || parsed < 0) {
    return fallback;
  }
  return parsed;
};

const formatDateTime = (value) => {
  if (!value) {
    return "-";
  }

  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return String(value);
  }

  return new Intl.DateTimeFormat("da-DK", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  }).format(parsed);
};

const formatScalar = (value, fallback = "-") => {
  if (value === null || value === undefined || value === "") {
    return fallback;
  }
  if (typeof value === "boolean") {
    return value ? "Ja" : "Nej";
  }
  return String(value);
};

const formatJson = (value) => {
  if (value === null || value === undefined) {
    return "{}";
  }

  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return String(value);
  }
};

const formatMoney = (value) => {
  const amount = Number(value);
  if (!Number.isFinite(amount)) {
    return "-";
  }
  return `${amount.toFixed(2)} DKK`;
};

const buildLocalFallbackSummary = (rawJob) => {
  const payload = rawJob?.payload && typeof rawJob.payload === "object"
    ? rawJob.payload
    : {};
  const result = rawJob?.result && typeof rawJob.result === "object"
    ? rawJob.result
    : {};

  return {
    message: rawJob?.error_message || result?.message || rawJob?.progress_message || "Ingen detaljer endnu.",
    target: {
      collected_invoice_id: toPositiveInt(
        rawJob?.collected_invoice_id ?? payload?.collected_invoice_id,
        null,
      ),
      send_as_is: Boolean(payload?.send_as_is ?? false),
      requested_by: toPositiveInt(payload?.requested_by ?? rawJob?.created_by, null),
    },
    customer: {
      customer_number: toPositiveInt(
        result?.customer_number ?? result?.customer?.customer_number,
        null,
      ),
      name: result?.customer_name ?? result?.customer?.name ?? null,
    },
    outcome: {
      status: rawJob?.status ?? null,
      economic_invoice_draft_id: toPositiveInt(
        result?.economic_invoice_draft_id ?? result?.draft_id,
        null,
      ),
      economic_invoice_booked_id: toPositiveInt(
        result?.economic_invoice_booked_id ?? result?.booked_id,
        null,
      ),
      external_id: result?.external_id ?? null,
      total_net_amount: result?.total_net_amount ?? null,
      order_count: toNonNegativeInt(
        result?.order_count ?? (Array.isArray(result?.order_ids) ? result.order_ids.length : null),
        0,
      ),
      error_message: rawJob?.error_message ?? null,
    },
    transfer: {
      transfer_type: rawJob?.transfer_type ?? null,
      status: rawJob?.status ?? null,
      progress_percent: toNonNegativeInt(rawJob?.progress_percent, 0),
      progress_message: rawJob?.progress_message ?? null,
      attempts: toNonNegativeInt(rawJob?.attempts, 0),
      max_attempts: toNonNegativeInt(rawJob?.max_attempts, 0),
      next_retry_at: rawJob?.next_retry_at ?? null,
    },
    technical: {
      job_id: toPositiveInt(rawJob?.id ?? rawJob?.job_id, null),
      created_by: toPositiveInt(rawJob?.created_by, null),
      created_at: rawJob?.created_at ?? null,
      updated_at: rawJob?.updated_at ?? null,
      started_at: rawJob?.started_at ?? null,
      completed_at: rawJob?.completed_at ?? null,
      raw_available: {
        payload: payload && Object.keys(payload).length > 0,
        result: result && Object.keys(result).length > 0,
      },
      raw: {
        payload,
        result,
      },
    },
  };
};

const normalizeDetailsSummary = (rawSummary, rawJob) => {
  const fallback = buildLocalFallbackSummary(rawJob);
  if (!rawSummary || typeof rawSummary !== "object") {
    return fallback;
  }

  return {
    message: rawSummary?.message ?? fallback.message,
    target: {
      ...fallback.target,
      ...(rawSummary?.target && typeof rawSummary.target === "object" ? rawSummary.target : {}),
    },
    customer: {
      ...fallback.customer,
      ...(rawSummary?.customer && typeof rawSummary.customer === "object" ? rawSummary.customer : {}),
    },
    outcome: {
      ...fallback.outcome,
      ...(rawSummary?.outcome && typeof rawSummary.outcome === "object" ? rawSummary.outcome : {}),
    },
    transfer: {
      ...fallback.transfer,
      ...(rawSummary?.transfer && typeof rawSummary.transfer === "object" ? rawSummary.transfer : {}),
    },
    technical: {
      ...fallback.technical,
      ...(rawSummary?.technical && typeof rawSummary.technical === "object" ? rawSummary.technical : {}),
      raw_available: {
        ...fallback.technical.raw_available,
        ...(rawSummary?.raw_available && typeof rawSummary.raw_available === "object" ? rawSummary.raw_available : {}),
        ...(rawSummary?.technical?.raw_available && typeof rawSummary.technical.raw_available === "object"
          ? rawSummary.technical.raw_available
          : {}),
      },
      raw: rawSummary?.technical?.raw ?? fallback.technical.raw,
    },
  };
};

const normalizeJob = (rawJob) => {
  const payload = rawJob?.payload && typeof rawJob.payload === "object"
    ? rawJob.payload
    : {};
  const progressPercent = Number(rawJob?.progress_percent ?? 0);

  return {
    ...rawJob,
    id: toPositiveInt(rawJob?.id ?? rawJob?.job_id ?? rawJob?.queue_job_id, null),
    collected_invoice_id: toPositiveInt(
      rawJob?.collected_invoice_id ?? payload?.collected_invoice_id ?? rawJob?.invoice_collection_id,
      null,
    ),
    status: String(rawJob?.status ?? "UNKNOWN").toUpperCase(),
    progress_percent: Number.isFinite(progressPercent)
      ? Math.max(0, Math.min(100, progressPercent))
      : 0,
    progress_message: String(rawJob?.progress_message ?? ""),
    error_message: String(rawJob?.error_message ?? ""),
    attempts: toNonNegativeInt(rawJob?.attempts, 0),
    max_attempts: toNonNegativeInt(rawJob?.max_attempts, 0),
    payload,
    result: rawJob?.result ?? null,
    created_by: toNonNegativeInt(rawJob?.created_by, 0),
    created_at: rawJob?.created_at ?? null,
    updated_at: rawJob?.updated_at ?? null,
    started_at: rawJob?.started_at ?? null,
    completed_at: rawJob?.completed_at ?? null,
    next_retry_at: rawJob?.next_retry_at ?? null,
    transfer_type: String(rawJob?.transfer_type ?? ""),
    details_summary: normalizeDetailsSummary(rawJob?.details_summary, rawJob),
  };
};

const hasActiveJobs = computed(() => jobs.value.some((job) => ACTIVE_STATUSES.has(job.status)));
const canGoToPrevious = computed(() => offsetFilter.value > 0);
const canGoToNext = computed(() => hasMore.value);
const runSummaryTone = computed(() => {
  if (!runSummary.value) {
    return "is-info";
  }
  if ((runSummary.value.failed ?? 0) > 0 && (runSummary.value.completed ?? 0) < 1) {
    return "is-danger";
  }
  if ((runSummary.value.completed ?? 0) > 0) {
    return "is-success";
  }
  if ((runSummary.value.processed ?? 0) < 1) {
    return "is-warning";
  }
  return "is-info";
});
const runSummaryMessage = computed(() => formatRunSummaryMessage(runSummary.value));
const selectedSummary = computed(() => selectedJob.value?.details_summary ?? null);

const formatRunSummaryMessage = (summary) => {
  if (!summary) {
    return "";
  }

  const parts = [
    summary.message || "Collected invoice queue batch processed",
    `Processed ${toNonNegativeInt(summary.processed, 0)}`,
    `Completed ${toNonNegativeInt(summary.completed, 0)}`,
    `Failed ${toNonNegativeInt(summary.failed, 0)}`,
  ];

  if (Array.isArray(summary.jobs) && summary.jobs.length > 0) {
    parts.push(`Jobs ${summary.jobs.join(", ")}`);
  }

  if (summary.fallback) {
    parts.push("Legacy fallback active");
  }

  return parts.join(" | ");
};

const getStatusTagClass = (status) => {
  switch (status) {
    case ECONOMIC_QUEUE_STATUS.QUEUED:
      return "is-warning";
    case ECONOMIC_QUEUE_STATUS.PROCESSING:
      return "is-info";
    case ECONOMIC_QUEUE_STATUS.COMPLETED:
      return "is-success";
    case ECONOMIC_QUEUE_STATUS.FAILED:
      return "is-danger";
    default:
      return "is-light";
  }
};

const stopPolling = () => {
  if (pollTimer !== null) {
    clearTimeout(pollTimer);
    pollTimer = null;
  }
};

const syncPollingState = () => {
  if (runningQueue.value) {
    stopPolling();
    return;
  }

  if (hasActiveJobs.value && !pollErrorMessage.value) {
    startPolling();
    return;
  }

  stopPolling();
};

const startPolling = () => {
  if (pollTimer !== null || !hasActiveJobs.value || runningQueue.value || pollErrorMessage.value) {
    return;
  }

  pollTimer = setTimeout(async () => {
    pollTimer = null;

    if (!hasActiveJobs.value || runningQueue.value) {
      stopPolling();
      return;
    }

    try {
      await runQueueBatchWithFallback();
      await loadQueueHistory({ silent: true, isPoll: true });
    } catch (error) {
      pollErrorMessage.value = `Polling paused due to a transport error: ${getEconomicApiErrorMessage(
        error,
        "Failed to run queue worker.",
      )}`;
      stopPolling();
      return;
    }

    syncPollingState();
  }, POLL_INTERVAL_MS);
};

const loadQueueHistory = async ({ silent = false, isPoll = false } = {}) => {
  if (loadPromise) {
    queuePendingLoad({ silent, isPoll });
    return loadPromise;
  }

  if (silent) {
    refreshing.value = true;
  } else {
    loading.value = true;
  }

  if (!isPoll) {
    pollErrorMessage.value = "";
  }
  errorMessage.value = "";

  loadPromise = (async () => {
    try {
      const response = await SessionUser.objects.collectedOrderInvoices.functions.economic.queue.list({
        status: statusFilter.value || undefined,
        limit: limitFilter.value,
        offset: offsetFilter.value,
      });

      const parsed = parseEconomicTransferQueueListResponse(response, {
        defaultLimit: limitFilter.value,
        defaultOffset: offsetFilter.value,
      });

      jobs.value = parsed.items.map((rawJob) => normalizeJob(rawJob));
      total.value = toNonNegativeInt(parsed.total, jobs.value.length);
      hasMore.value = Boolean(parsed.hasMore);

      if (selectedJob.value?.id) {
        selectedJob.value = jobs.value.find((job) => job.id === selectedJob.value.id) ?? null;
      }

      syncPollingState();
      return parsed;
    } catch (error) {
      const message = getEconomicApiErrorMessage(error, "Failed to load queue history.");

      if (isPoll) {
        pollErrorMessage.value = `Polling paused due to a transport error: ${message}`;
        stopPolling();
      } else {
        errorMessage.value = message;
      }

      throw error;
    } finally {
      loading.value = false;
      refreshing.value = false;
      loadPromise = null;

      const pendingLoad = takePendingLoad();
      if (pendingLoad) {
        void loadQueueHistory(pendingLoad);
      }
    }
  })();

  return loadPromise;
};

const isManualRunEndpointMissing = (error) => {
  const statusCode = Number(error?.response?.status ?? error?.status ?? 0);
  const message = getEconomicApiErrorMessage(error, "").toLowerCase();

  return statusCode === 404
    || message.includes("not found")
    || (
      statusCode >= 500
      && message.includes("undefined method")
      && message.includes("processpendingbytransfertype")
    );
};

const findQueuedJobForLegacyFallback = async () => {
  const localQueuedJob = jobs.value.find((job) => job.status === ECONOMIC_QUEUE_STATUS.QUEUED);
  if (localQueuedJob?.id) {
    return localQueuedJob;
  }

  const response = await SessionUser.objects.collectedOrderInvoices.functions.economic.queue.list({
    status: ECONOMIC_QUEUE_STATUS.QUEUED,
    limit: 1,
    offset: 0,
  });
  const parsed = parseEconomicTransferQueueListResponse(response, {
    defaultLimit: 1,
    defaultOffset: 0,
  });
  const firstQueuedJob = parsed.items[0] ? normalizeJob(parsed.items[0]) : null;
  return firstQueuedJob?.id ? firstQueuedJob : null;
};

const runQueueViaLegacyFallback = async () => {
  const queuedJob = await findQueuedJobForLegacyFallback();

  if (!queuedJob?.id) {
    return {
      message: "No queued jobs were available to run.",
      processed: 0,
      completed: 0,
      failed: 0,
      jobs: [],
      limit: MANUAL_RUN_LIMIT,
      transfer_type: "COLLECTED_INVOICE_EXPORT",
      status: ECONOMIC_QUEUE_STATUS.QUEUED,
      fallback: true,
    };
  }

  await SessionUser.objects.collectedOrderInvoices.functions.economic.queue.status(queuedJob.id);

  return {
    message: "Run queue now used the legacy queue status tick.",
    processed: 1,
    completed: 0,
    failed: 0,
    jobs: [queuedJob.id],
    limit: MANUAL_RUN_LIMIT,
    transfer_type: "COLLECTED_INVOICE_EXPORT",
    status: ECONOMIC_QUEUE_STATUS.QUEUED,
    fallback: true,
  };
};

const runQueueBatchWithFallback = async () => {
  try {
    const response = await SessionUser.objects.collectedOrderInvoices.functions.economic.queue.run();
    return response?.run ?? response;
  } catch (error) {
    if (isManualRunEndpointMissing(error)) {
      manualRunUnavailable.value = true;
      return runQueueViaLegacyFallback();
    }

    throw error;
  }
};

const onRefresh = async () => {
  runSummary.value = null;
  pollErrorMessage.value = "";
  stopPolling();

  try {
    if (hasActiveJobs.value) {
      await runQueueBatchWithFallback();
    }
    await loadQueueHistory({ silent: true });
  } catch (error) {
    errorMessage.value = getEconomicApiErrorMessage(error, "Refresh failed.");
    return;
  }
};

const onRetryJob = async (job) => {
  if (!job?.id || retryingJobIds.value.includes(job.id)) {
    return;
  }

  if (job.status !== ECONOMIC_QUEUE_STATUS.FAILED) {
    errorMessage.value = "Retry is only available for failed queue jobs.";
    return;
  }

  if (job.max_attempts > 0 && job.attempts >= job.max_attempts) {
    errorMessage.value = "Retry is no longer available because the max attempts were used.";
    return;
  }

  retryingJobIds.value = [...retryingJobIds.value, job.id];
  errorMessage.value = "";
  pollErrorMessage.value = "";
  stopPolling();

  try {
    await SessionUser.objects.collectedOrderInvoices.functions.economic.queue.retry(job.id);
    await loadQueueHistory({ silent: true });
  } catch (error) {
    errorMessage.value = getEconomicApiErrorMessage(error, "Retry failed.");
  } finally {
    retryingJobIds.value = retryingJobIds.value.filter((id) => id !== job.id);
    syncPollingState();
  }
};

const onRunQueueNow = async () => {
  if (runningQueue.value) {
    return;
  }

  runningQueue.value = true;
  errorMessage.value = "";
  pollErrorMessage.value = "";
  runSummary.value = null;
  stopPolling();

  try {
    const run = await runQueueBatchWithFallback();
    runSummary.value = run;
    await loadQueueHistory({ silent: true });
  } catch (error) {
    errorMessage.value = getEconomicApiErrorMessage(error, "Run queue now failed.");
  } finally {
    runningQueue.value = false;
    syncPollingState();
  }
};

const onLimitChange = (event) => {
  limitFilter.value = toPositiveInt(event?.target?.value, DEFAULT_LIMIT) ?? DEFAULT_LIMIT;
  offsetFilter.value = 0;
};

const onOffsetInput = (event) => {
  offsetFilter.value = toNonNegativeInt(event?.target?.value, 0);
};

const goToPreviousPage = () => {
  offsetFilter.value = Math.max(0, offsetFilter.value - limitFilter.value);
};

const goToNextPage = () => {
  if (!hasMore.value) {
    return;
  }
  offsetFilter.value = offsetFilter.value + limitFilter.value;
};

const openDetails = (job) => {
  selectedJob.value = job;
};

const closeDetails = () => {
  selectedJob.value = null;
};

watch([statusFilter, limitFilter, offsetFilter], () => {
  if (!isMounted) {
    return;
  }

  void loadQueueHistory();
});

watch(hasActiveJobs, () => {
  syncPollingState();
});

onMounted(() => {
  isMounted = true;
  void loadQueueHistory();
});

onBeforeUnmount(() => {
  stopPolling();
});

const __returned__ = { ACTIVE_STATUSES, DEFAULT_LIMIT, MANUAL_RUN_LIMIT, POLL_INTERVAL_MS, statusFilter, limitFilter, offsetFilter, jobs, total, hasMore, loading, refreshing, runningQueue, errorMessage, pollErrorMessage, manualRunUnavailable, runSummary, retryingJobIds, selectedJob, get pollTimer() { return pollTimer }, set pollTimer(v) { pollTimer = v; }, get loadPromise() { return loadPromise }, set loadPromise(v) { loadPromise = v; }, get isMounted() { return isMounted }, set isMounted(v) { isMounted = v; }, get pendingLoadAfterCurrent() { return pendingLoadAfterCurrent }, set pendingLoadAfterCurrent(v) { pendingLoadAfterCurrent = v; }, get pendingLoadSilent() { return pendingLoadSilent }, set pendingLoadSilent(v) { pendingLoadSilent = v; }, get pendingLoadIsPoll() { return pendingLoadIsPoll }, set pendingLoadIsPoll(v) { pendingLoadIsPoll = v; }, queuePendingLoad, takePendingLoad, toPositiveInt, toNonNegativeInt, formatDateTime, formatScalar, formatJson, formatMoney, buildLocalFallbackSummary, normalizeDetailsSummary, normalizeJob, hasActiveJobs, canGoToPrevious, canGoToNext, runSummaryTone, runSummaryMessage, selectedSummary, formatRunSummaryMessage, getStatusTagClass, stopPolling, syncPollingState, startPolling, loadQueueHistory, isManualRunEndpointMissing, findQueuedJobForLegacyFallback, runQueueViaLegacyFallback, runQueueBatchWithFallback, onRefresh, onRetryJob, onRunQueueNow, onLimitChange, onOffsetInput, goToPreviousPage, goToNextPage, openDetails, closeDetails, computed, onBeforeUnmount, onMounted, ref, watch, SessionUser, get ECONOMIC_QUEUE_STATUS() { return ECONOMIC_QUEUE_STATUS }, get getEconomicApiErrorMessage() { return getEconomicApiErrorMessage }, get parseEconomicTransferQueueListResponse() { return parseEconomicTransferQueueListResponse } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$m = { "data-testid": "economic-queue-history-page" };
const _hoisted_2$j = { class: "columns is-multiline is-vcentered" };
const _hoisted_3$j = { class: "column is-3" };
const _hoisted_4$j = { class: "select is-small is-fullwidth" };
const _hoisted_5$i = ["value"];
const _hoisted_6$i = ["value"];
const _hoisted_7$h = ["value"];
const _hoisted_8$h = ["value"];
const _hoisted_9$g = { class: "column is-3" };
const _hoisted_10$f = { class: "select is-small is-fullwidth" };
const _hoisted_11$c = ["value"];
const _hoisted_12$b = { class: "column is-3" };
const _hoisted_13$a = ["value"];
const _hoisted_14$a = { class: "column is-3 has-text-right" };
const _hoisted_15$a = { class: "buttons is-right are-small" };
const _hoisted_16$a = ["disabled"];
const _hoisted_17$8 = ["disabled"];
const _hoisted_18$8 = ["disabled"];
const _hoisted_19$7 = ["disabled"];
const _hoisted_20$6 = {
  class: "mb-3",
  "data-testid": "economic-queue-history-summary"
};
const _hoisted_21$6 = { class: "has-text-grey" };
const _hoisted_22$6 = { key: 0 };
const _hoisted_23$6 = { key: 1 };
const _hoisted_24$6 = { key: 2 };
const _hoisted_25$6 = {
  key: 1,
  class: "notification is-warning is-light",
  "data-testid": "economic-queue-history-poll-error"
};
const _hoisted_26$6 = {
  key: 2,
  class: "notification is-danger is-light",
  "data-testid": "economic-queue-history-error"
};
const _hoisted_27$6 = {
  key: 3,
  class: "notification is-light",
  "data-testid": "economic-queue-history-loading"
};
const _hoisted_28$6 = {
  key: 4,
  class: "notification is-light",
  "data-testid": "economic-queue-history-empty"
};
const _hoisted_29$5 = {
  key: 5,
  class: "table-container"
};
const _hoisted_30$5 = {
  class: "table is-fullwidth is-hoverable is-striped",
  "data-testid": "economic-queue-history-table"
};
const _hoisted_31$5 = ["data-testid"];
const _hoisted_32$5 = ["data-testid"];
const _hoisted_33$5 = { style: {"min-width":"240px"} };
const _hoisted_34$5 = { class: "is-block" };
const _hoisted_35$5 = ["value"];
const _hoisted_36$4 = { style: {"min-width":"220px"} };
const _hoisted_37$4 = { class: "is-block" };
const _hoisted_38$4 = { class: "is-block" };
const _hoisted_39$4 = { class: "is-block" };
const _hoisted_40$4 = { class: "is-block" };
const _hoisted_41$4 = { style: {"min-width":"220px"} };
const _hoisted_42$4 = { class: "is-block" };
const _hoisted_43$4 = {
  key: 0,
  class: "is-block"
};
const _hoisted_44$4 = ["onClick", "data-testid"];
const _hoisted_45$4 = { class: "has-text-right" };
const _hoisted_46$4 = ["onClick", "disabled", "data-testid"];
const _hoisted_47$4 = {
  key: 6,
  class: "modal is-active",
  "data-testid": "economic-queue-history-details-modal"
};
const _hoisted_48$4 = { class: "modal-card queue-details-modal-card" };
const _hoisted_49$3 = { class: "modal-card-head" };
const _hoisted_50$3 = { class: "modal-card-title" };
const _hoisted_51$3 = { class: "modal-card-body" };
const _hoisted_52$3 = {
  class: "box",
  "data-testid": "economic-queue-history-details-section-udfald"
};
const _hoisted_53$2 = { key: 0 };
const _hoisted_54$2 = {
  class: "box",
  "data-testid": "economic-queue-history-details-section-faktura"
};
const _hoisted_55$2 = {
  class: "box",
  "data-testid": "economic-queue-history-details-section-overfoersel"
};
const _hoisted_56$2 = {
  class: "box",
  "data-testid": "economic-queue-history-details-section-koersel"
};
const _hoisted_57$2 = {
  class: "box",
  "data-testid": "economic-queue-history-details-section-teknisk"
};
const _hoisted_58$2 = {
  class: "is-size-7 has-background-light p-3",
  "data-testid": "economic-queue-history-details-technical-raw"
};

function _sfc_render$n(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("section", _hoisted_1$m, [
    createBaseVNode("div", _hoisted_2$j, [
      createBaseVNode("div", _hoisted_3$j, [
        _cache[2] || (_cache[2] = createBaseVNode("label", { class: "label is-small" }, "Status", -1 /* CACHED */)),
        createBaseVNode("div", _hoisted_4$j, [
          withDirectives(createBaseVNode("select", {
            "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (($setup.statusFilter) = $event)),
            "data-testid": "economic-queue-history-status-filter"
          }, [
            _cache[1] || (_cache[1] = createBaseVNode("option", { value: "" }, "All", -1 /* CACHED */)),
            createBaseVNode("option", {
              value: $setup.ECONOMIC_QUEUE_STATUS.QUEUED
            }, "QUEUED", 8 /* PROPS */, _hoisted_5$i),
            createBaseVNode("option", {
              value: $setup.ECONOMIC_QUEUE_STATUS.PROCESSING
            }, "PROCESSING", 8 /* PROPS */, _hoisted_6$i),
            createBaseVNode("option", {
              value: $setup.ECONOMIC_QUEUE_STATUS.COMPLETED
            }, "COMPLETED", 8 /* PROPS */, _hoisted_7$h),
            createBaseVNode("option", {
              value: $setup.ECONOMIC_QUEUE_STATUS.FAILED
            }, "FAILED", 8 /* PROPS */, _hoisted_8$h)
          ], 512 /* NEED_PATCH */), [
            [vModelSelect, $setup.statusFilter]
          ])
        ])
      ]),
      createBaseVNode("div", _hoisted_9$g, [
        _cache[4] || (_cache[4] = createBaseVNode("label", { class: "label is-small" }, "Limit", -1 /* CACHED */)),
        createBaseVNode("div", _hoisted_10$f, [
          createBaseVNode("select", {
            value: String($setup.limitFilter),
            onChange: $setup.onLimitChange,
            "data-testid": "economic-queue-history-limit-filter"
          }, [...(_cache[3] || (_cache[3] = [
            createBaseVNode("option", { value: "10" }, "10", -1 /* CACHED */),
            createBaseVNode("option", { value: "25" }, "25", -1 /* CACHED */),
            createBaseVNode("option", { value: "50" }, "50", -1 /* CACHED */),
            createBaseVNode("option", { value: "100" }, "100", -1 /* CACHED */)
          ]))], 40 /* PROPS, NEED_HYDRATION */, _hoisted_11$c)
        ])
      ]),
      createBaseVNode("div", _hoisted_12$b, [
        _cache[5] || (_cache[5] = createBaseVNode("label", { class: "label is-small" }, "Offset", -1 /* CACHED */)),
        createBaseVNode("input", {
          class: "input is-small",
          type: "number",
          min: "0",
          value: $setup.offsetFilter,
          onInput: $setup.onOffsetInput,
          "data-testid": "economic-queue-history-offset-filter"
        }, null, 40 /* PROPS, NEED_HYDRATION */, _hoisted_13$a)
      ]),
      createBaseVNode("div", _hoisted_14$a, [
        _cache[6] || (_cache[6] = createBaseVNode("label", { class: "label is-small" }, " ", -1 /* CACHED */)),
        createBaseVNode("div", _hoisted_15$a, [
          createBaseVNode("button", {
            class: "button is-small is-info",
            type: "button",
            onClick: $setup.onRunQueueNow,
            disabled: $setup.loading || $setup.refreshing || $setup.runningQueue,
            "data-testid": "economic-queue-history-run-now"
          }, toDisplayString($setup.runningQueue ? "Running..." : "Run queue now"), 9 /* TEXT, PROPS */, _hoisted_16$a),
          createBaseVNode("button", {
            class: "button is-small",
            type: "button",
            onClick: $setup.goToPreviousPage,
            disabled: !$setup.canGoToPrevious || $setup.loading || $setup.refreshing || $setup.runningQueue,
            "data-testid": "economic-queue-history-prev-page"
          }, " Previous ", 8 /* PROPS */, _hoisted_17$8),
          createBaseVNode("button", {
            class: "button is-small",
            type: "button",
            onClick: $setup.goToNextPage,
            disabled: !$setup.canGoToNext || $setup.loading || $setup.refreshing || $setup.runningQueue,
            "data-testid": "economic-queue-history-next-page"
          }, " Next ", 8 /* PROPS */, _hoisted_18$8),
          createBaseVNode("button", {
            class: "button is-small is-link is-light",
            type: "button",
            onClick: $setup.onRefresh,
            disabled: $setup.loading || $setup.refreshing || $setup.runningQueue,
            "data-testid": "economic-queue-history-refresh"
          }, " Refresh ", 8 /* PROPS */, _hoisted_19$7)
        ])
      ])
    ]),
    createBaseVNode("div", _hoisted_20$6, [
      createBaseVNode("small", _hoisted_21$6, [
        createTextVNode(" Showing " + toDisplayString($setup.jobs.length) + " of " + toDisplayString($setup.total) + " jobs. ", 1 /* TEXT */),
        ($setup.hasMore)
          ? (openBlock(), createElementBlock("span", _hoisted_22$6, "More results available."))
          : createCommentVNode("v-if", true),
        ($setup.refreshing)
          ? (openBlock(), createElementBlock("span", _hoisted_23$6, "Refreshing..."))
          : createCommentVNode("v-if", true),
        ($setup.manualRunUnavailable)
          ? (openBlock(), createElementBlock("span", _hoisted_24$6, "Legacy fallback active while the backend queue runner is unavailable."))
          : createCommentVNode("v-if", true)
      ])
    ]),
    ($setup.runSummary)
      ? (openBlock(), createElementBlock("div", {
          key: 0,
          class: normalizeClass(["notification is-light", $setup.runSummaryTone]),
          "data-testid": "economic-queue-history-run-summary"
        }, toDisplayString($setup.runSummaryMessage), 3 /* TEXT, CLASS */))
      : createCommentVNode("v-if", true),
    ($setup.pollErrorMessage)
      ? (openBlock(), createElementBlock("div", _hoisted_25$6, toDisplayString($setup.pollErrorMessage), 1 /* TEXT */))
      : createCommentVNode("v-if", true),
    ($setup.errorMessage)
      ? (openBlock(), createElementBlock("div", _hoisted_26$6, toDisplayString($setup.errorMessage), 1 /* TEXT */))
      : createCommentVNode("v-if", true),
    ($setup.loading && $setup.jobs.length === 0)
      ? (openBlock(), createElementBlock("div", _hoisted_27$6, " Loading queue history... "))
      : ($setup.jobs.length === 0)
        ? (openBlock(), createElementBlock("div", _hoisted_28$6, " No queue jobs found for the selected filters. "))
        : (openBlock(), createElementBlock("div", _hoisted_29$5, [
            createBaseVNode("table", _hoisted_30$5, [
              _cache[7] || (_cache[7] = createBaseVNode("thead", null, [
                createBaseVNode("tr", null, [
                  createBaseVNode("th", null, "Job"),
                  createBaseVNode("th", null, "Invoice"),
                  createBaseVNode("th", null, "Status"),
                  createBaseVNode("th", null, "Attempts"),
                  createBaseVNode("th", null, "Progress"),
                  createBaseVNode("th", null, "Timestamps"),
                  createBaseVNode("th", null, "Details"),
                  createBaseVNode("th", { class: "has-text-right" }, "Actions")
                ])
              ], -1 /* CACHED */)),
              createBaseVNode("tbody", null, [
                (openBlock(true), createElementBlock(Fragment, null, renderList($setup.jobs, (job) => {
                  return (openBlock(), createElementBlock("tr", {
                    key: job.id || `${job.status}-${job.created_at}`,
                    "data-testid": `economic-queue-history-row-${job.id}`
                  }, [
                    createBaseVNode("td", null, "#" + toDisplayString(job.id || "n/a"), 1 /* TEXT */),
                    createBaseVNode("td", null, toDisplayString(job.collected_invoice_id || "-"), 1 /* TEXT */),
                    createBaseVNode("td", null, [
                      createBaseVNode("span", {
                        class: normalizeClass(["tag", $setup.getStatusTagClass(job.status)]),
                        "data-testid": `economic-queue-history-status-${job.id}`
                      }, toDisplayString(job.status), 11 /* TEXT, CLASS, PROPS */, _hoisted_32$5)
                    ]),
                    createBaseVNode("td", null, toDisplayString(job.attempts) + " / " + toDisplayString(job.max_attempts || 0), 1 /* TEXT */),
                    createBaseVNode("td", _hoisted_33$5, [
                      createBaseVNode("small", _hoisted_34$5, toDisplayString(job.progress_message || "-"), 1 /* TEXT */),
                      createBaseVNode("progress", {
                        class: "progress is-small is-link",
                        max: "100",
                        value: job.progress_percent
                      }, null, 8 /* PROPS */, _hoisted_35$5)
                    ]),
                    createBaseVNode("td", _hoisted_36$4, [
                      createBaseVNode("small", _hoisted_37$4, "Created: " + toDisplayString($setup.formatDateTime(job.created_at)), 1 /* TEXT */),
                      createBaseVNode("small", _hoisted_38$4, "Started: " + toDisplayString($setup.formatDateTime(job.started_at)), 1 /* TEXT */),
                      createBaseVNode("small", _hoisted_39$4, "Updated: " + toDisplayString($setup.formatDateTime(job.updated_at)), 1 /* TEXT */),
                      createBaseVNode("small", _hoisted_40$4, "Completed: " + toDisplayString($setup.formatDateTime(job.completed_at)), 1 /* TEXT */)
                    ]),
                    createBaseVNode("td", _hoisted_41$4, [
                      createBaseVNode("small", _hoisted_42$4, toDisplayString(job.details_summary?.message || "-"), 1 /* TEXT */),
                      (job.error_message)
                        ? (openBlock(), createElementBlock("small", _hoisted_43$4, toDisplayString(job.error_message), 1 /* TEXT */))
                        : createCommentVNode("v-if", true),
                      createBaseVNode("button", {
                        class: "button is-small is-light mt-2",
                        type: "button",
                        onClick: $event => ($setup.openDetails(job)),
                        "data-testid": `economic-queue-history-details-${job.id}`
                      }, " Se detaljer ", 8 /* PROPS */, _hoisted_44$4)
                    ]),
                    createBaseVNode("td", _hoisted_45$4, [
                      (job.status === $setup.ECONOMIC_QUEUE_STATUS.FAILED)
                        ? (openBlock(), createElementBlock("button", {
                            key: 0,
                            class: "button is-small is-danger is-light",
                            type: "button",
                            onClick: $event => ($setup.onRetryJob(job)),
                            disabled: $setup.retryingJobIds.includes(job.id) || (job.max_attempts > 0 && job.attempts >= job.max_attempts),
                            "data-testid": `economic-queue-history-retry-${job.id}`
                          }, toDisplayString($setup.retryingJobIds.includes(job.id) ? "Retrying..." : "Retry"), 9 /* TEXT, PROPS */, _hoisted_46$4))
                        : createCommentVNode("v-if", true)
                    ])
                  ], 8 /* PROPS */, _hoisted_31$5))
                }), 128 /* KEYED_FRAGMENT */))
              ])
            ])
          ])),
    ($setup.selectedJob && $setup.selectedSummary)
      ? (openBlock(), createElementBlock("div", _hoisted_47$4, [
          createBaseVNode("div", {
            class: "modal-background",
            onClick: $setup.closeDetails
          }),
          createBaseVNode("div", _hoisted_48$4, [
            createBaseVNode("header", _hoisted_49$3, [
              createBaseVNode("p", _hoisted_50$3, "Queue job #" + toDisplayString($setup.selectedJob.id), 1 /* TEXT */),
              createBaseVNode("button", {
                class: "delete",
                type: "button",
                "aria-label": "close",
                onClick: $setup.closeDetails,
                "data-testid": "economic-queue-history-details-close"
              })
            ]),
            createBaseVNode("section", _hoisted_51$3, [
              createBaseVNode("article", _hoisted_52$3, [
                _cache[8] || (_cache[8] = createBaseVNode("h4", { class: "title is-6" }, "Udfald", -1 /* CACHED */)),
                createBaseVNode("p", null, toDisplayString($setup.selectedSummary.message || "-"), 1 /* TEXT */),
                createBaseVNode("p", null, "Status: " + toDisplayString($setup.formatScalar($setup.selectedSummary.outcome?.status)), 1 /* TEXT */),
                createBaseVNode("p", null, "Draft id: " + toDisplayString($setup.formatScalar($setup.selectedSummary.outcome?.economic_invoice_draft_id)), 1 /* TEXT */),
                createBaseVNode("p", null, "Booked id: " + toDisplayString($setup.formatScalar($setup.selectedSummary.outcome?.economic_invoice_booked_id)), 1 /* TEXT */),
                createBaseVNode("p", null, "External id: " + toDisplayString($setup.formatScalar($setup.selectedSummary.outcome?.external_id)), 1 /* TEXT */),
                createBaseVNode("p", null, "Total net: " + toDisplayString($setup.formatMoney($setup.selectedSummary.outcome?.total_net_amount)), 1 /* TEXT */),
                createBaseVNode("p", null, "Order count: " + toDisplayString($setup.formatScalar($setup.selectedSummary.outcome?.order_count)), 1 /* TEXT */),
                ($setup.selectedSummary.outcome?.error_message)
                  ? (openBlock(), createElementBlock("p", _hoisted_53$2, "Error: " + toDisplayString($setup.selectedSummary.outcome.error_message), 1 /* TEXT */))
                  : createCommentVNode("v-if", true)
              ]),
              createBaseVNode("article", _hoisted_54$2, [
                _cache[9] || (_cache[9] = createBaseVNode("h4", { class: "title is-6" }, "Faktura", -1 /* CACHED */)),
                createBaseVNode("p", null, "Collected invoice id: " + toDisplayString($setup.formatScalar($setup.selectedSummary.target?.collected_invoice_id)), 1 /* TEXT */),
                createBaseVNode("p", null, "Send as is: " + toDisplayString($setup.formatScalar($setup.selectedSummary.target?.send_as_is)), 1 /* TEXT */),
                createBaseVNode("p", null, "Requested by: " + toDisplayString($setup.formatScalar($setup.selectedSummary.target?.requested_by)), 1 /* TEXT */),
                createBaseVNode("p", null, "Customer number: " + toDisplayString($setup.formatScalar($setup.selectedSummary.customer?.customer_number)), 1 /* TEXT */),
                createBaseVNode("p", null, "Customer name: " + toDisplayString($setup.formatScalar($setup.selectedSummary.customer?.name)), 1 /* TEXT */)
              ]),
              createBaseVNode("article", _hoisted_55$2, [
                _cache[10] || (_cache[10] = createBaseVNode("h4", { class: "title is-6" }, "Overførsel", -1 /* CACHED */)),
                createBaseVNode("p", null, "Transfer type: " + toDisplayString($setup.formatScalar($setup.selectedSummary.transfer?.transfer_type || $setup.selectedJob.transfer_type)), 1 /* TEXT */),
                createBaseVNode("p", null, "Status: " + toDisplayString($setup.formatScalar($setup.selectedSummary.transfer?.status || $setup.selectedJob.status)), 1 /* TEXT */),
                createBaseVNode("p", null, "Progress: " + toDisplayString($setup.formatScalar($setup.selectedSummary.transfer?.progress_percent || $setup.selectedJob.progress_percent)) + "%", 1 /* TEXT */),
                createBaseVNode("p", null, "Message: " + toDisplayString($setup.formatScalar($setup.selectedSummary.transfer?.progress_message || $setup.selectedJob.progress_message)), 1 /* TEXT */),
                createBaseVNode("p", null, "Attempts: " + toDisplayString($setup.formatScalar($setup.selectedSummary.transfer?.attempts || $setup.selectedJob.attempts)), 1 /* TEXT */),
                createBaseVNode("p", null, "Max attempts: " + toDisplayString($setup.formatScalar($setup.selectedSummary.transfer?.max_attempts || $setup.selectedJob.max_attempts)), 1 /* TEXT */),
                createBaseVNode("p", null, "Next retry at: " + toDisplayString($setup.formatScalar($setup.selectedSummary.transfer?.next_retry_at || $setup.selectedJob.next_retry_at)), 1 /* TEXT */)
              ]),
              createBaseVNode("article", _hoisted_56$2, [
                _cache[11] || (_cache[11] = createBaseVNode("h4", { class: "title is-6" }, "Koersel", -1 /* CACHED */)),
                createBaseVNode("p", null, "Created: " + toDisplayString($setup.formatDateTime($setup.selectedSummary.technical?.created_at || $setup.selectedJob.created_at)), 1 /* TEXT */),
                createBaseVNode("p", null, "Started: " + toDisplayString($setup.formatDateTime($setup.selectedSummary.technical?.started_at || $setup.selectedJob.started_at)), 1 /* TEXT */),
                createBaseVNode("p", null, "Updated: " + toDisplayString($setup.formatDateTime($setup.selectedSummary.technical?.updated_at || $setup.selectedJob.updated_at)), 1 /* TEXT */),
                createBaseVNode("p", null, "Completed: " + toDisplayString($setup.formatDateTime($setup.selectedSummary.technical?.completed_at || $setup.selectedJob.completed_at)), 1 /* TEXT */),
                createBaseVNode("p", null, "Created by: " + toDisplayString($setup.formatScalar($setup.selectedSummary.technical?.created_by || $setup.selectedJob.created_by)), 1 /* TEXT */),
                createBaseVNode("p", null, "Job id: " + toDisplayString($setup.formatScalar($setup.selectedSummary.technical?.job_id || $setup.selectedJob.id)), 1 /* TEXT */)
              ]),
              createBaseVNode("article", _hoisted_57$2, [
                _cache[12] || (_cache[12] = createBaseVNode("h4", { class: "title is-6" }, "Teknisk", -1 /* CACHED */)),
                createBaseVNode("p", null, "Payload available: " + toDisplayString($setup.formatScalar($setup.selectedSummary.technical?.raw_available?.payload)), 1 /* TEXT */),
                createBaseVNode("p", null, "Result available: " + toDisplayString($setup.formatScalar($setup.selectedSummary.technical?.raw_available?.result)), 1 /* TEXT */),
                createBaseVNode("pre", _hoisted_58$2, toDisplayString($setup.formatJson($setup.selectedSummary.technical?.raw)), 1 /* TEXT */)
              ])
            ])
          ])
        ]))
      : createCommentVNode("v-if", true)
  ]))
}
const CollectedOrderInvoicesQueueHistory = /*#__PURE__*/_export_sfc(_sfc_main$U, [['render',_sfc_render$n],['__scopeId',"data-v-d9bdf6bc"],['__file',"CollectedOrderInvoicesQueueHistory.vue"]]);

const _sfc_main$T = {
  __name: 'CollectedOrderInvoices',
  setup(__props, { expose: __expose }) {
  __expose();

const { t } = useI18n();

const tabs = ref([
  { name: 'Overblik', slot: 'overview', icon: 'chart-pie', hidden: false },
  { name: 'Fakturaer', slot: 'invoices', icon: 'list', hidden: false },
  { name: 'Periode', slot: 'period', icon: 'calendar-alt', hidden: false },
  { name: t('superuser_invoice_distribution.tab_label'), slot: 'distribution', icon: 'sitemap', hidden: false },
  { name: 'Overførsler', slot: 'queue', icon: 'tasks', hidden: false },
]);

const router = getCurrentInstance()?.appContext.config.globalProperties.$router;
const getQueryActiveTab = () => (
  router?.currentRoute.value.query.activeTab
  ?? new URLSearchParams(window.location.search).get('activeTab')
);
const activeTab = ref('overview');

watch(getQueryActiveTab, (newTab) => {
  if (newTab && tabs.value.some(tab => tab.slot === newTab)) {
    activeTab.value = newTab;
  }
});

watch(activeTab, (newTab) => {
  if (newTab && router && router.currentRoute.value.query.activeTab !== newTab) {
    router.replace({ query: { ...router.currentRoute.value.query, activeTab: newTab } });
  }
});

onMounted(() => {
  const queryTab = getQueryActiveTab();
  if (queryTab && tabs.value.some(tab => tab.slot === queryTab)) {
    activeTab.value = queryTab;
  } else {
    activeTab.value = 'overview';
  }
});

function getTabComponent(tabName) {
  switch (tabName) {
    case 'overview':
      return CollectedOrderInvoicesOverview;
    case 'invoices':
      return CollectedOrderInvoicesListPagination;
    case 'transactions':
      return InvoiceOrdersPagination;
    case 'period':
      return InvoicingBillingPeriod;
    case 'distribution':
      return InvoiceDistributionOverview;
    case 'queue':
      return CollectedOrderInvoicesQueueHistory;
    default:
      return null;
  }
}

const __returned__ = { t, tabs, router, getQueryActiveTab, activeTab, getTabComponent, RestrictedPageWrapper, SessionUser, CollectedOrderInvoicesListPagination, PageTitle, getCurrentInstance, onMounted, ref, watch, CollectedOrderInvoicesOverview, InvoiceOrdersPagination, InvoicingBillingPeriod, InvoiceDistributionOverview, CollectedOrderInvoicesQueueHistory, get useI18n() { return useI18n } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

function _sfc_render$m(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_b_tab_item = resolveComponent("b-tab-item");
  const _component_b_tabs = resolveComponent("b-tabs");

  return (openBlock(), createBlock($setup["RestrictedPageWrapper"], {
    hasPermission: $setup.SessionUser.canAccessSuperUser()
  }, {
    default: withCtx(() => [
      createVNode($setup["PageTitle"], {
        title: "Fakturaer",
        subtitle: "Her kan du se en liste over alle fakturaer i systemet"
      }),
      createVNode(_component_b_tabs, {
        modelValue: $setup.activeTab,
        "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (($setup.activeTab) = $event)),
        expanded: ""
      }, {
        default: withCtx(() => [
          (openBlock(true), createElementBlock(Fragment, null, renderList($setup.tabs, (tab) => {
            return (openBlock(), createElementBlock(Fragment, {
              key: tab.slot
            }, [
              (!tab.hidden)
                ? (openBlock(), createBlock(_component_b_tab_item, {
                    key: 0,
                    label: tab.name,
                    icon: tab.icon,
                    "icon-pack": 'fas',
                    value: tab.slot
                  }, {
                    default: withCtx(() => [
                      (openBlock(), createBlock(resolveDynamicComponent($setup.getTabComponent(tab.slot))))
                    ]),
                    _: 2 /* DYNAMIC */
                  }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["label", "icon", "value"]))
                : createCommentVNode("v-if", true)
            ], 64 /* STABLE_FRAGMENT */))
          }), 128 /* KEYED_FRAGMENT */))
        ]),
        _: 1 /* STABLE */
      }, 8 /* PROPS */, ["modelValue"])
    ]),
    _: 1 /* STABLE */
  }, 8 /* PROPS */, ["hasPermission"]))
}
const CollectedOrderInvoices$1 = /*#__PURE__*/_export_sfc(_sfc_main$T, [['render',_sfc_render$m],['__file',"CollectedOrderInvoices.vue"]]);

const _sfc_main$S = {
  __name: 'vehiclesTable',
  props: {
  vehicles: {
    type: Array,
    required: true,
  },
  show_add_vehicle: {
    type: Number,
    required: false,
    default: null,
  },
  compact: {
    type: Boolean,
    required: false,
    default: false,
  },
  reloadList: {
    type: Function,
    required: false,
    default: null,
  },
  add_other_customer_id: {
    type: Number,
    required: false,
    default: null,
  },
  userScopedUserId: {
    type: [Number, String],
    required: false,
    default: null,
  },
  superuserPage: {
    type: Boolean,
    required: false,
    default: false,
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const { t } = useI18n();
const props = __props;

const reload = () => {
  // Load the list of vehicles
  if (props.reloadList) {
    props.reloadList();
  } else {
    loadList();
  }
};

const canViewVehicle = () => SessionUser.canAccessCustomerFeature("vehicles", "list");
const canEditVehicle = () => SessionUser.canAccessCustomerFeature("vehicles", "edit");
const canDeleteVehicle = () => SessionUser.canAccessCustomerFeature("vehicles", "delete");
const canShowVehicleRowActions = () => canViewVehicle() || canDeleteVehicle();
const isUserScoped = () => Boolean(props.userScopedUserId);

const redirectVehiclePage = (vehicle) => {
  if (props.superuserPage) {
    window.location.href = `/superuser/vehicles/${encodeURIComponent(vehicle.reg)}`;
    return;
  }

  window.location.href = `/user/vehicles/${encodeURIComponent(vehicle.id)}`;
};

// Get the departments (If the departments are not already loaded)
if (departments.value.length === 0) {
  getDepartments();
}

const vehicleAddons = ref(null);
const getVehicleAvailableAddons = (vehicleId, forceReload = false) => {
  if (forceReload === true) {
    vehicleAddons.value = null;
  }
  // Get the vehicle addons from the server
  if (vehicleAddons.value === null) {
    vehicleAddons.value = [];
    SessionUser.request("/vehicles/addons/available", "GET", {
      id: vehicleId,
    }).then((response) => {
      vehicleAddons.value = response.data.data;
    });
  }
  return vehicleAddons.value;
};

const toggleVehicleAddon = (vehicleId, addonId) => {
  // Toggle the vehicle addon
  SessionUser.request("/vehicles/addons/toggle", "POST", {
    vehicle_id: vehicleId,
    addon_id: addonId,
  }).then(() => {
    reload();
  });
};

const getVehicleAddonToggleIcon = (vehicleAddon) => {
  // Check if the vehicle addon is applied
  if (isVehicleAddonApplied(vehicleAddon)) {
    return "fas fa-minus";
  } else {
    return "fas fa-plus";
  }
};

const isVehicleAddonApplied = (addon) => {
  if (!addon) {
    return false;
  }
  return addon.amount ? addon.amount > 0 : false;
};

const getProductOptionsLabel = (vehicle) => {
  const enabled = Number(vehicle?.addons?.enabled ?? 0);
  if (enabled <= 0) {
    return SessionUser.objects.product_options.meta.title;
  }

  const available = Number(vehicle?.addons?.available ?? 0);
  return `${SessionUser.objects.product_options.meta.title} ( ${enabled} / ${available} )`;
};

const editVehicleField = (id, column, value, onAfterSubmit = null) => {
  if (isUserScoped()) {
    return SessionUser.objects.vehicles.functions.showEditObjectFieldForUserForm(
      props.userScopedUserId,
      id,
      column,
      value,
      onAfterSubmit
    );
  }

  return SessionUser.objects.vehicles.showEditObjectFieldForm(id, column, value, onAfterSubmit);
};

const deleteVehicle = (id) => {
  if (isUserScoped()) {
    return SessionUser.objects.vehicles.functions.showDeleteObjectForUserForm(props.userScopedUserId, id, () => reload());
  }

  return SessionUser.objects.vehicles.functions.showDeleteObjectForm(id, () => reload());
};

const __returned__ = { t, props, reload, canViewVehicle, canEditVehicle, canDeleteVehicle, canShowVehicleRowActions, isUserScoped, redirectVehiclePage, vehicleAddons, getVehicleAvailableAddons, toggleVehicleAddon, getVehicleAddonToggleIcon, isVehicleAddonApplied, getProductOptionsLabel, editVehicleField, deleteVehicle, EditableTableColumn, ref, get useI18n() { return useI18n }, departments, getDepartments, SessionUser, loadList, ActionSettingsWheelButton, ActionSettingsWheelItem };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$l = {
  class: "table-container",
  "data-testid": "user-vehicles-table-container"
};
const _hoisted_2$i = {
  class: "table is-fullwidth",
  "data-testid": "user-vehicles-table"
};
const _hoisted_3$i = { key: 0 };
const _hoisted_4$i = { key: 1 };
const _hoisted_5$h = { key: 2 };
const _hoisted_6$h = { key: 3 };
const _hoisted_7$g = { key: 4 };
const _hoisted_8$g = { key: 2 };
const _hoisted_9$f = { key: 4 };
const _hoisted_10$e = { colspan: "10" };

function _sfc_render$l(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", null, [
    createBaseVNode("div", _hoisted_1$l, [
      createBaseVNode("table", _hoisted_2$i, [
        createBaseVNode("thead", null, [
          createBaseVNode("tr", null, [
            (!$setup.props.compact)
              ? (openBlock(), createElementBlock("th", _hoisted_3$i, toDisplayString(_ctx.$t("objects.columns.id")), 1 /* TEXT */))
              : createCommentVNode("v-if", true),
            (!$setup.props.compact)
              ? (openBlock(), createElementBlock("th", _hoisted_4$i, toDisplayString(_ctx.$t("objects.columns.customer_id")), 1 /* TEXT */))
              : createCommentVNode("v-if", true),
            createBaseVNode("th", null, toDisplayString(_ctx.$t("objects.bookings.columns.reg_1")), 1 /* TEXT */),
            createBaseVNode("th", null, toDisplayString(_ctx.$t("vehicles.type")), 1 /* TEXT */),
            createBaseVNode("th", null, toDisplayString(_ctx.$t("objects.vehicles.columns.wash_subscription")), 1 /* TEXT */),
            (!$setup.props.compact)
              ? (openBlock(), createElementBlock("th", _hoisted_5$h, toDisplayString($setup.SessionUser.objects.product_options.meta.title), 1 /* TEXT */))
              : createCommentVNode("v-if", true),
            (!$setup.props.compact)
              ? (openBlock(), createElementBlock("th", _hoisted_6$h, toDisplayString(_ctx.$t("common.reference")), 1 /* TEXT */))
              : createCommentVNode("v-if", true),
            (!$setup.props.compact)
              ? (openBlock(), createElementBlock("th", _hoisted_7$g))
              : createCommentVNode("v-if", true)
          ])
        ]),
        createBaseVNode("tbody", null, [
          (openBlock(true), createElementBlock(Fragment, null, renderList($setup.props.vehicles, (object) => {
            return (openBlock(), createElementBlock("tr", {
              key: object.id
            }, [
              createCommentVNode(" ID "),
              (!$setup.props.compact)
                ? (openBlock(), createBlock($setup["EditableTableColumn"], {
                    key: 0,
                    object: object,
                    loadList: $setup.reload,
                    column: "id"
                  }, null, 8 /* PROPS */, ["object"]))
                : createCommentVNode("v-if", true),
              createCommentVNode(" Customer ID "),
              (!$setup.props.compact)
                ? (openBlock(), createBlock($setup["EditableTableColumn"], {
                    key: 1,
                    object: object,
                    loadList: $setup.reload,
                    column: "customer_id"
                  }, null, 8 /* PROPS */, ["object"]))
                : createCommentVNode("v-if", true),
              createCommentVNode(" Reg "),
              createVNode($setup["EditableTableColumn"], {
                object: object,
                loadList: $setup.reload,
                editFunction: $setup.editVehicleField,
                "permission-check-function": $setup.canEditVehicle,
                column: "reg"
              }, null, 8 /* PROPS */, ["object"]),
              createCommentVNode(" Type "),
              createVNode($setup["EditableTableColumn"], {
                object: object,
                loadList: $setup.reload,
                editFunction: $setup.editVehicleField,
                "permission-check-function": $setup.canEditVehicle,
                column: "type",
                "parse-function": 
                (value) => {
                  return $setup.SessionUser.objects.products.functions.getProductName(value, 'Ukendt');
                }
              
              }, null, 8 /* PROPS */, ["object", "parse-function"]),
              createCommentVNode(" Wash Subscription "),
              createVNode($setup["EditableTableColumn"], {
                object: object,
                loadList: $setup.reload,
                editFunction: $setup.editVehicleField,
                "permission-check-function": $setup.canEditVehicle,
                column: "wash_subscription",
                "parse-function": 
                (value) => {
                  return value ? $setup.t('common.yes') : $setup.t('common.no');
                }
              
              }, null, 8 /* PROPS */, ["object", "parse-function"]),
              createCommentVNode(" Product Options, if the wash subscription is set to true "),
              (!$setup.props.compact)
                ? (openBlock(), createElementBlock("td", _hoisted_8$g, [
                    (object.wash_subscription && $setup.canEditVehicle())
                      ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                          createCommentVNode(" Enabled subscription "),
                          createVNode($setup["ActionSettingsWheelButton"], {
                            label: $setup.getProductOptionsLabel(object),
                            icon: $setup.SessionUser.objects.product_options.meta.icon,
                            onMouseenter: $event => ($setup.getVehicleAvailableAddons(object.id, true))
                          }, {
                            actions: withCtx(() => [
                              createCommentVNode(" List addons "),
                              (openBlock(true), createElementBlock(Fragment, null, renderList($setup.vehicleAddons, (vehicleAddon) => {
                                return (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                                  key: vehicleAddon.id,
                                  label: 
                          ($setup.isVehicleAddonApplied(vehicleAddon)
                            ? $setup.SessionUser.objects.global.language.remove
                            : $setup.SessionUser.objects.global.language.add) +
                          ' ' +
                          vehicleAddon.name
                        ,
                                  icon: $setup.getVehicleAddonToggleIcon(vehicleAddon),
                                  "click-action": () => $setup.toggleVehicleAddon(object.id, vehicleAddon.id),
                                  template: $setup.isVehicleAddonApplied(vehicleAddon) ? 'danger' : 'default'
                                }, null, 8 /* PROPS */, ["label", "icon", "click-action", "template"]))
                              }), 128 /* KEYED_FRAGMENT */)),
                              createCommentVNode(" If there are no addons, show a message "),
                              ($setup.vehicleAddons ? $setup.vehicleAddons.length === 0 : true)
                                ? (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                                    key: 0,
                                    label: _ctx.$t('global.no_data'),
                                    icon: "fas fa-list"
                                  }, null, 8 /* PROPS */, ["label"]))
                                : createCommentVNode("v-if", true),
                              createCommentVNode(" Addons ")
                            ]),
                            _: 2 /* DYNAMIC */
                          }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["label", "icon", "onMouseenter"])
                        ], 64 /* STABLE_FRAGMENT */))
                      : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
                          createCommentVNode(" Disabled subscription "),
                          createTextVNode(" " + toDisplayString(_ctx.$t("global.no_data")), 1 /* TEXT */)
                        ], 64 /* STABLE_FRAGMENT */))
                  ]))
                : createCommentVNode("v-if", true),
              createCommentVNode(" Reference to the vehicle "),
              (!$setup.props.compact)
                ? (openBlock(), createBlock($setup["EditableTableColumn"], {
                    key: 3,
                    object: object,
                    loadList: $setup.reload,
                    editFunction: $setup.editVehicleField,
                    "permission-check-function": $setup.canEditVehicle,
                    column: "reference"
                  }, null, 8 /* PROPS */, ["object"]))
                : createCommentVNode("v-if", true),
              createCommentVNode(" Actions "),
              (!$setup.props.compact)
                ? (openBlock(), createElementBlock("td", _hoisted_9$f, [
                    createCommentVNode(" Actions stay grouped behind the wheel menu. "),
                    ($setup.canShowVehicleRowActions())
                      ? (openBlock(), createBlock($setup["ActionSettingsWheelButton"], {
                          key: 0,
                          user_id: object.user_id,
                          reg_1: object.reg,
                          displayActionsDirectly: false
                        }, {
                          actions: withCtx(() => [
                            createCommentVNode(" View (Redirect to the vehicle page) "),
                            ($setup.canViewVehicle())
                              ? (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                                  key: 0,
                                  label: _ctx.$t('global.manage') + ' ' + _ctx.$t('objects.vehicles.single'),
                                  icon: "fas fa-eye",
                                  "click-action": () => $setup.redirectVehiclePage(object)
                                }, null, 8 /* PROPS */, ["label", "click-action"]))
                              : createCommentVNode("v-if", true),
                            createCommentVNode(" Delete "),
                            ($setup.canDeleteVehicle())
                              ? (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                                  key: 1,
                                  label: _ctx.$t('global.delete') + ' ' + _ctx.$t('objects.vehicles.single'),
                                  icon: "fas fa-trash",
                                  template: 'danger',
                                  "click-action": () => $setup.deleteVehicle(object.id)
                                }, null, 8 /* PROPS */, ["label", "click-action"]))
                              : createCommentVNode("v-if", true)
                          ]),
                          _: 2 /* DYNAMIC */
                        }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["user_id", "reg_1"]))
                      : createCommentVNode("v-if", true)
                  ]))
                : createCommentVNode("v-if", true)
            ]))
          }), 128 /* KEYED_FRAGMENT */))
        ]),
        createBaseVNode("tfoot", null, [
          createBaseVNode("tr", null, [
            createBaseVNode("td", _hoisted_10$e, toDisplayString(_ctx.$t("tables.showing")) + " " + toDisplayString($setup.props.vehicles.length) + " " + toDisplayString(_ctx.$t("objects.vehicles.multiple")), 1 /* TEXT */)
          ])
        ])
      ])
    ])
  ]))
}
const VehiclesTable = /*#__PURE__*/_export_sfc(_sfc_main$S, [['render',_sfc_render$l],['__file',"vehiclesTable.vue"]]);

const _sfc_main$R = /* @__PURE__ */ defineComponent({
  __name: "PaginationDisplayFilters",
  props: {
    departmentColumn: {
      type: String || void 0,
      default: void 0,
      required: false
    },
    productColumn: {
      type: String || void 0,
      default: void 0,
      required: false
    },
    columnLabels: {
      type: Object || void 0,
      default: void 0,
      required: false
      // Example: { department: 'Department', product: 'Product Type' }
    }
  },
  setup(__props, { expose: __expose }) {
    __expose();
    const paginatedList = inject(PaginatedListKey, paginatedListModule);
    const { setFilter, getFilter } = paginatedList;
    const props = __props;
    const getOptionsForSelect = (options, searchQuery) => {
      if (!searchQuery) return options;
      const query = searchQuery.toLowerCase();
      let filteredOptions = options;
      filteredOptions = filteredOptions.sort((a, b) => {
        const aStartsWith = a.label.toLowerCase().startsWith(query) ? -1 : 1;
        const bStartsWith = b.label.toLowerCase().startsWith(query) ? -1 : 1;
        return aStartsWith - bStartsWith;
      });
      filteredOptions = filteredOptions.filter((option) => option.label.toLowerCase().includes(query));
      return filteredOptions;
    };
    const setFilterValue = (filterName, value) => {
      setFilter(filterName, value);
    };
    const getFilterValue = (filterName) => {
      return getFilter(filterName);
    };
    const departmentFilter = ref({
      label: SessionUser_default.functions.ucFirst(SessionUser_default.objects.departments.meta.labels.single),
      columnName: props.departmentColumn || "department_id",
      type: "select",
      multiple: false,
      loading: false,
      searchable: true,
      placeholder: SessionUser_default.objects.global.language.search,
      value: props.departmentColumn ? getFilterValue(props.departmentColumn) : void 0,
      loadFunction: async () => {
        if (departmentFilter.value.loading) return;
        departmentFilter.value.loading = true;
        try {
          const departments = await SessionUser_default.objects.departments.get.all();
          departmentFilter.value.options = [
            { label: SessionUser_default.objects.global.language.all, value: "*" },
            ...departments.map((dept) => ({
              label: dept.name,
              value: dept.id
            }))
          ];
        } catch (error) {
          console.error("Error loading departments:", error);
        } finally {
          departmentFilter.value.loading = false;
        }
      },
      options: [
        { label: SessionUser_default.objects.global.language.all, value: "*" }
        // Additional options can be loaded dynamically
      ],
      onChange: (value) => {
        setFilterValue(props.departmentColumn || "department_id", value);
        departmentFilter.value.searchQuery = value.toString();
        departmentFilter.value.value = value;
      },
      onInput: (value) => {
        departmentFilter.value.searchQuery = value.toString();
      }
    });
    const productFilter = ref({
      label: SessionUser_default.functions.ucFirst(SessionUser_default.objects.products.meta.labels.single),
      columnName: props.productColumn || "product",
      type: "select",
      multiple: false,
      loading: false,
      searchable: true,
      placeholder: SessionUser_default.objects.global.language.search,
      value: props.productColumn ? getFilterValue(props.productColumn) : void 0,
      loadFunction: async () => {
        if (productFilter.value.loading) return;
        productFilter.value.loading = true;
        try {
          const productTypes = await SessionUser_default.objects.vehicles.columns.type.options();
          productFilter.value.options = [
            { label: SessionUser_default.objects.global.language.all, value: "*" },
            ...productTypes.map((type) => ({
              label: type.name,
              value: type.id
            }))
          ];
        } catch (error) {
          console.error("Error loading product types:", error);
        } finally {
          productFilter.value.loading = false;
        }
      },
      options: [
        { label: SessionUser_default.objects.global.language.all, value: "*" }
        // Additional options can be loaded dynamically
      ],
      onChange: (value) => {
        setFilterValue(props.productColumn || "product", value);
        productFilter.value.searchQuery = value.toString();
        productFilter.value.value = value;
      },
      onInput: (value) => {
        productFilter.value.searchQuery = value.toString();
      }
    });
    const filters = computed(() => {
      const filterList = [];
      if (props.departmentColumn) {
        filterList.push(departmentFilter.value);
      }
      if (props.productColumn) {
        filterList.push(productFilter.value);
      }
      return filterList;
    });
    const loadFilters = async () => {
      for (const filter of filters.value) {
        if (filter.loadFunction) {
          await filter.loadFunction();
        }
      }
    };
    const isFilterSet = (filter) => {
      if (filter.multiple) {
        return Array.isArray(filter.value) && filter.value.length > 0;
      } else {
        return filter.value !== void 0 && filter.value !== null && filter.value !== "*";
      }
    };
    onMounted(() => {
      loadFilters();
    });
    const renderFilterName = (filter) => {
      return props?.columnLabels?.[filter.columnName] || filter.label;
    };
    const __returned__ = { paginatedList, setFilter, getFilter, props, getOptionsForSelect, setFilterValue, getFilterValue, departmentFilter, productFilter, filters, loadFilters, isFilterSet, renderFilterName, SessionUser: SessionUser_default, get BAutocomplete() {
      return BAutocomplete;
    } };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$k = {
  key: 0,
  class: "column is-narrow"
};
const _hoisted_2$h = { class: "field mb-0" };
const _hoisted_3$h = { class: "label is-small" };
const _hoisted_4$h = { class: "is-float-right" };
const _hoisted_5$g = ["onClick"];
const _hoisted_6$g = { class: "mr-1" };
const _hoisted_7$f = { class: "control" };
const _hoisted_8$f = {
  key: 0,
  class: "select"
};
const _hoisted_9$e = ["value", "onChange"];
const _hoisted_10$d = ["value"];
function _sfc_render$k(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(true), createElementBlock(
    Fragment,
    null,
    renderList($setup.filters, (filter) => {
      return openBlock(), createElementBlock(
        Fragment,
        {
          key: filter.label
        },
        [
          createCommentVNode(" Select "),
          filter.type === "select" ? (openBlock(), createElementBlock("div", _hoisted_1$k, [
            createBaseVNode("div", _hoisted_2$h, [
              createCommentVNode(" Label "),
              createBaseVNode("label", _hoisted_3$h, [
                createTextVNode(
                  toDisplayString($setup.renderFilterName(filter)) + " ",
                  1
                  /* TEXT */
                ),
                createBaseVNode("span", _hoisted_4$h, [
                  createCommentVNode(' Reset "button" '),
                  $setup.isFilterSet(filter) ? (openBlock(), createElementBlock("span", {
                    key: 0,
                    onClick: ($event) => filter.onChange ? filter.onChange(filter.multiple ? [] : "*") : null,
                    class: "is-clickable"
                  }, [
                    createBaseVNode(
                      "span",
                      _hoisted_6$g,
                      toDisplayString($setup.SessionUser.objects.global.language.reset),
                      1
                      /* TEXT */
                    ),
                    _cache[0] || (_cache[0] = createBaseVNode(
                      "span",
                      { class: "icon is-small" },
                      [
                        createBaseVNode("i", { class: "fas fa-times-circle" })
                      ],
                      -1
                      /* CACHED */
                    ))
                  ], 8, _hoisted_5$g)) : createCommentVNode("v-if", true)
                ])
              ]),
              createBaseVNode("div", _hoisted_7$f, [
                createCommentVNode(" Single select "),
                !filter.multiple ? (openBlock(), createElementBlock("div", _hoisted_8$f, [
                  createCommentVNode(" Searchable (autocomplete) "),
                  filter.searchable ? (openBlock(), createBlock($setup["BAutocomplete"], {
                    key: 0,
                    loading: filter.loading,
                    placeholder: filter.placeholder || "",
                    "open-on-focus": true,
                    icon: filter.icon || "",
                    data: $setup.getOptionsForSelect(filter.options || [], filter.searchQuery).map((option) => option.label) || [],
                    "model-value": filter.options?.find((option) => option.value === filter.value)?.label || "",
                    onInput: (value) => {
                      const selectedOption = filter.options?.find((option) => option.label === value);
                      if (selectedOption) {
                        filter.onChange ? filter.onChange(selectedOption.value) : null;
                      }
                      console.warn("Search input: ", value.target.value);
                      filter.onInput ? filter.onInput(value.target.value) : null;
                    },
                    onSelect: (value) => {
                      const selectedOption = filter.options?.find((option) => option.label === value);
                      if (selectedOption) {
                        filter.onChange ? filter.onChange(selectedOption.value) : null;
                      }
                    }
                  }, null, 8, ["loading", "placeholder", "icon", "data", "model-value", "onInput", "onSelect"])) : (openBlock(), createElementBlock(
                    Fragment,
                    { key: 1 },
                    [
                      createCommentVNode(" Regular select "),
                      createBaseVNode("select", {
                        value: filter.value,
                        onChange: (event) => {
                          const selectedValue = event.target.value;
                          filter.onChange ? filter.onChange(selectedValue) : null;
                        }
                      }, [
                        (openBlock(true), createElementBlock(
                          Fragment,
                          null,
                          renderList(filter.options, (option) => {
                            return openBlock(), createElementBlock("option", {
                              key: option.value,
                              value: option.value
                            }, toDisplayString(option.label), 9, _hoisted_10$d);
                          }),
                          128
                          /* KEYED_FRAGMENT */
                        ))
                      ], 40, _hoisted_9$e)
                    ],
                    2112
                    /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
                  ))
                ])) : createCommentVNode("v-if", true),
                createCommentVNode(" Multiple select goes here when relevant... ")
              ])
            ])
          ])) : createCommentVNode("v-if", true),
          createCommentVNode(" Date Picker "),
          createCommentVNode(" ... Other filter types can be added here ... ")
        ],
        64
        /* STABLE_FRAGMENT */
      );
    }),
    128
    /* KEYED_FRAGMENT */
  );
}
const PaginationDisplayFilters = /* @__PURE__ */ _export_sfc(_sfc_main$R, [["render", _sfc_render$k], ["__file", "PaginationDisplayFilters.vue"]]);

const _sfc_main$Q = {
  __name: 'VehiclesPagination',
  props: {
  endpoint: {
    type: String,
    required: false,
    default: "/vehicles",
  },
  customer_id: {
    type: Number,
    required: false,
    default: null,
  },
  add_other_customer_id: {
    type: Number,
    required: false,
    default: null,
  },
  userScopedUserId: {
    type: [Number, String],
    required: false,
    default: null,
  },
  superuserPage: {
    type: Boolean,
    required: false,
    default: false,
  },
  onAfterMutation: {
    type: Function,
    required: false,
    default: null,
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const { t } = useI18n();

/**
 * Router
 */
const router = useRouter();
const isUserRoute = computed(() => router.currentRoute.value.path.startsWith("/user"));
const canAddVehicle = computed(() => SessionUser.canAccessCustomerFeature("vehicles", "add"));

const props = __props;
setEndpoint(props.endpoint, false);
if (props.customer_id) {
  setFilter("customer_id", props.customer_id, false);
}
loadList();

const reloadVehicles = async () => {
  await loadList();
  if (typeof props.onAfterMutation === "function") {
    await props.onAfterMutation();
  }
};

const __returned__ = { t, router, isUserRoute, canAddVehicle, props, reloadVehicles, list, loadList, setEndpoint, setFilter, SessionUser, get useRouter() { return useRouter }, VehiclesTable, computed, PaginationDisplayFilters, Colors, TableLabeledPagination, get useI18n() { return useI18n } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$j = { class: "vehicles-pagination" };
const _hoisted_2$g = { class: "column vehicles-pagination__filter-action-column" };
const _hoisted_3$g = { class: "vehicles-pagination__filter-action-row" };
const _hoisted_4$g = { class: "vehicles-pagination__filters" };
const _hoisted_5$f = {
  key: 0,
  class: "vehicles-pagination__add-action"
};
const _hoisted_6$f = {
  key: 1,
  class: "vehicles-pagination__add-action"
};

function _sfc_render$j(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$j, [
    createVNode($setup["TableLabeledPagination"], { label: "Oversigt over registrerede køretøjer" }, {
      paginationDisplayFiltersElement: withCtx(() => [
        createBaseVNode("div", _hoisted_2$g, [
          createBaseVNode("div", _hoisted_3$g, [
            createBaseVNode("div", _hoisted_4$g, [
              createVNode($setup["PaginationDisplayFilters"], {
                productColumn: 'type',
                columnLabels: { type: $setup.SessionUser.objects.vehicles.columns.type.label }
              }, null, 8 /* PROPS */, ["columnLabels"])
            ]),
            (_ctx.$slots.actions)
              ? (openBlock(), createElementBlock("div", _hoisted_5$f, [
                  _cache[1] || (_cache[1] = createBaseVNode("label", { class: "label is-small" }, " ", -1 /* CACHED */)),
                  renderSlot(_ctx.$slots, "actions", {}, undefined, true)
                ]))
              : createCommentVNode("v-if", true),
            createCommentVNode(" Create a new vehicle, if the route is /user "),
            ($setup.isUserRoute && $setup.canAddVehicle)
              ? (openBlock(), createElementBlock("div", _hoisted_6$f, [
                  _cache[2] || (_cache[2] = createBaseVNode("label", { class: "label is-small" }, " ", -1 /* CACHED */)),
                  createBaseVNode("button", {
                    class: "button is-link button-same-width vehicles-pagination__add-button",
                    onClick: _cache[0] || (_cache[0] = $event => ($setup.SessionUser.objects.vehicles.functions.showCreateObjectForCustomerForm($setup.props.customer_id, () => $setup.loadList()))),
                    style: normalizeStyle([{"text-decoration-line":"none"}, { 'color': $setup.Colors.buttons.textColor, 'background-color': $setup.Colors.buttons.backgroundColor }]),
                    "data-testid": "user-vehicles-add"
                  }, toDisplayString($setup.t('user_vehicles.add_vehicle')), 5 /* TEXT, STYLE */)
                ]))
              : createCommentVNode("v-if", true)
          ])
        ])
      ]),
      default: withCtx(() => [
        createVNode($setup["VehiclesTable"], {
          vehicles: $setup.list,
          show_add_vehicle: $setup.props.customer_id,
          add_other_customer_id: $setup.props.add_other_customer_id,
          "reload-list": $setup.reloadVehicles,
          "user-scoped-user-id": $setup.props.userScopedUserId,
          "superuser-page": $setup.props.superuserPage
        }, null, 8 /* PROPS */, ["vehicles", "show_add_vehicle", "add_other_customer_id", "user-scoped-user-id", "superuser-page"])
      ]),
      _: 3 /* FORWARDED */
    })
  ]))
}
const VehiclesPagination = /*#__PURE__*/_export_sfc(_sfc_main$Q, [['render',_sfc_render$j],['__scopeId',"data-v-959b841e"],['__file',"VehiclesPagination.vue"]]);

const _sfc_main$P = {
  __name: 'CustomerModal',
  props: {
  user_id: {
    type: Number,
    required: false,
    default: null,
  },
  customer_id: {
    type: Number,
    required: false,
    default: null,
  },
},
  emits: ["closeModal", "saveChanges"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const { t } = useI18n();
const props = __props;

const tabs = ref([
  { name: SessionUser.objects.global.language.customer, slot: 'customer', icon: 'fas fa-user', hidden: false },
  { name: SessionUser.objects.vehicles.meta.title, slot: 'vehicles', icon: 'fas fa-car', hidden: false },
  { name: SessionUser.objects.vehicles.columns.wash_subscription.label + ' ' + SessionUser.objects.collectedOrderInvoices.meta.labels.multiple, slot: 'subscription', icon: 'fas fa-file-invoice', hidden: false },

]);

const emit = __emit;

const closeModal = () => {
  emit("closeModal");
};

// Listen for esc key to close the modal
const handleKeydown = (event) => {
  if (event.key === "Escape") {
    closeModal();
  }
};
window.addEventListener("keydown", handleKeydown);

const user = ref(null);

const loadUser = async () => {
  if (props.user_id) {
    // Load the user from the server
    SessionUser.request(
        '/superuser/user',
        'GET',
        {
          user_id: props.user_id,
        },
    ).then(response => {
      user.value = response.data.data;
      // Select the customer if it is not null
      if (user.value.customer_number) {
        customer_id.value = user.value.customer_number;
        searchAndSelectCustomer(user.value.customer_number);
      }
      // Load the vehicles for the user
      getUserVehicles();
    }).catch(error => {
      console.error("Error loading user:", error);
    });
  }
};

const getUserKey = (key, fallback = null, loading = null) => {
  if (user.value === null) {
    return loading ? loading : (fallback ?? t('modals.unknown_customer'));
  }
  if (user.value[key] === undefined) {
    return fallback ?? t('modals.unknown_customer');
  }
  return user.value[key];
};

const getUserVehicles = () => {
  SessionUser.request(
      '/vehicles',
      'GET',
      {
        filters: 'customer_id:' + user.value.customer_number,
      },
  ).then(response => {
    user.value.vehicles = response.data.data;
  }).catch(error => {
    console.error("Error loading vehicles:", error);
  });
};

loadUser();

const __returned__ = { t, props, tabs, emit, closeModal, handleKeydown, user, loadUser, getUserKey, getUserVehicles, ref, get useI18n() { return useI18n }, SessionUser, InvoiceOrdersPagination, ElementTabsBox, CollectedOrderInvoicesOverview, customer_id, searchAndSelectCustomer, isCustomerSelected, PosSelectedCustomer, CollectedOrderInvoices: CollectedOrderInvoices$1, VehiclesPagination, VehiclesTable, OrdersTable };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$i = {
  class: "modal is-active",
  ref: "modal"
};
const _hoisted_2$f = { class: "modal-card" };
const _hoisted_3$f = { class: "modal-card-head" };
const _hoisted_4$f = { class: "modal-card-title" };
const _hoisted_5$e = { class: "modal-card-body" };
const _hoisted_6$e = { class: "content" };
const _hoisted_7$e = {
  class: "progress is-small is-dark",
  max: "100"
};
const _hoisted_8$e = { class: "modal-card-foot" };
const _hoisted_9$d = { class: "buttons" };
const _hoisted_10$c = { class: "button" };

function _sfc_render$i(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$i, [
    createBaseVNode("div", {
      class: "modal-background",
      onClick: $setup.closeModal
    }),
    createBaseVNode("div", _hoisted_2$f, [
      createBaseVNode("header", _hoisted_3$f, [
        createBaseVNode("p", _hoisted_4$f, toDisplayString($setup.getUserKey('customer_name', $setup.t('modals.unknown_customer'), $setup.t('common.loading'))), 1 /* TEXT */),
        createBaseVNode("button", {
          class: "delete",
          "aria-label": "close",
          onClick: $setup.closeModal
        })
      ]),
      createBaseVNode("section", _hoisted_5$e, [
        createCommentVNode(" Content ... "),
        ($setup.user !== null)
          ? (openBlock(), createBlock($setup["ElementTabsBox"], {
              key: 0,
              tabs: $setup.tabs,
              "default-active-tab": "customer",
              class: "is-boxed",
              allowCompactWhenOneTab: true
            }, {
              customer: withCtx(() => [
                ($setup.isCustomerSelected)
                  ? (openBlock(), createBlock($setup["PosSelectedCustomer"], { key: 0 }))
                  : createCommentVNode("v-if", true)
              ]),
              vehicles: withCtx(() => [
                createVNode($setup["VehiclesTable"], {
                  vehicles: $setup.user.vehicles,
                  show_add_vehicle: false,
                  compact: true,
                  "reload-list": $setup.getUserVehicles
                }, null, 8 /* PROPS */, ["vehicles"])
              ]),
              subscription: withCtx(() => [
                createVNode($setup["OrdersTable"], {
                  orders: $setup.user.wash_subscription_transactions,
                  compact: true,
                  "reload-list": $setup.loadUser
                }, null, 8 /* PROPS */, ["orders"])
              ]),
              _: 1 /* STABLE */
            }, 8 /* PROPS */, ["tabs"]))
          : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
              createCommentVNode(" Loading state "),
              createBaseVNode("div", _hoisted_6$e, [
                createBaseVNode("p", null, toDisplayString($setup.t('modals.fetching_data')), 1 /* TEXT */),
                createBaseVNode("p", null, toDisplayString($setup.t('modals.please_wait')), 1 /* TEXT */)
              ]),
              createBaseVNode("progress", _hoisted_7$e, toDisplayString($setup.t('common.loading')), 1 /* TEXT */)
            ], 64 /* STABLE_FRAGMENT */))
      ]),
      createBaseVNode("footer", _hoisted_8$e, [
        createBaseVNode("div", _hoisted_9$d, [
          createBaseVNode("button", {
            class: "button is-success",
            onClick: $setup.loadUser
          }, toDisplayString($setup.SessionUser.objects.global.language.reload), 1 /* TEXT */),
          createBaseVNode("button", _hoisted_10$c, toDisplayString($setup.SessionUser.objects.global.language.close), 1 /* TEXT */)
        ])
      ])
    ])
  ], 512 /* NEED_PATCH */))
}
const CustomerModal = /*#__PURE__*/_export_sfc(_sfc_main$P, [['render',_sfc_render$i],['__file',"CustomerModal.vue"]]);

const desktopFlyoutMinViewportWidth = 1400;
const desktopFlyoutRootPanelWidthRem = 15;
const desktopFlyoutSubmenuWidthRem = 17;
const desktopFlyoutNestedPanelWidthRem = 17;
const desktopFlyoutPanelGapPx = 12;

const SELF_SERVE_WASH_ATTACHMENT_TYPE$1 = "SELF_SERVE_WASH";


const _sfc_main$O = {
  __name: 'ActionSettingsWheelButton',
  props: {
  icon: {
    type: String,
    default: "fas fa-cog",
  },
  label: {
    type: String,
    default: "",
  },
  triggerButtonVariant: {
    type: String,
    default: "dark",
  },
  user_id: {
    type: Number,
    default: null,
  },
  order_id: {
    type: Number,
    default: null,
  },
  invoice_collection_id: {
    type: Number,
    default: null,
  },
  reg_1: {
    type: String,
    default: null,
  },
  reg_2: {
    type: String,
    default: null,
  },
  reg_3: {
    type: String,
    default: null,
  },
  order_booking_id: {
    type: Number,
    default: null,
  },
  customer_number: {
    type: Number,
    default: null,
  },
  refreshFunction: {
    type: Function,
    default: () => {
      console.warn("Refresh function is not defined");
    },
  },
  department_id: {
    type: Number,
    default: null,
  },
  attachments: {
    type: Array,
    default: () => [],
  },
  displayActionsDirectly: {
    type: Boolean,
    default: false,
  },
  directSectionKeys: {
    type: Array,
    default: () => [],
  },
  menuSections: {
    type: Array,
    default: () => [],
  },
  allowBookingCompletion: {
    type: Boolean,
    default: false,
  },
  allowBookingDeletion: {
    type: Boolean,
    default: false,
  },
  department_lane_id: {
    type: Number,
    default: null,
  },
  subuserGrant: {
    type: Object,
    default: null,
  },
  flagTarget: {
    type: Object,
    default: null,
  },
},
  emits: ["deleted", "flagCreated"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const { t } = useI18n();
const slots = useSlots();
const imageExtensions = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg"];
const officeExtensions = [".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx"];
const emit = __emit;
const emitDeleted = () => {
  emit("deleted");
};
const emitFlagCreated = (flag) => {
  emit("flagCreated", flag);
};
const props = __props;

const customerModalVisible = ref(false);
const userIdFromCustomerNumber = ref(null);
const userLookupRequestId = ref(0);
const isResolvingUserId = ref(false);
const customerRuleAttributes = ref([]);
const customerRuleAttributesLoaded = ref(false);
const customerRuleAttributesLoading = ref(false);
const dropdownRoot = ref(null);
const dropdownContent = ref(null);
const isDropdownOpen = ref(false);
const dropdownInstanceId = Math.random().toString(36).substring(2, 15);
const dropdownPlacement = ref("bottom");
const isDropdownPlacementLocked = ref(false);
const shouldOpenDropdownUp = ref(false);
const dropdownMaxHeight = ref(null);
const isDesktopFlyoutLayout = ref(false);
const isFixedPosition = ref(false);
const fixedPositionStyles = ref({});
const activeDesktopFlyoutSectionKey = ref(null);
const activeDesktopFlyoutSubsectionKey = ref(null);
const activeAttachmentId = ref(null);
const previewLoadingAttachmentId = ref(null);
const deletingAttachmentId = ref(null);
const previewSourcesById = ref({});
const previewRequestsInFlight = new Set();
const generatedObjectUrls = new Set();
let previewStateGeneration = 0;
let contentResizeObserver = null;
let dropdownLayoutUpdateId = 0;
const closeDropdown = () => {
  isDropdownOpen.value = false;
};

const openDropdown = () => {
  if (!isDropdownOpen.value) {
    window.dispatchEvent(
      new CustomEvent("action-settings-wheel:opened", {
        detail: {
          id: dropdownInstanceId,
        },
      })
    );
  }

  isDropdownOpen.value = true;
};

const toggleDropdown = () => {
  if (isDropdownOpen.value) {
    closeDropdown();
    return;
  }

  openDropdown();
};

const onActionSelected = () => {
  closeDropdown();
};

const isTextTriggerButton = computed(() => props.triggerButtonVariant === "text");
const isIconOnlyTriggerButton = computed(() => props.label.length === 0);
const getTriggerButtonClass = computed(() => ({
  button: true,
  "is-small": true,
  "is-dark": !isTextTriggerButton.value,
  "action-settings-wheel-trigger": true,
  "action-settings-wheel-trigger--active": isDropdownOpen.value,
  "action-settings-wheel-trigger--text": isTextTriggerButton.value,
  "action-settings-wheel-trigger--icon-only": isIconOnlyTriggerButton.value,
}));
const dropdownClass = computed(() => ({
  "is-active": isDropdownOpen.value,
  "is-up": shouldOpenDropdownUp.value,
}));
const dropdownContentClass = computed(() => ({
  "action-settings-wheel-dropdown-content--desktop-flyout": isDesktopFlyoutLayout.value,
}));
const dropdownMenuStyle = computed(() => {
  if (!isFixedPosition.value) {
    return {};
  }

  return {
    position: "fixed",
    zIndex: 10000,
    left: "auto",
    bottom: "auto",
    paddingTop: 0,
    paddingBottom: 0,
    ...fixedPositionStyles.value,
  };
});
const dropdownContentStyle = computed(() => {
  if (isFixedPosition.value) {
    const fixedStyles = {
      maxHeight: dropdownMaxHeight.value ? `${dropdownMaxHeight.value}px` : "95vh",
      overscrollBehavior: "contain",
    };

    if (isDesktopFlyoutLayout.value) {
      return {
        ...fixedStyles,
        overflow: "visible",
      };
    }

    return {
      ...fixedStyles,
      overflowY: "auto",
    };
  }

  if (!dropdownMaxHeight.value) {
    return {};
  }

  return {
    maxHeight: `${dropdownMaxHeight.value}px`,
    overflowY: "auto",
    overscrollBehavior: "contain",
  };
});

const resetDropdownLayout = () => {
  dropdownPlacement.value = "bottom";
  isDropdownPlacementLocked.value = false;
  shouldOpenDropdownUp.value = false;
  dropdownMaxHeight.value = null;
  isFixedPosition.value = false;
  fixedPositionStyles.value = {};
};

const isVisibleFixedInsetElement = (element) => {
  if (!(element instanceof HTMLElement)) {
    return false;
  }

  const styles = window.getComputedStyle(element);
  if (styles.display === "none" || styles.visibility === "hidden" || Number(styles.opacity || "1") === 0) {
    return false;
  }

  return styles.position === "fixed" || styles.position === "sticky";
};

const getInsetElements = (selectors) =>
  selectors.flatMap((selector) => Array.from(document.querySelectorAll(selector)));

const getViewportInsets = () => {
  const viewportPadding = 12;
  const fixedTopElements = Array.from(new Set(getInsetElements([".navbar.is-fixed-top"])));
  const fixedBottomElements = Array.from(
    new Set(getInsetElements([".navbar.is-fixed-bottom", ".fixed-bottom-footer", ".request-queue-progress-shell"]))
  );

  const topInset = fixedTopElements.reduce((maxInset, element) => {
    if (!isVisibleFixedInsetElement(element)) {
      return maxInset;
    }

    const rect = element.getBoundingClientRect();
    if (rect.bottom <= 0 || rect.top > viewportPadding) {
      return maxInset;
    }

    return Math.max(maxInset, Math.ceil(rect.bottom));
  }, 0);

  const bottomInset = fixedBottomElements.reduce((maxInset, element) => {
    if (!isVisibleFixedInsetElement(element)) {
      return maxInset;
    }

    const rect = element.getBoundingClientRect();
    if (rect.top >= window.innerHeight || rect.bottom < window.innerHeight - viewportPadding) {
      return maxInset;
    }

    return Math.max(maxInset, Math.ceil(window.innerHeight - rect.top));
  }, 0);

  return {
    top: topInset + viewportPadding,
    bottom: bottomInset + viewportPadding,
  };
};

const getDropdownPlacementSpaces = (triggerRect, viewportInsets = getViewportInsets()) => ({
  bottom: Math.max(window.innerHeight - triggerRect.bottom - viewportInsets.bottom, 0),
  top: Math.max(triggerRect.top - viewportInsets.top, 0),
});

const resolveDropdownPlacement = (triggerRect, menuHeight, viewportInsets = getViewportInsets()) => {
  const spaces = getDropdownPlacementSpaces(triggerRect, viewportInsets);

  return menuHeight > spaces.bottom && spaces.top > spaces.bottom ? "top" : "bottom";
};

const getDropdownAvailableHeight = (triggerRect, viewportInsets = getViewportInsets()) => {
  const spaces = getDropdownPlacementSpaces(triggerRect, viewportInsets);

  return dropdownPlacement.value === "top" ? spaces.top : spaces.bottom;
};

const lockDropdownPlacement = (triggerRect, menuHeight, viewportInsets = getViewportInsets()) => {
  if (!isDropdownPlacementLocked.value) {
    dropdownPlacement.value = resolveDropdownPlacement(triggerRect, menuHeight, viewportInsets);
    isDropdownPlacementLocked.value = true;
  }

  shouldOpenDropdownUp.value = dropdownPlacement.value === "top";
};

const updateDropdownLayout = async () => {
  const updateId = ++dropdownLayoutUpdateId;

  if (!isDropdownOpen.value || !dropdownRoot.value || !dropdownContent.value) {
    resetDropdownLayout();
    return;
  }

  await nextTick();

  if (updateId !== dropdownLayoutUpdateId || !isDropdownOpen.value || !dropdownRoot.value || !dropdownContent.value) {
    return;
  }

  const triggerElement = dropdownRoot.value.querySelector(".dropdown-trigger");
  const triggerRect = (triggerElement ?? dropdownRoot.value).getBoundingClientRect();
  syncDesktopFlyoutState(triggerRect);

  await nextTick();

  if (updateId !== dropdownLayoutUpdateId || !isDropdownOpen.value || !dropdownContent.value) {
    return;
  }

  const viewportInsets = getViewportInsets();
  const viewportTop = viewportInsets.top;
  const viewportBottom = window.innerHeight - viewportInsets.bottom;
  const menuHeight = Math.ceil(dropdownContent.value.scrollHeight);
  lockDropdownPlacement(triggerRect, menuHeight, viewportInsets);
  const availableHeight = getDropdownAvailableHeight(triggerRect, viewportInsets);
  const nextMaxHeight = availableHeight > 0 && menuHeight > availableHeight ? Math.floor(availableHeight) : null;

  dropdownMaxHeight.value = nextMaxHeight;

  await nextTick();

  if (updateId !== dropdownLayoutUpdateId || !isDropdownOpen.value || !dropdownContent.value) {
    return;
  }

  syncDesktopFlyoutPosition();

  await nextTick();

  if (updateId !== dropdownLayoutUpdateId || !isDropdownOpen.value || !dropdownContent.value) {
    return;
  }

  const renderedMenuRect = dropdownContent.value.getBoundingClientRect();
  const overflowAbove = Math.max(viewportTop - renderedMenuRect.top, 0);
  const overflowBelow = Math.max(renderedMenuRect.bottom - viewportBottom, 0);

  if (overflowAbove <= 0 && overflowBelow <= 0) {
    return;
  }

  const boundedHeight = Math.floor(renderedMenuRect.height - overflowAbove - overflowBelow);
  dropdownMaxHeight.value = boundedHeight > 0 ? boundedHeight : 1;

  await nextTick();

  if (updateId !== dropdownLayoutUpdateId || !isDropdownOpen.value) {
    return;
  }

  syncDesktopFlyoutPosition();
};

const onDocumentClick = (event) => {
  if (!isDropdownOpen.value) {
    return;
  }

  if (dropdownRoot.value && !dropdownRoot.value.contains(event.target)) {
    closeDropdown();
  }
};

const onDocumentKeydown = (event) => {
  if (event.key === "Escape") {
    closeDropdown();
  }
};

const onActionSettingsWheelOpened = (event) => {
  if (event?.detail?.id !== dropdownInstanceId) {
    closeDropdown();
  }
};

const onViewportChange = () => {
  if (!isDropdownOpen.value) {
    return;
  }

  void updateDropdownLayout();
};

const resolveUserId = async () => {
  if (props.user_id) {
    isResolvingUserId.value = false;
    userIdFromCustomerNumber.value = props.user_id;
    return;
  }

  if (!props.customer_number) {
    isResolvingUserId.value = false;
    userIdFromCustomerNumber.value = null;
    return;
  }

  const currentLookupId = userLookupRequestId.value + 1;
  userLookupRequestId.value = currentLookupId;
  isResolvingUserId.value = true;

  try {
    const response = await SessionUser.adminUser.customers.fromCustomerNumber.getUserId(props.customer_number);
    if (currentLookupId !== userLookupRequestId.value) {
      return;
    }

    userIdFromCustomerNumber.value = response?.data?.data?.user_id ?? null;
  } catch (error) {
    if (currentLookupId !== userLookupRequestId.value) {
      return;
    }

    userIdFromCustomerNumber.value = null;
    console.error(error);
  } finally {
    if (currentLookupId === userLookupRequestId.value) {
      isResolvingUserId.value = false;
    }
  }
};

const resetCustomerRuleState = () => {
  customerRuleAttributes.value = [];
  customerRuleAttributesLoaded.value = false;
  customerRuleAttributesLoading.value = false;
};

const loadCustomerRuleAttributes = async ({ force = false } = {}) => {
  if (!canViewCustomerRules.value || !customerAttributeTarget.value) {
    return customerRuleAttributes.value;
  }

  if (!force && (customerRuleAttributesLoaded.value || customerRuleAttributesLoading.value)) {
    return customerRuleAttributes.value;
  }

  customerRuleAttributesLoading.value = true;

  try {
    const response = await listCustomerAttributes(customerAttributeTarget.value);
    customerRuleAttributes.value = extractCustomerAttributesData(response);
    customerRuleAttributesLoaded.value = true;
  } catch (error) {
    console.warn("Unable to load customer attributes for action wheel", error);
  } finally {
    customerRuleAttributesLoading.value = false;
  }

  return customerRuleAttributes.value;
};

const toggleCustomerRuleAttribute = async (attribute, enabled) => {
  if (!customerAttributeTarget.value || !attribute) {
    return;
  }

  if (enabled) {
    await createCustomerAttribute(customerAttributeTarget.value, attribute);

    if (!activeCustomerRuleAttributes.value.has(attribute)) {
      customerRuleAttributes.value = [
        ...customerRuleAttributes.value,
        {
          attribute,
          ...customerAttributeTarget.value,
        },
      ];
    }

    return;
  }

  await deleteCustomerAttribute(customerAttributeTarget.value, attribute);
  customerRuleAttributes.value = customerRuleAttributes.value.filter((entry) => entry?.attribute !== attribute);
};

const showSetCustomerPassword = (userId) => {
  Swal.fire({
    title: t("admin.pos.settings_wheel.change_password"),
    html: `<input id="swal-input1" class="swal2-input" placeholder="${t("admin.pos.settings_wheel.enter_password")}">`,
    focusConfirm: false,
    preConfirm: () => {
      const password = document.getElementById("swal-input1").value;
      if (password === "") {
        Swal.showValidationMessage(t("admin.pos.settings_wheel.please_enter_password"));
      }
      return password;
    },
  }).then((result) => {
    if (result.isConfirmed) {
      const password = result.value;
      // Call the API to set the password
      SessionUser.request("/superuser/user/password", "POST", {
        user_id: userId,
        password: password,
      })
        .then(() => {
          Swal.fire({
            title: t("admin.pos.settings_wheel.password_changed"),
            text: t("admin.pos.settings_wheel.password_changed_text"),
            icon: "success",
          });
        })
        .catch((error) => {
          Swal.fire({
            title: t("common.error"),
            text: t("admin.pos.settings_wheel.error_changing_password"),
            icon: "error",
          });
        });
    }
  });
};

const redirectSuperUserInvoiceCollectionPage = (invoiceCollectionId) => {
  // Send the user to the invoice collection page (In a new tab)
  window.open(`/superuser/invoices/${invoiceCollectionId}`, "_blank");
};

const redirectDepartmentOrderPage = async (orderId, newTab = false) => {
  // Send the user to the order page (In a new tab)
  // Get the department id from the order
  await SessionUser.objects.orders.functions
    .get_department_id(props.order_id)
    .then((response) => {
      console.warn(response);
      // Get the department id from the response
      SessionUser.functions.redirectTo.department(response, "modules/pos/orders/" + orderId, !!newTab);
    })
    .catch((error) => {
      console.error(error);
    });
};

const normalizeInvoicePeriodFlagTarget = (target) => {
  if (!target || typeof target !== "object") {
    return null;
  }

  const targetType = String(target.target_type || target.targetType || "").trim();
  const targetId = Number.parseInt(String(target.target_id || target.targetId || ""), 10);
  if (!targetType || !Number.isInteger(targetId) || targetId < 1) {
    return null;
  }

  return {
    target_type: targetType,
    target_id: targetId,
    field: target.field || null,
  };
};

const getInvoicePeriodFlagTargetLabel = (target) => {
  if (!target || typeof target !== "object") {
    return t("admin.pos.settings_wheel.add_flag_target");
  }

  if (target.target_type === "collected_order_invoice") {
    return t("admin.pos.settings_wheel.add_flag_invoice_collection");
  }

  if (target.target_type === "order") {
    return t("admin.pos.settings_wheel.add_flag_order");
  }

  if (target.target_type === "order_field") {
    const orderFieldLabels = {
      customer: t("admin.pos.settings_wheel.add_flag_order_customer"),
      reference: t("admin.pos.settings_wheel.add_flag_order_reference"),
      po: t("admin.pos.settings_wheel.add_flag_order_po"),
      notes: t("admin.pos.settings_wheel.add_flag_order_notes"),
    };

    return orderFieldLabels[target.field] ?? t("admin.pos.settings_wheel.add_flag_order");
  }

  if (target.target_type === "order_item") {
    return t("admin.pos.settings_wheel.add_flag_order_item");
  }

  if (target.target_type === "order_item_field") {
    const orderItemFieldLabels = {
      notes: t("admin.pos.settings_wheel.add_flag_order_item_notes"),
      quantity: t("admin.pos.settings_wheel.add_flag_order_item_quantity"),
      reference: t("admin.pos.settings_wheel.add_flag_order_item_reference"),
      price: t("admin.pos.settings_wheel.add_flag_order_item_price"),
    };

    return orderItemFieldLabels[target.field] ?? t("admin.pos.settings_wheel.add_flag_order_item");
  }

  if (target.target_type === "customer") {
    return t("admin.pos.settings_wheel.add_flag_customer");
  }

  return t("admin.pos.settings_wheel.add_flag_target");
};

const defaultInvoicePeriodFlagTargets = computed(() => {
  const targets = [];
  const explicitTarget = normalizeInvoicePeriodFlagTarget(props.flagTarget);

  if (explicitTarget && explicitTarget.target_type !== "order_item") {
    targets.push({
      key: "custom",
      label: getInvoicePeriodFlagTargetLabel(explicitTarget),
      target: explicitTarget,
    });
  }

  if (props.invoice_collection_id) {
    targets.push({
      key: "collected-order-invoice",
      label: t("admin.pos.settings_wheel.add_flag_invoice_collection"),
      target: {
        target_type: "collected_order_invoice",
        target_id: props.invoice_collection_id,
      },
    });
  }

  if (props.order_id) {
    targets.push({
      key: "order",
      label: t("admin.pos.settings_wheel.add_flag_order"),
      target: {
        target_type: "order",
        target_id: props.order_id,
      },
    });
    [
      ["customer", t("admin.pos.settings_wheel.add_flag_order_customer")],
      ["reference", t("admin.pos.settings_wheel.add_flag_order_reference")],
      ["po", t("admin.pos.settings_wheel.add_flag_order_po")],
      ["notes", t("admin.pos.settings_wheel.add_flag_order_notes")],
    ].forEach(([field, label]) => {
      targets.push({
        key: `order-${field}`,
        label,
        target: {
          target_type: "order_field",
          target_id: props.order_id,
          field,
        },
      });
    });
  }

  if (explicitTarget?.target_type === "order_item") {
    [
      [null, t("admin.pos.settings_wheel.add_flag_order_item")],
      ["notes", t("admin.pos.settings_wheel.add_flag_order_item_notes")],
      ["quantity", t("admin.pos.settings_wheel.add_flag_order_item_quantity")],
      ["reference", t("admin.pos.settings_wheel.add_flag_order_item_reference")],
      ["price", t("admin.pos.settings_wheel.add_flag_order_item_price")],
    ].forEach(([field, label]) => {
      targets.push({
        key: `order-item-${field || "all"}`,
        label,
        target: {
          target_type: field ? "order_item_field" : "order_item",
          target_id: explicitTarget.target_id,
          field,
        },
      });
    });
  }

  if (props.customer_number && !targets.some((item) => item.target.target_type === "customer")) {
    targets.push({
      key: "customer",
      label: t("admin.pos.settings_wheel.add_flag_customer"),
      target: {
        target_type: "customer",
        target_id: props.customer_number,
      },
    });
  }

  const seen = new Set();
  return targets.filter((item) => {
    const key = `${item.target.target_type}:${item.target.target_id}:${item.target.field || ""}`;
    if (seen.has(key)) {
      return false;
    }
    seen.add(key);
    return true;
  });
});

const canAddInvoicePeriodFlag = computed(
  () =>
    SessionUser.canAccessSuperUser() &&
    SessionUser.hasPermission("add_invoice_period_flag") &&
    defaultInvoicePeriodFlagTargets.value.length > 0
);

const showCreateInvoicePeriodFlagForm = async (target) => {
  const result = await Swal.fire({
    title: t("admin.pos.settings_wheel.add_flag"),
    input: "textarea",
    inputPlaceholder: t("admin.pos.settings_wheel.add_flag_reason_placeholder"),
    inputValidator: (value) => {
      if (!value || String(value).trim() === "") {
        return t("admin.pos.settings_wheel.add_flag_reason_required");
      }
      return null;
    },
    showCancelButton: true,
    confirmButtonText: t("admin.pos.settings_wheel.add_flag"),
    cancelButtonText: t("common.cancel"),
  });

  if (!result.isConfirmed) {
    return;
  }

  const response = await SessionUser.request("/superuser/invoicing/period/flags", "POST", {
    ...target,
    reason: String(result.value || "").trim(),
  });

  emitFlagCreated(response?.data?.data ?? response?.data ?? response);
};

const hasUser = computed(() => Boolean(props.user_id || props.customer_number || userIdFromCustomerNumber.value));
const customerAttributeTarget = computed(() => {
  if (!hasUser.value) {
    return null;
  }

  const payload = buildCustomerAttributeTargetPayload({
    userId: props.user_id,
    customerNumber: props.customer_number,
  });

  return Object.keys(payload).length > 0 ? payload : null;
});
const canViewCustomerRules = computed(
  () => hasUser.value && SessionUser.canAccessSuperUser() && SessionUser.hasPermission("list_customer_attributes")
);
const customerRuleDepartmentId = computed(() => (
  props.department_id || SessionUser.functions?.getDepartmentIdFromUrl?.() || null
));
const customerRuleDefinitions = computed(() => getCustomerRuleDefinitions());
const activeCustomerRuleAttributes = computed(() => {
  const enabledAttributes = new Set();

  customerRuleAttributes.value.forEach((entry) => {
    const attributeKey = String(entry?.attribute || "").trim();
    if (attributeKey) {
      enabledAttributes.add(attributeKey);
    }
  });

  return enabledAttributes;
});
const customerRuleItems = computed(() =>
  customerRuleDefinitions.value.map((rule) => {
    const isEnabled = activeCustomerRuleAttributes.value.has(rule.attribute);
    const requiredPermission = isEnabled ? rule.deletePermission : rule.addPermission;

    return {
      attribute: rule.attribute,
      customerRuleActive: isEnabled,
      customerRuleAttribute: rule.attribute,
      customerRuleCustomerNumber: props.customer_number,
      customerRuleDepartmentId: customerRuleDepartmentId.value,
      description: t(rule.descriptionKey),
      disabled: !SessionUser.hasPermission(requiredPermission),
      key: `customer-rule-${rule.attribute}`,
      label: t(rule.labelKey),
      testId: `action-settings-wheel-toggle-customer-rule-${rule.attribute}`,
      type: "toggle",
      value: isEnabled,
    };
  })
);
const customerShortcutItems = computed(() => {
  if (!SessionUser.canAccessSuperUser() || !userIdFromCustomerNumber.value) {
    return [];
  }

  const userId = userIdFromCustomerNumber.value;
  return [
    {
      key: "customer-shortcut-overview",
      icon: "fas fa-user",
      label: t("admin.pos.settings_wheel.shortcut_overview"),
      clickAction: () => SessionUser.functions.redirectTo.superUser(`/users/${userId}`, true),
    },
    {
      key: "customer-shortcut-orders",
      icon: "fas fa-file-alt",
      label: t("admin.pos.settings_wheel.shortcut_orders"),
      clickAction: () => SessionUser.functions.redirectTo.superUser(`/users/${userId}/orders`, true),
    },
    {
      key: "customer-shortcut-pricing",
      icon: "fas fa-tags",
      label: t("admin.pos.settings_wheel.shortcut_pricing"),
      clickAction: () => SessionUser.functions.redirectTo.superUser(`/users/${userId}/pricing`, true),
    },
    {
      key: "customer-shortcut-other",
      icon: "fas fa-sliders-h",
      label: t("admin.pos.settings_wheel.shortcut_other"),
      clickAction: () => SessionUser.functions.redirectTo.superUser(`/users/${userId}/other`, true),
    },
    {
      key: "customer-shortcut-vehicles",
      icon: "fas fa-car",
      label: t("common.vehicles"),
      clickAction: () => SessionUser.functions.redirectTo.superUser(`/users/${userId}/vehicles`, true),
    },
  ];
});

watch(
  () => [props.user_id, props.customer_number],
  () => {
    resetCustomerRuleState();
    void resolveUserId();

    if (props.displayActionsDirectly || isDropdownOpen.value) {
      void loadCustomerRuleAttributes({ force: true });
    }
  },
  { immediate: true }
);

watch(
  () => props.displayActionsDirectly,
  (displayActionsDirectly) => {
    if (displayActionsDirectly) {
      void loadCustomerRuleAttributes();
    }
  },
  { immediate: true }
);

watch(isDropdownOpen, async (isOpen) => {
  if (!isOpen) {
    isDesktopFlyoutLayout.value = false;
    activeDesktopFlyoutSectionKey.value = null;
    clearAttachmentPreviewState();
    resetDropdownLayout();
    return;
  }

  await nextTick();

  if (dropdownContent.value) {
    dropdownContent.value.scrollTop = 0;
  }

  void loadCustomerRuleAttributes();
  void updateDropdownLayout();
});

const attachmentsFromOrder = ref([]);
const attachmentsFromOrderError = ref(null);
const normalizePositiveInteger = (value) => {
  const parsed = Number.parseInt(String(value ?? ""), 10);
  return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
};

const getAttachmentOtherPayload = (attachment) => attachment?.content?.other ?? null;

const isSelfServeWashAttachment = (attachment) => {
  const other = getAttachmentOtherPayload(attachment);
  return Boolean(other && typeof other === "object" && other.type === SELF_SERVE_WASH_ATTACHMENT_TYPE$1);
};

const getSelfServeWashAttachment = computed(() =>
  attachmentsFromOrder.value.find((attachment) => isSelfServeWashAttachment(attachment)) || null
);

const getSelfServeWashPayload = computed(() => getAttachmentOtherPayload(getSelfServeWashAttachment.value));

const getSelfServeWashCustomerNumber = computed(() =>
  normalizePositiveInteger(getSelfServeWashPayload.value?.customer_number)
);

const canAcceptSelfServeWashDraft = computed(() =>
  Boolean(
    props.order_id
    && getSelfServeWashCustomerNumber.value
    && normalizePositiveInteger(props.customer_number) !== getSelfServeWashCustomerNumber.value
    && (SessionUser.canAccessAdmin() || SessionUser.canAccessSuperUser())
  )
);

const isObjectUrl = (value) => typeof value === "string" && value.startsWith("blob:");

const releaseObjectUrl = (value) => {
  if (!isObjectUrl(value)) {
    return;
  }

  URL.revokeObjectURL(value);
  generatedObjectUrls.delete(value);
};

const clearAttachmentPreviewState = () => {
  previewStateGeneration += 1;
  previewRequestsInFlight.clear();
  Object.values(previewSourcesById.value).forEach((value) => {
    releaseObjectUrl(value);
  });
  previewSourcesById.value = {};
  previewLoadingAttachmentId.value = null;
  activeAttachmentId.value = null;
};

const getAttachmentLabel = (attachment) => {
  if (isSelfServeWashAttachment(attachment)) {
    const customerNumber = normalizePositiveInteger(attachment?.content?.other?.customer_number);
    return customerNumber
      ? t("admin.pos.settings_wheel.self_serve_wash_attachment_for_customer", { customerNumber })
      : t("admin.pos.settings_wheel.self_serve_wash_attachment");
  }

  const other = getAttachmentOtherPayload(attachment);
  const otherLabel = typeof other === "string"
    ? other
    : other && typeof other === "object"
      ? (other.label || other.type || JSON.stringify(other))
      : null;

  return (
    attachment?.content?.document ||
    attachment?.content?.image ||
    otherLabel ||
    `Attachment ${attachment?.id ?? ""}`.trim()
  );
};

const isWashCertificateAttachment = (attachment) => {
  const marker = String(getAttachmentOtherPayload(attachment) || "").trim().toUpperCase();
  if (marker === "WASH_CERTIFICATE") {
    return true;
  }

  return /(?:^|[/\\])wash[_-]?certificate.*\.pdf$/i.test(getAttachmentLabel(attachment));
};

const getAttachmentExtension = (attachment) => {
  const match = String(getAttachmentLabel(attachment))
    .toLowerCase()
    .match(/(\.[a-z0-9]+)$/);

  return match?.[1] || "";
};

const getAttachmentPreviewKind = (attachment) => {
  const extension = getAttachmentExtension(attachment);

  if (attachment?.content?.image || imageExtensions.includes(extension)) {
    return "image";
  }

  if (attachment?.content?.document || extension === ".pdf") {
    return officeExtensions.includes(extension) ? "office" : "document";
  }

  if (officeExtensions.includes(extension)) {
    return "office";
  }

  const other = getAttachmentOtherPayload(attachment);
  if (typeof other === "string" && other.startsWith("http")) {
    return "link";
  }

  if (other) {
    return "text";
  }

  return "none";
};

const formatAttachmentText = (attachment) => {
  const other = getAttachmentOtherPayload(attachment);
  if (isSelfServeWashAttachment(attachment)) {
    const parts = [
      t("admin.pos.settings_wheel.self_serve_wash_attachment"),
      other?.customer_number
        ? `${t("admin.pos.settings_wheel.self_serve_customer")}: #${other.customer_number}`
        : null,
      other?.subuser?.name || other?.subuser?.username || other?.subuser_id
        ? `${t("admin.pos.settings_wheel.self_serve_driver")}: ${other?.subuser?.name || other?.subuser?.username || `#${other.subuser_id}`}`
        : null,
      other?.license_plate
        ? `${t("pos.license_plate")}: ${other.license_plate}`
        : null,
      other?.elapsed_wash_time_seconds
        ? `${t("admin.pos.settings_wheel.self_serve_elapsed")}: ${Math.ceil(Number(other.elapsed_wash_time_seconds) / 60)} min`
        : null,
    ].filter(Boolean);

    return parts.join("\n");
  }

  if (typeof other === "string") {
    return other;
  }

  if (other && typeof other === "object") {
    return JSON.stringify(other, null, 2);
  }

  return "";
};

const getAttachmentPreviewPlaceholderIcon = (attachment) => {
  const previewKind = getAttachmentPreviewKind(attachment);

  if (previewKind === "image") {
    return "fas fa-image";
  }

  if (previewKind === "document" || previewKind === "office") {
    return "fas fa-file-alt";
  }

  if (previewKind === "link") {
    return "fas fa-link";
  }

  if (previewKind === "text") {
    return "fas fa-align-left";
  }

  return "fas fa-paperclip";
};

const getAttachmentPreviewPlaceholderLabel = (attachment) => {
  const extension = getAttachmentExtension(attachment).replace(".", "").toUpperCase();
  if (extension) {
    return extension;
  }

  const previewKind = getAttachmentPreviewKind(attachment);
  if (previewKind === "link") {
    return "LINK";
  }

  if (previewKind === "text") {
    return "TEXT";
  }

  return "FILE";
};

const activeAttachment = computed(() => {
  return attachmentsFromOrder.value.find((attachment) => attachment.id === activeAttachmentId.value) || null;
});

const activeAttachmentPreviewKind = computed(() => {
  if (!activeAttachment.value) {
    return "none";
  }

  return getAttachmentPreviewKind(activeAttachment.value);
});

const activeAttachmentPreviewSource = computed(() => {
  if (!activeAttachment.value) {
    return null;
  }

  return previewSourcesById.value[activeAttachment.value.id] ?? null;
});

const hasWashCertificateAttachment = computed(() =>
  attachmentsFromOrder.value.some((attachment) => isWashCertificateAttachment(attachment))
);

const hasCachedPreviewSource = (attachmentId) => {
  return Object.prototype.hasOwnProperty.call(previewSourcesById.value, attachmentId);
};

const buildAttachmentPreviewHeaders = () => {
  const headers = {};
  const token = window.localStorage.getItem("token");
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  const isSubuser = window.localStorage.getItem("is_subuser") === "true";
  const selectedCustomerNumber = window.localStorage.getItem("selected_customer_number");
  if (isSubuser && selectedCustomerNumber) {
    headers["X-Customer-Number"] = selectedCustomerNumber;
  }

  return headers;
};

const shouldRetryPreviewRequestWithAuth = (downloadLink) => {
  if (!downloadLink) {
    return false;
  }

  try {
    const previewUrl = new URL(downloadLink, window.location.origin);
    const apiOrigin = new URL(getReleaseRuntimeApiBaseUrl(), window.location.origin).origin;
    return previewUrl.origin === apiOrigin || previewUrl.origin === window.location.origin;
  } catch {
    return false;
  }
};

const fetchAttachmentPreviewBlob = async (downloadLink, withAuthHeaders = false) => {
  const requestConfig = {
    method: "GET",
  };

  if (withAuthHeaders) {
    requestConfig.headers = buildAttachmentPreviewHeaders();
  }

  const response = await fetch(downloadLink, requestConfig);
  if (!response.ok) {
    return null;
  }

  const fileBlob = await response.blob();
  if (!fileBlob || fileBlob.size === 0) {
    return null;
  }

  return fileBlob;
};

const createEmbeddablePreviewUrl = async (downloadLink) => {
  if (!downloadLink) {
    return null;
  }

  try {
    let fileBlob = await fetchAttachmentPreviewBlob(downloadLink, false);
    if (!fileBlob && shouldRetryPreviewRequestWithAuth(downloadLink)) {
      fileBlob = await fetchAttachmentPreviewBlob(downloadLink, true);
    }

    if (!fileBlob || fileBlob.size === 0) {
      return null;
    }

    const objectUrl = URL.createObjectURL(fileBlob);
    generatedObjectUrls.add(objectUrl);
    return objectUrl;
  } catch (error) {
    console.warn("Unable to create embeddable attachment preview blob", error);
    return null;
  }
};

const loadOrderAttachments = async () => {
  if (!props.order_id) {
    attachmentsFromOrder.value = [];
    attachmentsFromOrderError.value = null;
    clearAttachmentPreviewState();
    return [];
  }

  attachmentsFromOrderError.value = null;

  try {
    let response = await SessionUser.objects.orders.functions.fetchAttachments(props.order_id);
    if (!Array.isArray(response)) {
      response = [];
    }

    attachmentsFromOrder.value = response;

    if (!response.some((attachment) => attachment.id === activeAttachmentId.value)) {
      activeAttachmentId.value = null;
    }

    return response;
  } catch (error) {
    const parsedErrorMessage = SessionUser.functions.parseErrorMessage(error);
    console.warn("Error fetching attachments from order:", error, parsedErrorMessage);
    attachmentsFromOrder.value = [];
    attachmentsFromOrderError.value = `ERROR: ${parsedErrorMessage || "Failed to fetch attachments"}`;
    clearAttachmentPreviewState();
    return [];
  }
};

const resolveAttachmentDownloadLink = async (attachment) => {
  if (!props.order_id || !attachment?.id) {
    return null;
  }

  return SessionUser.objects.orders.functions.downloadAttachment(props.order_id, attachment.id, false);
};

const ensurePreviewSource = async (attachment) => {
  if (!attachment) {
    return null;
  }

  const currentPreviewStateGeneration = previewStateGeneration;
  const previewKind = getAttachmentPreviewKind(attachment);
  if (!["image", "document"].includes(previewKind)) {
    return null;
  }

  if (hasCachedPreviewSource(attachment.id) || previewRequestsInFlight.has(attachment.id)) {
    return previewSourcesById.value[attachment.id] ?? null;
  }

  previewRequestsInFlight.add(attachment.id);
  previewLoadingAttachmentId.value = attachment.id;

  try {
    const downloadLink = await resolveAttachmentDownloadLink(attachment);
    const previewSource = await createEmbeddablePreviewUrl(downloadLink);

    if (currentPreviewStateGeneration !== previewStateGeneration) {
      releaseObjectUrl(previewSource);
      return null;
    }

    previewSourcesById.value = {
      ...previewSourcesById.value,
      [attachment.id]: previewSource,
    };
    return previewSource;
  } catch (error) {
    console.warn("Unable to load attachment preview", attachment.id, error);
    if (currentPreviewStateGeneration === previewStateGeneration) {
      previewSourcesById.value = {
        ...previewSourcesById.value,
        [attachment.id]: null,
      };
    }
    return null;
  } finally {
    previewRequestsInFlight.delete(attachment.id);
    if (previewLoadingAttachmentId.value === attachment.id) {
      previewLoadingAttachmentId.value = null;
    }
  }
};

const setActiveAttachment = async (attachment) => {
  if (!attachment) {
    activeAttachmentId.value = null;
    return;
  }

  activeAttachmentId.value = attachment.id;
  await ensurePreviewSource(attachment);
};

const openAttachmentInNewTab = (url) => {
  if (!url) {
    return null;
  }

  return window.open(url, "_blank", "noopener,noreferrer");
};

const downloadAttachmentFile = (url, attachment) => {
  if (!url) {
    return;
  }

  const link = document.createElement("a");
  link.href = url;
  link.target = "_blank";
  link.rel = "noopener noreferrer";
  link.download = getAttachmentLabel(attachment);
  document.body.appendChild(link);
  link.click();
  link.remove();
};

const previewAttachment = async (attachment) => {
  try {
    const previewKind = getAttachmentPreviewKind(attachment);
    if (["image", "document"].includes(previewKind)) {
      const previewSource = (await ensurePreviewSource(attachment)) || (await resolveAttachmentDownloadLink(attachment));
      openAttachmentInNewTab(previewSource);
      return;
    }

    const downloadLink = await resolveAttachmentDownloadLink(attachment);
    openAttachmentInNewTab(downloadLink);
  } catch (error) {
    console.warn("Unable to preview attachment", attachment?.id, error);
    Swal.fire({
      title: t("common.error"),
      text: t("admin.pos.settings_wheel.error_downloading_attachment"),
      icon: "error",
    });
  }
};

const downloadAttachment = async (attachment) => {
  try {
    const downloadLink = await resolveAttachmentDownloadLink(attachment);
    downloadAttachmentFile(downloadLink, attachment);
  } catch (error) {
    Swal.fire({
      title: t("common.error"),
      text: t("admin.pos.settings_wheel.error_downloading_attachment"),
      icon: "error",
    });
  }
};

const printAttachment = async (attachment) => {
  try {
    const previewKind = getAttachmentPreviewKind(attachment);
    const downloadLink = await resolveAttachmentDownloadLink(attachment);

    if (!downloadLink) {
      return;
    }

    if (!["image", "document"].includes(previewKind)) {
      openAttachmentInNewTab(downloadLink);
      return;
    }

    const printableSource = (await ensurePreviewSource(attachment)) || downloadLink;
    if (previewKind === "image") {
      const printWindow = window.open("", "_blank", "noopener,noreferrer,width=960,height=720");
      if (!printWindow) {
        openAttachmentInNewTab(printableSource);
        return;
      }

      const escapedTitle = getAttachmentLabel(attachment).replace(/"/g, "&quot;");
      printWindow.document.write(`<!DOCTYPE html>
<html>
  <head>
    <title>${escapedTitle}</title>
    <style>
      html, body {
        margin: 0;
        min-height: 100%;
        background: #ffffff;
      }
      body {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      img {
        display: block;
        max-width: 100%;
        max-height: 100vh;
        object-fit: contain;
      }
    </style>
  </head>
  <body>
    <img id="attachment-print-image" src="${printableSource}" alt="" />
  </body>
</html>`);
      printWindow.document.close();

      const printableImage = printWindow.document.getElementById("attachment-print-image");
      if (!printableImage) {
        openAttachmentInNewTab(printableSource);
        return;
      }

      printableImage.addEventListener(
        "load",
        () => {
          printWindow.focus();
          window.setTimeout(() => {
            printWindow.print();
          }, 150);
        },
        { once: true }
      );
      printableImage.addEventListener(
        "error",
        () => {
          openAttachmentInNewTab(printableSource);
        },
        { once: true }
      );
      return;
    }

    const printWindow = window.open(printableSource, "_blank", "noopener,noreferrer");
    if (!printWindow) {
      openAttachmentInNewTab(printableSource);
      return;
    }

    const triggerPrint = () => {
      printWindow.focus();
      window.setTimeout(() => {
        printWindow.print();
      }, 250);
    };

    printWindow.addEventListener("load", triggerPrint, { once: true });
    window.setTimeout(triggerPrint, 900);
  } catch (error) {
    console.warn("Unable to print attachment", attachment?.id, error);
    Swal.fire({
      title: t("common.error"),
      text: t("admin.pos.settings_wheel.error_downloading_attachment"),
      icon: "error",
    });
  }
};

const removeAttachment = async (attachment) => {
  if (!props.order_id || !attachment?.id || deletingAttachmentId.value === attachment.id) {
    return;
  }

  deletingAttachmentId.value = attachment.id;

  try {
    const response = await SessionUser.objects.orders.functions.removeAttachment(props.order_id, attachment.id);
    if (!response) {
      throw new Error("Attachment delete failed");
    }

    releaseObjectUrl(previewSourcesById.value[attachment.id]);

    const nextPreviewSourcesById = { ...previewSourcesById.value };
    delete nextPreviewSourcesById[attachment.id];
    previewSourcesById.value = nextPreviewSourcesById;

    await loadOrderAttachments();
    await props.refreshFunction();
  } catch (error) {
    console.warn("Unable to delete attachment", attachment?.id, error);
    Swal.fire({
      title: t("common.error"),
      text: t("admin.pos.settings_wheel.error_downloading_attachment"),
      icon: "error",
    });
  } finally {
    deletingAttachmentId.value = null;
  }
};

watch(
  () => [attachmentsFromOrder.value.length, attachmentsFromOrderError.value, userIdFromCustomerNumber.value],
  () => {
    if (isDropdownOpen.value) {
      void updateDropdownLayout();
    }
  }
);

watch(
  () => props.order_id,
  () => {
    void loadOrderAttachments();
  },
  { immediate: true }
);

onMounted(() => {
  document.addEventListener("click", onDocumentClick);
  document.addEventListener("keydown", onDocumentKeydown);
  window.addEventListener("action-settings-wheel:opened", onActionSettingsWheelOpened);
  window.addEventListener("resize", onViewportChange);
  document.addEventListener("scroll", onViewportChange, true);

  contentResizeObserver = new ResizeObserver(() => {
    if (isDropdownOpen.value) {
      void updateDropdownLayout();
    }
  });

  if (dropdownContent.value) {
    contentResizeObserver.observe(dropdownContent.value);
  }
});

watch(dropdownContent, (newEl, oldEl) => {
  if (oldEl && contentResizeObserver) {
    contentResizeObserver.unobserve(oldEl);
  }
  if (newEl && contentResizeObserver) {
    contentResizeObserver.observe(newEl);
  }
});


onBeforeUnmount(() => {
  document.removeEventListener("click", onDocumentClick);
  document.removeEventListener("keydown", onDocumentKeydown);
  window.removeEventListener("action-settings-wheel:opened", onActionSettingsWheelOpened);
  window.removeEventListener("resize", onViewportChange);
  document.removeEventListener("scroll", onViewportChange, true);
  clearAttachmentPreviewState();

  if (contentResizeObserver) {
    contentResizeObserver.disconnect();
    contentResizeObserver = null;
  }
});

const onShowImpersonationQRCode = (src, directLink) => {
  Swal.fire({
    title: t("admin.pos.settings_wheel.scan_qr_to_login"),
    html: `<img src="${src}" alt="QR-kode" />`,
    showCloseButton: true,
    showConfirmButton: !!directLink,
    showCancelButton: true,
    focusConfirm: false,
    confirmButtonText: t("admin.pos.settings_wheel.copy_link"),
    cancelButtonText: t("common.close"),
    preConfirm: () => {
      navigator.clipboard.writeText(directLink);
      Swal.showValidationMessage(t("admin.pos.settings_wheel.link_copied"));
    },
  });
};

const onClickShowImpersonationQRCode = async (userId) => {
  // Get the session token
  const newToken = await SessionUser.superUser.intimidate.getImpersonationToken(userId);
  // Create the impersonation link
  const link = `${window.location.protocol}//${window.location.host}/login/qr?token=${newToken}`;
  // Generate a QR code for the impersonation link
  const response = await SessionUser.superUser.intimidate.showImpersonationQRCode(link);
  // Show the QR code in a modal
  onShowImpersonationQRCode(response.value, link);
};

const hasCustomActionsSlot = computed(() => Boolean(slots.actions));

const buildMenuAction = (key, config) => ({
  key,
  disabled: false,
  template: "default",
  type: "action",
  ...config,
});

const buildMenuToggleAction = (key, config) => ({
  key,
  disabled: false,
  type: "toggle",
  value: false,
  ...config,
});

const buildMenuSelectAction = (key, config) => ({
  key,
  disabled: false,
  options: [],
  type: "select",
  ...config,
});

const buildMenuLabel = (key, config) => ({
  key,
  type: "label",
  ...config,
});

const buildMenuSubsection = (key, config) => ({
  key,
  type: "subsection",
  ...config,
});

const buildMenuSection = (key, label, items) => {
  const visibleItems = items.filter(Boolean);
  if (visibleItems.length === 0) {
    return null;
  }

  return {
    key,
    label,
    items: visibleItems,
  };
};

const isToggleMenuItem = (item) => item?.type === "toggle";
const isSelectMenuItem = (item) => item?.type === "select";
const isLabelMenuItem = (item) => item?.type === "label";
const isSubsectionMenuItem = (item) => item?.type === "subsection";
const getSubsectionMenuItems = (section) => (section?.items || []).filter((item) => isSubsectionMenuItem(item));
const hasSubsectionMenuItems = (section) => getSubsectionMenuItems(section).length > 0;

const normalizeExternalMenuItem = (item, itemKey) => {
  if (!item || item.visible === false) {
    return null;
  }

  if (isToggleMenuItem(item)) {
    return buildMenuToggleAction(itemKey, item);
  }

  if (isSelectMenuItem(item)) {
    return buildMenuSelectAction(itemKey, item);
  }

  if (isLabelMenuItem(item)) {
    return buildMenuLabel(itemKey, item);
  }

  if (isSubsectionMenuItem(item)) {
    const children = Array.isArray(item.items) ? item.items : [];
    return buildMenuSubsection(itemKey, {
      ...item,
      items: children
        .map((child, childIndex) => normalizeExternalMenuItem(child, String(child?.key || `${itemKey}-item-${childIndex}`)))
        .filter(Boolean),
    });
  }

  return buildMenuAction(itemKey, item);
};

const externalMenuSections = computed(() =>
  props.menuSections
    .map((section, sectionIndex) => {
      const sectionKey = String(section?.key || `external-section-${sectionIndex}`);
      const items = Array.isArray(section?.items) ? section.items : [];

      return buildMenuSection(
        sectionKey,
        section?.label || sectionKey,
        items.map((item, itemIndex) => {
          const itemKey = String(item?.key || `${sectionKey}-item-${itemIndex}`);
          return normalizeExternalMenuItem(item, itemKey);
        })
      );
    })
    .filter(Boolean)
);

const downloadOrderAttachment = (attachment) =>
  downloadAttachment(attachment).catch(() => {
    Swal.fire({
      title: t("common.error"),
      text: t("admin.pos.settings_wheel.error_downloading_attachment"),
      icon: "error",
    });
  });

const openDepartmentWorkspaceTab = (tabId) =>
  SessionUser.functions.redirectTo.superUser(
    `/departments/${props.department_id}/gateways?tab=${encodeURIComponent(String(tabId))}`,
    true
  );

const openPrimaryGatewayPage = async () => {
  if (!props.department_id) {
    SessionUser.functions.redirectTo.superUser("/selfserve/edge-agents", true);
    return;
  }

  try {
    const response = await SessionUser.request(
      `/modules/edge-gateways/workspace/departments/${props.department_id}`,
      "GET"
    );
    const primaryGatewayId = response?.data?.data?.summary?.primary_gateway?.id ?? null;

    if (primaryGatewayId) {
      SessionUser.functions.redirectTo.superUser(
        `/selfserve/edge-agents/${encodeURIComponent(String(primaryGatewayId))}/overview`,
        true
      );
      return;
    }
  } catch (error) {
    console.warn("Unable to resolve primary gateway from department workspace", error);
  }

  SessionUser.functions.redirectTo.superUser("/selfserve/edge-agents", true);
};

const showCompleteOrderBookingConfirmation = async () => {
  const result = await Swal.fire({
    title: t("bookings.complete_booking"),
    text: t("pos.confirm_complete_order"),
    icon: "warning",
    showDenyButton: true,
    showCancelButton: true,
    confirmButtonText: t("admin.pos.settings_wheel.view_booking_new_tab"),
    denyButtonText: t("tables.bookings.complete_wash_without_certificate"),
    cancelButtonText: t("common.cancel"),
    reverseButtons: true,
  });

  if (result.isConfirmed) {
    SessionUser.functions.redirectTo.department(
      props.department_id,
      "modules/bookings/order/" + props.order_booking_id,
      true
    );
    return;
  }

  if (result.isDenied) {
    await SessionUser.objects.order_bookings.functions.complete(props.order_booking_id, null, () => {
      props.refreshFunction();
    });
  }
};

const showEmailNotificationActionResult = async (requestAction, successKey, errorKey) => {
  try {
    await requestAction();
    await Swal.fire({
      title: t(successKey),
      icon: "success",
      showConfirmButton: false,
      timer: 2000,
      heightAuto: false,
    });
  } catch (error) {
    console.error(error);
    await Swal.fire({
      title: t("common.error"),
      text: [t(errorKey), SessionUser.functions.parseErrorMessage?.(error)].filter(Boolean).join(": "),
      icon: "error",
      heightAuto: false,
    });
  }
};

const resendBookingConfirmation = () =>
  showEmailNotificationActionResult(
    () => SessionUser.objects.order_bookings.functions.resendBookingConfirmation(props.order_booking_id),
    "admin.pos.settings_wheel.resend_booking_confirmation_success",
    "admin.pos.settings_wheel.resend_booking_confirmation_error"
  );

const resendBookingCompletionConfirmation = () =>
  showEmailNotificationActionResult(
    () => SessionUser.objects.order_bookings.functions.resendBookingCompletionConfirmation(props.order_booking_id),
    "admin.pos.settings_wheel.resend_booking_completion_confirmation_success",
    "admin.pos.settings_wheel.resend_booking_completion_confirmation_error"
  );

const resendWashCertificate = () =>
  showEmailNotificationActionResult(
    () => SessionUser.objects.orders.functions.resendWashCertificate(props.order_id),
    "admin.pos.settings_wheel.resend_wash_certificate_success",
    "admin.pos.settings_wheel.resend_wash_certificate_error"
  );

const getAvailableInvoiceCollectionsForCustomer = async (customerNumber) => {
  const normalizedCustomerNumber = normalizePositiveInteger(customerNumber);
  if (!normalizedCustomerNumber) {
    return [];
  }

  const response = await SessionUser.request("/collected-invoices", "GET", {
    page: 1,
    limit: 100,
    order: "closed_at:asc",
    filters: `customer_number:${normalizedCustomerNumber},booked_invoice_id:is_null`,
  });

  return Array.isArray(response?.data?.data) ? response.data.data : [];
};

const ensureOpenInvoiceCollectionForCustomer = async (customerNumber) => {
  const collections = await getAvailableInvoiceCollectionsForCustomer(customerNumber);
  const openCollection = collections.find((collection) => collection?.closed_at === null);
  const openCollectionId = normalizePositiveInteger(openCollection?.id);
  if (openCollectionId) {
    return openCollectionId;
  }

  const response = await SessionUser.objects.collectedOrderInvoices.add(
    customerNumber,
    t("admin.pos.drafts_assignment.new_collection_name"),
    t("admin.pos.drafts_assignment.new_collection_description"),
    null
  );

  return normalizePositiveInteger(response?.data?.data?.id ?? response?.data?.id);
};

const acceptSelfServeWashDraft = async () => {
  const customerNumber = getSelfServeWashCustomerNumber.value;
  const orderId = normalizePositiveInteger(props.order_id);
  if (!customerNumber || !orderId) {
    return;
  }

  const result = await Swal.fire({
    title: t("admin.pos.settings_wheel.accept_self_serve_wash"),
    text: t("admin.pos.settings_wheel.accept_self_serve_wash_confirm", { customerNumber }),
    icon: "question",
    showCancelButton: true,
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
  });

  if (!result.isConfirmed) {
    return;
  }

  try {
    const invoiceCollectionId = await ensureOpenInvoiceCollectionForCustomer(customerNumber);
    if (!invoiceCollectionId) {
      throw new Error(t("admin.pos.drafts_assignment.invoice_collection_empty"));
    }

    await SessionUser.objects.orders.functions.assignDraftCustomer({
      order_id: orderId,
      customer_id: customerNumber,
      invoice_collection_id: invoiceCollectionId,
      department_id: normalizePositiveInteger(props.department_id),
      recalculate_prices: true,
    });

    await props.refreshFunction();
    await Swal.fire({
      icon: "success",
      title: t("admin.pos.settings_wheel.accept_self_serve_wash_success"),
      timer: 1800,
      showConfirmButton: false,
    });
  } catch (error) {
    await Swal.fire({
      icon: "error",
      title: t("admin.pos.drafts_assignment.error"),
      text: SessionUser.functions.parseErrorMessage(error) || t("admin.pos.drafts_assignment.error"),
    });
  }
};

const canDeleteOrderBooking = computed(() =>
  !props.order_id &&
  (props.allowBookingDeletion || SessionUser.canAccessAdmin() || SessionUser.canAccessSuperUser())
);

const flatBuiltInMenuSections = computed(() => {
  const sections = [...externalMenuSections.value];

  if (props.order_booking_id) {
    const bookingSection = buildMenuSection("booking", t("admin.pos.settings_wheel.booking"), [
      props.allowBookingCompletion
        ? buildMenuAction("booking-complete", {
            icon: "fas fa-check",
            label: t("admin.pos.settings_wheel.mark_as_completed"),
            template: "success",
            clickAction: showCompleteOrderBookingConfirmation,
          })
        : null,
      buildMenuAction("booking-view", {
        icon: "fas fa-external-link-alt",
        label: t("admin.pos.settings_wheel.view_booking_new_tab"),
        clickAction: () =>
          SessionUser.functions.redirectTo.department(
            props.department_id,
            "modules/bookings/order/" + props.order_booking_id,
            true
          ),
      }),
      SessionUser.canAccessAdmin() || SessionUser.canAccessSuperUser()
        ? buildMenuAction("booking-change-association", {
            icon: "fas fa-edit",
            label: !props.order_id
              ? t("admin.pos.settings_wheel.associate_order", {
                  order: SessionUser.objects.orders.meta.labels.single.toLowerCase(),
                })
              : t("admin.pos.settings_wheel.change_order", {
                  order: SessionUser.objects.orders.meta.labels.single.toLowerCase(),
                }),
            clickAction: () =>
              SessionUser.objects.order_bookings.showEditObjectFieldForm(
                props.order_booking_id,
                "order_id",
                props.order_id,
                () => {
                  props.refreshFunction();
                },
                {
                  filters: {
                    ...(props.customer_number ? { customer_id: props.customer_number } : {}),
                    ...(props.department_id ? { department_id: props.department_id } : {}),
                  },
                  pagination: {
                    page: 1,
                    limit: 100,
                  },
                }
              ),
          })
        : null,
      canDeleteOrderBooking.value
        ? buildMenuAction("booking-delete", {
            icon: "fas fa-trash-alt",
            label: t("admin.pos.settings_wheel.delete_booking"),
            template: "danger",
            clickAction: () =>
              SessionUser.objects.order_bookings.functions.showDeleteConfirmationModal(props.order_booking_id, () => {
                props.refreshFunction();
              }),
          })
        : null,
    ]);

    if (bookingSection) {
      sections.push(bookingSection);
    }
  }

  if (props.order_id) {
    const orderSection = buildMenuSection(
      "order",
      SessionUser.functions.ucFirst(SessionUser.objects.orders.meta.labels.single),
      [
        buildMenuAction("order-view", {
          icon: "fas fa-external-link-alt",
          label: t("admin.pos.settings_wheel.view_order_new_tab"),
          clickAction: () =>
            SessionUser.canAccessAdmin() || SessionUser.canAccessSuperUser()
              ? redirectDepartmentOrderPage(props.order_id, true)
              : SessionUser.functions.redirectTo.user("/orders/" + props.order_id, true),
        }),
        SessionUser.canAccessAdmin() || SessionUser.canAccessSuperUser()
          ? canAcceptSelfServeWashDraft.value
            ? buildMenuAction("order-accept-self-serve-wash", {
                icon: "fas fa-check-circle",
                label: t("admin.pos.settings_wheel.accept_self_serve_wash"),
                template: "success",
                clickAction: acceptSelfServeWashDraft,
              })
            : null
          : null,
        SessionUser.canAccessAdmin() || SessionUser.canAccessSuperUser()
          ? buildMenuAction("order-attach-wash-certificate", {
              icon: "fas fa-paperclip",
              label: t("admin.pos.settings_wheel.attach_wash_certificate"),
              clickAction: () =>
                SessionUser.objects.orders.functions.showAttachWashCertificateForm(props.order_id, () => {
                  props.refreshFunction();
                }),
            })
          : null,
        SessionUser.canAccessSuperUser()
          ? buildMenuAction("order-change-customer", {
              icon: "fas fa-user-edit",
              label: t("admin.pos.settings_wheel.change_customer"),
              clickAction: () => SessionUser.objects.orders.functions.showChangeCustomerForm(props.order_id),
            })
          : null,
        SessionUser.canAccessSuperUser()
          ? buildMenuAction("order-change-invoice-collection", {
              icon: "fas fa-file-invoice-dollar",
              label: t("admin.pos.settings_wheel.change_invoice_collection"),
              clickAction: () =>
                SessionUser.objects.orders.functions.showChangeInvoiceCollectionForm(
                  props.order_id,
                  props.refreshFunction
                ),
            })
          : null,
        SessionUser.canAccessAdmin() || SessionUser.canAccessSuperUser()
          ? buildMenuAction("order-delete", {
              icon: "fas fa-trash-alt",
              label: t("admin.pos.settings_wheel.delete_order"),
              template: "danger",
              clickAction: () =>
                SessionUser.objects.orders.functions.showDeleteConfirmationModal(props.order_id, () => {
                  emitDeleted();
                }),
            })
          : null,
      ]
    );

    if (orderSection) {
      sections.push(orderSection);
    }
  }

  if (props.order_booking_id || hasWashCertificateAttachment.value) {
    const emailNotificationsSection = buildMenuSection(
      "email-notifications",
      t("admin.pos.settings_wheel.email_notifications_section"),
      [
        props.order_booking_id
          ? buildMenuAction("email-notifications-resend-booking-confirmation", {
              icon: "fas fa-envelope",
              label: t("admin.pos.settings_wheel.resend_booking_confirmation"),
              clickAction: resendBookingConfirmation,
            })
          : null,
        props.order_booking_id && hasWashCertificateAttachment.value
          ? buildMenuAction("email-notifications-resend-booking-completion-confirmation", {
              icon: "fas fa-envelope-open-text",
              label: t("admin.pos.settings_wheel.resend_booking_completion_confirmation"),
              clickAction: resendBookingCompletionConfirmation,
            })
          : null,
        !props.order_booking_id && hasWashCertificateAttachment.value
          ? buildMenuAction("email-notifications-resend-wash-certificate", {
              icon: "fas fa-file-pdf",
              label: t("admin.pos.settings_wheel.resend_wash_certificate"),
              clickAction: resendWashCertificate,
            })
          : null,
      ]
    );

    if (emailNotificationsSection) {
      sections.push(emailNotificationsSection);
    }
  }

  if (props.invoice_collection_id && SessionUser.canAccessSuperUser()) {
    const invoiceCollectionLinkSection = buildMenuSection(
      "invoice-collection-link",
      SessionUser.objects.collectedOrderInvoices.meta.title,
      [
        buildMenuAction("invoice-collection-view", {
          icon: "fas fa-file-invoice-dollar",
          label: t("admin.pos.settings_wheel.view_invoice_collection_new_tab"),
          clickAction: () => redirectSuperUserInvoiceCollectionPage(props.invoice_collection_id),
        }),
      ]
    );

    if (invoiceCollectionLinkSection) {
      sections.push(invoiceCollectionLinkSection);
    }
  }

  if (props.department_lane_id) {
    const departmentLaneSection = buildMenuSection(
      "department-lane",
      SessionUser.objects.department_lanes.meta.labels.single,
      [
        (SessionUser.canAccessAdmin() || SessionUser.canAccessSuperUser()) && props.department_id
          ? buildMenuAction("department-lane-view-admin", {
              icon: "fas fa-external-link-alt",
              label: t("admin.pos.settings_wheel.view_lane_new_tab"),
              clickAction: () =>
                SessionUser.functions.redirectTo.department(
                  props.department_id,
                  "modules/wash-lanes/" + props.department_lane_id,
                  !SessionUser.functions.device.isMobile()
                ),
            })
          : null,
        SessionUser.canAccessSuperUser()
          ? buildMenuAction("department-lane-view-superuser", {
              icon: "fas fa-external-link-alt",
              label: t("admin.pos.settings_wheel.view_lane_setup_new_tab"),
              clickAction: () =>
                SessionUser.functions.redirectTo.superUser("/department/lanes/" + props.department_lane_id, true),
            })
          : null,
        SessionUser.canAccessSuperUser()
          ? buildMenuAction("department-lane-force-enable", {
              icon: "fas fa-play",
              label: t("superuser.department_lane.force_enable_machine"),
              template: "success",
              clickAction: () => SessionUser.objects.department_lanes.functions.forceEnableMachine(props.department_lane_id),
            })
          : null,
        SessionUser.canAccessSuperUser()
          ? buildMenuAction("department-lane-force-disable", {
              icon: "fas fa-stop",
              label: t("superuser.department_lane.force_disable_machine"),
              template: "danger",
              clickAction: () => SessionUser.objects.department_lanes.functions.forceDisableMachine(props.department_lane_id),
            })
          : null,
      ]
    );

    if (departmentLaneSection) {
      sections.push(departmentLaneSection);
    }
  }

  if (props.department_lane_id && props.department_id) {
    const selfServeStudioSection = buildMenuSection(
      "department-self-serve-studio",
      t("admin.pos.settings_wheel.self_serve_studio_section"),
      [
        (SessionUser.canAccessAdmin() || SessionUser.canAccessSuperUser()) && props.department_id
          ? buildMenuAction("department-self-serve-studio-open", {
              icon: "fas fa-external-link-alt",
              label: t("admin.pos.settings_wheel.open_studio"),
              clickAction: () =>
                SessionUser.functions.redirectTo.department(
                  props.department_id,
                  "modules/self-serve/studio",
                  !SessionUser.functions.device.isMobile()
                ),
            })
          : null,
        SessionUser.canAccessSuperUser()
          ? buildMenuAction("department-self-serve-studio-open-legacy", {
              icon: "fas fa-external-link-alt",
              label: t("admin.pos.settings_wheel.open_legacy_self_serve"),
              clickAction: () => SessionUser.functions.redirectTo.superUser("/selfserve", true),
            })
          : null,
        SessionUser.canAccessSuperUser()
          ? buildMenuAction("department-self-serve-studio-open-workspace", {
              icon: "fas fa-microchip",
              label: t("admin.pos.settings_wheel.open_hardware_workspace_lanes"),
              clickAction: () => openDepartmentWorkspaceTab("lanes"),
            })
          : null,
      ]
    );

    if (selfServeStudioSection) {
      sections.push(selfServeStudioSection);
    }

    const gatesSection = buildMenuSection("department-gates", t("admin.pos.settings_wheel.gates_section"), [
      SessionUser.canAccessSuperUser()
        ? buildMenuAction("department-gates-open-tab", {
            icon: "fas fa-door-open",
            label: t("admin.pos.settings_wheel.open_gates_tab"),
            clickAction: () => openDepartmentWorkspaceTab("gates"),
          })
        : null,
      SessionUser.canAccessSuperUser()
        ? buildMenuAction("department-gates-open-legacy", {
            icon: "fas fa-external-link-alt",
            label: t("admin.pos.settings_wheel.open_legacy_gates"),
            clickAction: () => SessionUser.functions.redirectTo.superUser("/department/gates", true),
          })
        : null,
      SessionUser.canAccessSuperUser()
        ? buildMenuAction("department-gates-create", {
            icon: "fas fa-plus",
            label: t("admin.pos.settings_wheel.add_gate"),
            clickAction: () =>
              SessionUser.objects.department_gates.showCreateObjectForm(() => {
                props.refreshFunction();
              }, { department: props.department_id }),
          })
        : null,
    ]);

    if (gatesSection) {
      sections.push(gatesSection);
    }

    const relaysSection = buildMenuSection("department-relays", t("admin.pos.settings_wheel.relays_section"), [
      SessionUser.canAccessSuperUser()
        ? buildMenuAction("department-relays-open-tab", {
            icon: "fas fa-bolt",
            label: t("admin.pos.settings_wheel.open_relays_tab"),
            clickAction: () => openDepartmentWorkspaceTab("relays"),
          })
        : null,
      SessionUser.canAccessSuperUser()
        ? buildMenuAction("department-relays-open-legacy", {
            icon: "fas fa-external-link-alt",
            label: t("admin.pos.settings_wheel.open_legacy_relays"),
            clickAction: () => SessionUser.functions.redirectTo.superUser("/department/relays", true),
          })
        : null,
      SessionUser.canAccessSuperUser()
        ? buildMenuAction("department-relays-create", {
            icon: "fas fa-plus",
            label: t("admin.pos.settings_wheel.add_relay"),
            clickAction: () =>
              SessionUser.objects.department_relays.showCreateObjectForm(() => {
                props.refreshFunction();
              }, { department: props.department_id }),
          })
        : null,
    ]);

    if (relaysSection) {
      sections.push(relaysSection);
    }

    const gatewaysSection = buildMenuSection(
      "department-gateways",
      t("admin.pos.settings_wheel.gateways_section"),
      [
        SessionUser.canAccessSuperUser()
          ? buildMenuAction("department-gateways-open-tab", {
              icon: "fas fa-network-wired",
              label: t("admin.pos.settings_wheel.open_gateways_tab"),
              clickAction: () => openDepartmentWorkspaceTab("gateways"),
            })
          : null,
        SessionUser.canAccessSuperUser()
          ? buildMenuAction("department-gateways-open-fleet", {
              icon: "fas fa-sitemap",
              label: t("admin.pos.settings_wheel.open_fleet_landing"),
              clickAction: () => SessionUser.functions.redirectTo.superUser("/selfserve/edge-agents", true),
            })
          : null,
        SessionUser.canAccessSuperUser()
          ? buildMenuAction("department-gateways-open-primary", {
              icon: "fas fa-star",
              label: t("admin.pos.settings_wheel.open_primary_gateway"),
              clickAction: () => openPrimaryGatewayPage(),
            })
          : null,
      ]
    );

    if (gatewaysSection) {
      sections.push(gatewaysSection);
    }
  }

  if (hasUser.value && SessionUser.canAccessSuperUser()) {
    const customerSectionItems = userIdFromCustomerNumber.value
      ? [
          buildMenuAction("customer-view", {
            icon: "fas fa-user-edit",
            label: t("admin.pos.settings_wheel.view_customer_new_tab"),
            clickAction: () =>
              SessionUser.functions.redirectTo.superUser("/users/" + userIdFromCustomerNumber.value, true),
          }),
          buildMenuAction("customer-login", {
            icon: "fas fa-user-shield",
            label: t("admin.pos.settings_wheel.login_as_user"),
            clickAction: () => SessionUser.superUser.intimidate.intimidateUser(userIdFromCustomerNumber.value),
          }),
          buildMenuAction("customer-login-qr", {
            icon: "fas fa-user-shield",
            label: t("admin.pos.settings_wheel.login_as_user_qr"),
            clickAction: () => onClickShowImpersonationQRCode(userIdFromCustomerNumber.value),
          }),
          buildMenuAction("customer-change-password", {
            icon: "fas fa-key",
            label: t("admin.pos.settings_wheel.change_password"),
            clickAction: () => showSetCustomerPassword(userIdFromCustomerNumber.value),
          }),
          buildMenuAction("customer-show", {
            icon: "fas fa-user",
            label: t("admin.pos.settings_wheel.show_customer"),
            clickAction: () => {
              customerModalVisible.value = true;
            },
          }),
        ]
      : isResolvingUserId.value
        ? [
            buildMenuAction("customer-loading", {
              disabled: true,
              icon: "fas fa-spinner",
              label: t("global.loading"),
            }),
          ]
        : [];
    const customerSection = buildMenuSection(
      "customer",
      t("admin.pos.settings_wheel.customer_section"),
      customerSectionItems
    );

    if (customerSection) {
      sections.push(customerSection);
    }

    if (canViewCustomerRules.value) {
      const ruleSection = buildMenuSection(
        "rules",
        t("admin.pos.settings_wheel.rules_section"),
        customerRuleAttributesLoading.value && !customerRuleAttributesLoaded.value
          ? [
              buildMenuAction("customer-rules-loading", {
                disabled: true,
                icon: "fas fa-spinner",
                label: t("global.loading"),
              }),
            ]
          : customerRuleItems.value.map((rule) =>
              buildMenuToggleAction(rule.key, {
                customerRuleActive: rule.customerRuleActive,
                customerRuleAttribute: rule.customerRuleAttribute,
                customerRuleCustomerNumber: rule.customerRuleCustomerNumber,
                customerRuleDepartmentId: rule.customerRuleDepartmentId,
                description: rule.description,
                disabled: rule.disabled,
                label: rule.label,
                testId: rule.testId,
                value: rule.value,
                clickAction: () => toggleCustomerRuleAttribute(rule.attribute, !rule.value),
              })
            )
      );

      if (ruleSection) {
        sections.push(ruleSection);
      }
    }

    const shortcutsSection = buildMenuSection(
      "shortcuts",
      t("admin.pos.settings_wheel.shortcuts_section"),
      userIdFromCustomerNumber.value
        ? customerShortcutItems.value
        : isResolvingUserId.value
          ? [
              buildMenuAction("customer-shortcuts-loading", {
                disabled: true,
                icon: "fas fa-spinner",
                label: t("global.loading"),
              }),
            ]
          : []
    );

    if (shortcutsSection) {
      sections.push(shortcutsSection);
    }
  }

  if (props.reg_1 || props.reg_2 || props.reg_3) {
    const vehicleSection = buildMenuSection(
      "vehicle",
      [props.reg_1, props.reg_2, props.reg_3].filter(Boolean).length > 1
        ? SessionUser.objects.vehicles.meta.labels.multiple
        : SessionUser.objects.vehicles.meta.labels.single,
      [
        props.reg_1 && SessionUser.canAccessSuperUser()
          ? buildMenuAction("vehicle-reg-1", {
              icon: "fas fa-car",
              label: t("admin.pos.settings_wheel.view_vehicle_new_tab", { reg: props.reg_1 }),
              clickAction: () => SessionUser.functions.redirectTo.superUser("/vehicles/" + props.reg_1, true),
            })
          : null,
        props.reg_2 && SessionUser.canAccessSuperUser()
          ? buildMenuAction("vehicle-reg-2", {
              icon: "fas fa-car",
              label: t("admin.pos.settings_wheel.view_vehicle_new_tab", { reg: props.reg_2 }),
              clickAction: () => SessionUser.functions.redirectTo.superUser("/vehicles/" + props.reg_2, true),
            })
          : null,
        props.reg_3 && SessionUser.canAccessSuperUser()
          ? buildMenuAction("vehicle-reg-3", {
              icon: "fas fa-car",
              label: t("admin.pos.settings_wheel.view_vehicle_new_tab", { reg: props.reg_3 }),
              clickAction: () => SessionUser.functions.redirectTo.superUser("/vehicles/" + props.reg_3, true),
            })
          : null,
      ]
    );

    if (vehicleSection) {
      sections.push(vehicleSection);
    }
  }

  if (attachmentsFromOrder.value.length > 0) {
    const attachmentsSection = buildMenuSection("attachments", t("admin.pos.settings_wheel.attached_files"), [
      ...attachmentsFromOrder.value.map((attachment) =>
        buildMenuAction(`attachment-${attachment.id}`, {
          icon: "fas fa-paperclip",
          label: getAttachmentLabel(attachment),
          clickAction: () => downloadOrderAttachment(attachment),
        })
      ),
    ]);

    if (attachmentsSection) {
      sections.push({
        ...attachmentsSection,
        attachments: [...attachmentsFromOrder.value],
      });
    }
  }

  if (props.invoice_collection_id) {
    const invoiceCollectionDownloadSection = buildMenuSection(
      "invoice-collection-download",
      SessionUser.objects.collectedOrderInvoices.meta.title,
      [
        buildMenuAction("invoice-collection-download-invoice", {
          icon: "fas fa-download",
          label: t("admin.pos.settings_wheel.download_invoice"),
          clickAction: () => SessionUser.objects.collectedOrderInvoices.functions.download(props.invoice_collection_id),
        }),
      ]
    );

    if (invoiceCollectionDownloadSection) {
      sections.push(invoiceCollectionDownloadSection);
    }
  }

  if (canAddInvoicePeriodFlag.value) {
    const flagSection = buildMenuSection(
      "invoice-period-flags",
      t("admin.pos.settings_wheel.flags_section"),
      defaultInvoicePeriodFlagTargets.value.map((item) =>
        buildMenuAction(`add-invoice-period-flag-${item.key}`, {
          icon: "fas fa-flag",
          label: item.label,
          template: "danger",
          clickAction: () => showCreateInvoicePeriodFlagForm(item.target),
        })
      )
    );

    if (flagSection) {
      sections.push(flagSection);
    }
  }

  return sections;
});

const standaloneMenuActions = computed(() => {
  const actions = [];

  if (props.subuserGrant && SessionUser.canAccessUser()) {
    actions.push(
      buildMenuAction("subuser-grant-edit-permissions", {
        icon: "fas fa-edit",
        label: t("admin.pos.settings_wheel.edit_permissions"),
        clickAction: () =>
          SessionUser.objects.subuser_grants.functions.showPermissionEditForm(props.subuserGrant, () => {
            props.refreshFunction();
          }),
      })
    );
    actions.push(
      buildMenuAction("subuser-grant-delete-user", {
        icon: "fas fa-trash",
        label: t("admin.pos.settings_wheel.delete_user"),
        clickAction: () =>
          SessionUser.objects.subuser_grants.delete(props.subuserGrant.id, () => {
            props.refreshFunction();
          }),
      })
    );
  }

  return actions;
});

const directBuiltInMenuSections = computed(() => {
  if (!props.displayActionsDirectly || !Array.isArray(props.directSectionKeys) || props.directSectionKeys.length === 0) {
    return flatBuiltInMenuSections.value;
  }

  const allowedKeys = new Set(props.directSectionKeys.map((key) => String(key)));
  return flatBuiltInMenuSections.value.filter((section) => allowedKeys.has(String(section.key)));
});

const desktopFlyoutMenuSections = computed(() => {
  const mergedSections = [];
  const mergedSectionsByLabel = new Map();

  flatBuiltInMenuSections.value.forEach((section) => {
    const labelKey = String(section.label);
    const existingSection = mergedSectionsByLabel.get(labelKey);

    if (existingSection) {
      existingSection.items.push(...section.items);
      return;
    }

    const mergedSection = {
      ...section,
      items: [...section.items],
    };

    mergedSectionsByLabel.set(labelKey, mergedSection);
    mergedSections.push(mergedSection);
  });

  return mergedSections;
});

watch(
  [
    activeDesktopFlyoutSectionKey,
    activeDesktopFlyoutSubsectionKey,
    activeAttachmentId,
    isDesktopFlyoutLayout,
    desktopFlyoutMenuSections,
    activeAttachmentPreviewSource,
    attachmentsFromOrder,
  ],
  () => {
    if (isDropdownOpen.value) {
      void nextTick(() => {
        void updateDropdownLayout();
      });
    }
  }
);

const activeDesktopFlyoutSection = computed(() => {
  return (
    desktopFlyoutMenuSections.value.find((section) => section.key === activeDesktopFlyoutSectionKey.value) ??
    desktopFlyoutMenuSections.value[0] ??
    null
  );
});

const activeDesktopFlyoutSubsection = computed(() => {
  const subsectionItems = getSubsectionMenuItems(activeDesktopFlyoutSection.value);

  if (subsectionItems.length === 0) {
    return null;
  }

  return (
    subsectionItems.find((item) => item.key === activeDesktopFlyoutSubsectionKey.value) ??
    subsectionItems[0] ??
    null
  );
});
const hasDesktopFlyoutSubsections = computed(() =>
  desktopFlyoutMenuSections.value.some((section) => hasSubsectionMenuItems(section))
);

const hasDropdownContent = computed(
  () => hasCustomActionsSlot.value || flatBuiltInMenuSections.value.length > 0 || standaloneMenuActions.value.length > 0
);

const getDesktopFlyoutEstimatedWidth = () => {
  const rootFontSize = Number.parseFloat(window.getComputedStyle(document.documentElement).fontSize || "16") || 16;
  const panelWidthRem =
    desktopFlyoutRootPanelWidthRem +
    desktopFlyoutSubmenuWidthRem +
    (hasDesktopFlyoutSubsections.value ? desktopFlyoutNestedPanelWidthRem : 0);
  const panelGapCount = hasDesktopFlyoutSubsections.value ? 2 : 1;

  return panelWidthRem * rootFontSize + desktopFlyoutPanelGapPx * panelGapCount;
};

const setActiveDesktopFlyoutSubsectionForSection = (section) => {
  activeDesktopFlyoutSubsectionKey.value = getSubsectionMenuItems(section)[0]?.key ?? null;
};

const syncDesktopFlyoutState = (triggerRect) => {
  if (typeof window === "undefined") {
    isDesktopFlyoutLayout.value = false;
    return;
  }

  const canUseHover =
    typeof window.matchMedia === "function"
      ? window.matchMedia("(hover: hover) and (pointer: fine)").matches
      : false;
  const hasSections = desktopFlyoutMenuSections.value.length > 0;
  const hasSpaceForFlyout =
    !!triggerRect && triggerRect.right - getDesktopFlyoutEstimatedWidth() >= desktopFlyoutPanelGapPx;
  const nextDesktopFlyoutState =
    canUseHover && hasSections && window.innerWidth >= desktopFlyoutMinViewportWidth && hasSpaceForFlyout;

  isDesktopFlyoutLayout.value = nextDesktopFlyoutState;

  if (!nextDesktopFlyoutState) {
    activeDesktopFlyoutSectionKey.value = null;
    activeDesktopFlyoutSubsectionKey.value = null;
    return;
  }

  const currentSectionStillExists = desktopFlyoutMenuSections.value.some(
    (section) => section.key === activeDesktopFlyoutSectionKey.value
  );

  if (!currentSectionStillExists) {
    activeDesktopFlyoutSectionKey.value = desktopFlyoutMenuSections.value[0]?.key ?? null;
    setActiveDesktopFlyoutSubsectionForSection(desktopFlyoutMenuSections.value[0] ?? null);
  }
};

const setActiveDesktopFlyoutSection = (sectionKey) => {
  activeDesktopFlyoutSectionKey.value = sectionKey;
  setActiveDesktopFlyoutSubsectionForSection(
    desktopFlyoutMenuSections.value.find((section) => section.key === sectionKey) ?? null
  );

  if (sectionKey !== "attachments") {
    activeAttachmentId.value = null;
  }
};

const setActiveDesktopFlyoutSubsection = (subsectionKey) => {
  activeDesktopFlyoutSubsectionKey.value = subsectionKey;
};

const isOverflowClippingStyle = (style) =>
  ["overflow", "overflowX", "overflowY"].some((property) => {
    const value = style[property];
    return value && value !== "visible";
  });

const isDropdownClippedByAncestor = (dropdownRect, triggerRect) => {
  let el = dropdownRoot.value?.parentElement;

  while (el && el !== document.body) {
    const style = window.getComputedStyle(el);
    if (isOverflowClippingStyle(style)) {
      const ancestorRect = el.getBoundingClientRect();
      const wouldClipCurrentDropdown =
        dropdownRect.top < ancestorRect.top ||
        dropdownRect.right > ancestorRect.right ||
        dropdownRect.bottom > ancestorRect.bottom ||
        dropdownRect.left < ancestorRect.left;
      const wouldClipBelow = triggerRect.bottom + dropdownRect.height > ancestorRect.bottom;
      const wouldClipAbove = triggerRect.top - dropdownRect.height < ancestorRect.top;

      if (wouldClipCurrentDropdown || (wouldClipBelow && wouldClipAbove)) {
        return true;
      }
    }

    el = el.parentElement;
  }

  return false;
};

// Smart re-positioning of the flyout menu when either it's partially or fully hidden
const syncDesktopFlyoutPosition = () => {
  if (typeof window === "undefined") {
    return;
  }
  const dropdownContentEl = dropdownContent.value;
  const triggerEl = dropdownRoot.value?.querySelector(".dropdown-trigger") ?? dropdownRoot.value;
  if (!dropdownContentEl || !triggerEl) {
    return;
  }

  const triggerRect = triggerEl.getBoundingClientRect();
  const contentHeight = dropdownContentEl.scrollHeight;
  const viewportWidth = window.innerWidth;
  const contentRect = dropdownContentEl.getBoundingClientRect();

  let needsFixed = isDropdownClippedByAncestor(contentRect, triggerRect);
  if (isDesktopFlyoutLayout.value) {
    let el = dropdownRoot.value.parentElement;
    while (el && el !== document.body && el !== null) {
      const style = window.getComputedStyle(el);
      if (style.overflowY !== "visible") {
        if (el.clientHeight < contentHeight + 10) {
          needsFixed = true;
          break;
        }
      }
      el = el.parentElement;
    }
  }

  if (isFixedPosition.value !== needsFixed) {
    isFixedPosition.value = needsFixed;
  }

  if (needsFixed) {
    if (dropdownContentEl.style.top !== "") {
      dropdownContentEl.style.top = "";
    }

    const viewportInsets = getViewportInsets();
    const viewportTop = viewportInsets.top;
    const effectiveContentHeight = dropdownMaxHeight.value
      ? Math.min(contentHeight, dropdownMaxHeight.value)
      : contentHeight;
    const top =
      dropdownPlacement.value === "top"
        ? Math.max(viewportTop, triggerRect.top - effectiveContentHeight)
        : triggerRect.bottom;

    const nextFixedStyles = {
      top: `${top}px`,
      right: `${viewportWidth - triggerRect.right}px`,
      width: "max-content",
    };

    if (
      fixedPositionStyles.value.top !== nextFixedStyles.top ||
      fixedPositionStyles.value.right !== nextFixedStyles.right ||
      fixedPositionStyles.value.width !== nextFixedStyles.width
    ) {
      fixedPositionStyles.value = nextFixedStyles;
    }
  } else {
    if (dropdownContentEl.style.top !== "") {
      dropdownContentEl.style.top = "";
    }
  }
};



const __returned__ = { t, slots, imageExtensions, officeExtensions, emit, emitDeleted, emitFlagCreated, props, customerModalVisible, userIdFromCustomerNumber, userLookupRequestId, isResolvingUserId, customerRuleAttributes, customerRuleAttributesLoaded, customerRuleAttributesLoading, dropdownRoot, dropdownContent, isDropdownOpen, dropdownInstanceId, dropdownPlacement, isDropdownPlacementLocked, shouldOpenDropdownUp, dropdownMaxHeight, isDesktopFlyoutLayout, isFixedPosition, fixedPositionStyles, activeDesktopFlyoutSectionKey, activeDesktopFlyoutSubsectionKey, activeAttachmentId, previewLoadingAttachmentId, deletingAttachmentId, previewSourcesById, previewRequestsInFlight, generatedObjectUrls, get previewStateGeneration() { return previewStateGeneration }, set previewStateGeneration(v) { previewStateGeneration = v; }, get contentResizeObserver() { return contentResizeObserver }, set contentResizeObserver(v) { contentResizeObserver = v; }, get dropdownLayoutUpdateId() { return dropdownLayoutUpdateId }, set dropdownLayoutUpdateId(v) { dropdownLayoutUpdateId = v; }, desktopFlyoutMinViewportWidth, desktopFlyoutRootPanelWidthRem, desktopFlyoutSubmenuWidthRem, desktopFlyoutNestedPanelWidthRem, desktopFlyoutPanelGapPx, closeDropdown, openDropdown, toggleDropdown, onActionSelected, isTextTriggerButton, isIconOnlyTriggerButton, getTriggerButtonClass, dropdownClass, dropdownContentClass, dropdownMenuStyle, dropdownContentStyle, resetDropdownLayout, isVisibleFixedInsetElement, getInsetElements, getViewportInsets, getDropdownPlacementSpaces, resolveDropdownPlacement, getDropdownAvailableHeight, lockDropdownPlacement, updateDropdownLayout, onDocumentClick, onDocumentKeydown, onActionSettingsWheelOpened, onViewportChange, resolveUserId, resetCustomerRuleState, loadCustomerRuleAttributes, toggleCustomerRuleAttribute, showSetCustomerPassword, redirectSuperUserInvoiceCollectionPage, redirectDepartmentOrderPage, normalizeInvoicePeriodFlagTarget, getInvoicePeriodFlagTargetLabel, defaultInvoicePeriodFlagTargets, canAddInvoicePeriodFlag, showCreateInvoicePeriodFlagForm, hasUser, customerAttributeTarget, canViewCustomerRules, customerRuleDepartmentId, customerRuleDefinitions, activeCustomerRuleAttributes, customerRuleItems, customerShortcutItems, attachmentsFromOrder, attachmentsFromOrderError, SELF_SERVE_WASH_ATTACHMENT_TYPE: SELF_SERVE_WASH_ATTACHMENT_TYPE$1, normalizePositiveInteger, getAttachmentOtherPayload, isSelfServeWashAttachment, getSelfServeWashAttachment, getSelfServeWashPayload, getSelfServeWashCustomerNumber, canAcceptSelfServeWashDraft, isObjectUrl, releaseObjectUrl, clearAttachmentPreviewState, getAttachmentLabel, isWashCertificateAttachment, getAttachmentExtension, getAttachmentPreviewKind, formatAttachmentText, getAttachmentPreviewPlaceholderIcon, getAttachmentPreviewPlaceholderLabel, activeAttachment, activeAttachmentPreviewKind, activeAttachmentPreviewSource, hasWashCertificateAttachment, hasCachedPreviewSource, buildAttachmentPreviewHeaders, shouldRetryPreviewRequestWithAuth, fetchAttachmentPreviewBlob, createEmbeddablePreviewUrl, loadOrderAttachments, resolveAttachmentDownloadLink, ensurePreviewSource, setActiveAttachment, openAttachmentInNewTab, downloadAttachmentFile, previewAttachment, downloadAttachment, printAttachment, removeAttachment, onShowImpersonationQRCode, onClickShowImpersonationQRCode, hasCustomActionsSlot, buildMenuAction, buildMenuToggleAction, buildMenuSelectAction, buildMenuLabel, buildMenuSubsection, buildMenuSection, isToggleMenuItem, isSelectMenuItem, isLabelMenuItem, isSubsectionMenuItem, getSubsectionMenuItems, hasSubsectionMenuItems, normalizeExternalMenuItem, externalMenuSections, downloadOrderAttachment, openDepartmentWorkspaceTab, openPrimaryGatewayPage, showCompleteOrderBookingConfirmation, showEmailNotificationActionResult, resendBookingConfirmation, resendBookingCompletionConfirmation, resendWashCertificate, getAvailableInvoiceCollectionsForCustomer, ensureOpenInvoiceCollectionForCustomer, acceptSelfServeWashDraft, canDeleteOrderBooking, flatBuiltInMenuSections, standaloneMenuActions, directBuiltInMenuSections, desktopFlyoutMenuSections, activeDesktopFlyoutSection, activeDesktopFlyoutSubsection, hasDesktopFlyoutSubsections, hasDropdownContent, getDesktopFlyoutEstimatedWidth, setActiveDesktopFlyoutSubsectionForSection, syncDesktopFlyoutState, setActiveDesktopFlyoutSection, setActiveDesktopFlyoutSubsection, isOverflowClippingStyle, isDropdownClippedByAncestor, syncDesktopFlyoutPosition, onMounted, onBeforeUnmount, computed, nextTick, watch, useSlots, SessionUser, ActionSettingsWheelItem, ActionSettingsWheelToggleItem, ActionSettingsWheelSelectItem, get Swal() { return Swal }, ref, CustomerModal, ActionSettingsWheelItemLabel, get useI18n() { return useI18n }, get getReleaseRuntimeApiBaseUrl() { return getReleaseRuntimeApiBaseUrl }, get getCustomerRuleDefinitions() { return getCustomerRuleDefinitions }, CustomerRuleTooltip, get buildCustomerAttributeTargetPayload() { return buildCustomerAttributeTargetPayload }, get createCustomerAttribute() { return createCustomerAttribute }, get deleteCustomerAttribute() { return deleteCustomerAttribute }, get extractCustomerAttributesData() { return extractCustomerAttributesData }, get listCustomerAttributes() { return listCustomerAttributes } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$h = {
  key: 0,
  class: "message is-danger"
};
const _hoisted_2$e = { class: "message-body" };
const _hoisted_3$e = ["data-testid"];
const _hoisted_4$e = { class: "action-settings-wheel-subsection__title" };
const _hoisted_5$d = {
  key: 0,
  class: "action-settings-wheel-subsection__description"
};
const _hoisted_6$d = { class: "dropdown-trigger" };
const _hoisted_7$d = ["aria-expanded"];
const _hoisted_8$d = { class: "icon" };
const _hoisted_9$c = {
  key: 0,
  class: "ml-2"
};
const _hoisted_10$b = {
  key: 0,
  class: "action-settings-wheel-flyout",
  "data-testid": "action-settings-wheel-flyout"
};
const _hoisted_11$b = ["data-testid"];
const _hoisted_12$a = { class: "action-settings-wheel-nested-panel__title" };
const _hoisted_13$9 = {
  key: 0,
  class: "action-settings-wheel-nested-panel__description"
};
const _hoisted_14$9 = { class: "action-settings-wheel-nested-panel__items" };
const _hoisted_15$9 = { class: "action-settings-wheel-flyout__submenu-stack" };
const _hoisted_16$9 = ["data-testid"];
const _hoisted_17$7 = { class: "action-settings-wheel-flyout__submenu-title" };
const _hoisted_18$7 = { class: "action-settings-wheel-flyout__submenu-items" };
const _hoisted_19$6 = ["data-testid", "title", "onMouseenter", "onFocus", "onClick"];
const _hoisted_20$5 = { class: "action-settings-wheel-section-trigger__label" };
const _hoisted_21$5 = ["data-testid", "onMouseenter", "onFocus", "onClick"];
const _hoisted_22$5 = { class: "action-settings-wheel-section-trigger__text" };
const _hoisted_23$5 = { class: "action-settings-wheel-section-trigger__label" };
const _hoisted_24$5 = {
  key: 0,
  class: "action-settings-wheel-section-trigger__description"
};
const _hoisted_25$5 = {
  key: 0,
  class: "action-settings-wheel-attachment-panel",
  "data-testid": "action-settings-wheel-attachment-panel"
};
const _hoisted_26$5 = ["title"];
const _hoisted_27$5 = {
  class: "action-settings-wheel-attachment-panel__preview",
  "data-testid": "action-settings-wheel-attachment-preview"
};
const _hoisted_28$5 = {
  key: 0,
  class: "action-settings-wheel-attachment-panel__text"
};
const _hoisted_29$4 = ["src"];
const _hoisted_30$4 = ["src"];
const _hoisted_31$4 = ["href"];
const _hoisted_32$4 = {
  key: 4,
  class: "action-settings-wheel-attachment-panel__placeholder"
};
const _hoisted_33$4 = { class: "action-settings-wheel-attachment-panel__placeholder-icon" };
const _hoisted_34$4 = { class: "action-settings-wheel-attachment-panel__placeholder-label" };
const _hoisted_35$4 = {
  key: 5,
  class: "action-settings-wheel-attachment-panel__text"
};
const _hoisted_36$3 = {
  key: 6,
  class: "action-settings-wheel-attachment-panel__text"
};
const _hoisted_37$3 = {
  key: 7,
  class: "action-settings-wheel-attachment-panel__text"
};
const _hoisted_38$3 = { class: "action-settings-wheel-attachment-panel__actions" };
const _hoisted_39$3 = ["data-testid"];
const _hoisted_40$3 = ["data-testid"];
const _hoisted_41$3 = ["data-testid"];
const _hoisted_42$3 = ["disabled", "data-testid"];
const _hoisted_43$3 = {
  class: "action-settings-wheel-flyout__sections",
  "data-testid": "action-settings-wheel-sections"
};
const _hoisted_44$3 = ["data-testid", "onMouseenter", "onFocus", "onClick"];
const _hoisted_45$3 = { class: "action-settings-wheel-section-trigger__label" };
const _hoisted_46$3 = {
  key: 1,
  class: "action-settings-wheel-flyout__standalone-actions"
};
const _hoisted_47$3 = {
  key: 1,
  "data-testid": "action-settings-wheel-sections"
};
const _hoisted_48$3 = ["data-testid"];
const _hoisted_49$2 = { class: "action-settings-wheel-subsection__title" };
const _hoisted_50$2 = {
  key: 0,
  class: "action-settings-wheel-subsection__description"
};
const _hoisted_51$2 = {
  key: 1,
  class: "dropdown-item"
};
const _hoisted_52$2 = { class: "has-text-centered" };

function _sfc_render$h(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", null, [
    ($props.displayActionsDirectly)
      ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
          createCommentVNode(" Error "),
          ($setup.attachmentsFromOrderError)
            ? (openBlock(), createElementBlock("div", _hoisted_1$h, [
                createBaseVNode("div", _hoisted_2$e, toDisplayString($setup.attachmentsFromOrderError), 1 /* TEXT */)
              ]))
            : createCommentVNode("v-if", true),
          ($setup.hasCustomActionsSlot)
            ? renderSlot(_ctx.$slots, "actions", { key: 1 }, undefined, true)
            : createCommentVNode("v-if", true),
          (openBlock(true), createElementBlock(Fragment, null, renderList($setup.directBuiltInMenuSections, (section) => {
            return (openBlock(), createElementBlock(Fragment, {
              key: section.key
            }, [
              createVNode($setup["ActionSettingsWheelItemLabel"], {
                label: section.label
              }, null, 8 /* PROPS */, ["label"]),
              (openBlock(true), createElementBlock(Fragment, null, renderList(section.items, (item) => {
                return (openBlock(), createElementBlock(Fragment, {
                  key: item.key
                }, [
                  ($setup.isSubsectionMenuItem(item))
                    ? (openBlock(), createElementBlock("div", {
                        key: 0,
                        class: "action-settings-wheel-subsection",
                        "data-testid": item.testId || `action-settings-wheel-subsection-${item.key}`
                      }, [
                        createBaseVNode("p", _hoisted_4$e, toDisplayString(item.label), 1 /* TEXT */),
                        (item.description)
                          ? (openBlock(), createElementBlock("p", _hoisted_5$d, toDisplayString(item.description), 1 /* TEXT */))
                          : createCommentVNode("v-if", true),
                        (openBlock(true), createElementBlock(Fragment, null, renderList(item.items || [], (subItem) => {
                          return (openBlock(), createElementBlock(Fragment, {
                            key: subItem.key
                          }, [
                            ($setup.isLabelMenuItem(subItem))
                              ? (openBlock(), createBlock($setup["ActionSettingsWheelItemLabel"], {
                                  key: 0,
                                  icon: subItem.icon,
                                  label: subItem.label,
                                  "detail-value": subItem.detailValue,
                                  appearance: subItem.appearance,
                                  template: subItem.template,
                                  "data-testid": subItem.testId || undefined
                                }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "appearance", "template", "data-testid"]))
                              : ($setup.isToggleMenuItem(subItem))
                                ? (openBlock(), createBlock($setup["ActionSettingsWheelToggleItem"], {
                                    key: 1,
                                    checked: subItem.value,
                                    "click-action": subItem.clickAction,
                                    description: subItem.description,
                                    disabled: subItem.disabled,
                                    label: subItem.label,
                                    "test-id": subItem.testId
                                  }, null, 8 /* PROPS */, ["checked", "click-action", "description", "disabled", "label", "test-id"]))
                                : ($setup.isSelectMenuItem(subItem))
                                  ? (openBlock(), createBlock($setup["ActionSettingsWheelSelectItem"], {
                                      key: 2,
                                      icon: subItem.icon,
                                      label: subItem.label,
                                      value: subItem.value,
                                      options: subItem.options,
                                      "change-action": subItem.changeAction,
                                      disabled: subItem.disabled,
                                      "test-id": subItem.testId
                                    }, null, 8 /* PROPS */, ["icon", "label", "value", "options", "change-action", "disabled", "test-id"]))
                                  : (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                                      key: 3,
                                      icon: subItem.icon,
                                      label: subItem.label,
                                      "detail-value": subItem.detailValue,
                                      template: subItem.template,
                                      "click-action": subItem.clickAction,
                                      disabled: subItem.disabled,
                                      "test-id": subItem.testId
                                    }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "template", "click-action", "disabled", "test-id"]))
                          ], 64 /* STABLE_FRAGMENT */))
                        }), 128 /* KEYED_FRAGMENT */))
                      ], 8 /* PROPS */, _hoisted_3$e))
                    : ($setup.isLabelMenuItem(item))
                      ? (openBlock(), createBlock($setup["ActionSettingsWheelItemLabel"], {
                          key: 1,
                          icon: item.icon,
                          label: item.label,
                          "detail-value": item.detailValue,
                          appearance: item.appearance,
                          template: item.template,
                          "data-testid": item.testId || undefined
                        }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "appearance", "template", "data-testid"]))
                      : ($setup.isToggleMenuItem(item))
                        ? (openBlock(), createBlock($setup["ActionSettingsWheelToggleItem"], {
                            key: 2,
                            checked: item.value,
                            "click-action": item.clickAction,
                            description: item.description,
                            disabled: item.disabled,
                            label: item.label,
                            "test-id": item.testId
                          }, createSlots({ _: 2 /* DYNAMIC */ }, [
                            (item.customerRuleAttribute)
                              ? {
                                  name: "label",
                                  fn: withCtx(({ label }) => [
                                    createVNode($setup["CustomerRuleTooltip"], {
                                      attribute: item.customerRuleAttribute,
                                      active: item.customerRuleActive,
                                      "customer-number": item.customerRuleCustomerNumber,
                                      "department-id": item.customerRuleDepartmentId,
                                      "test-id": `${item.testId}-tooltip`
                                    }, {
                                      default: withCtx(() => [
                                        createBaseVNode("span", null, toDisplayString(label), 1 /* TEXT */)
                                      ]),
                                      _: 2 /* DYNAMIC */
                                    }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["attribute", "active", "customer-number", "department-id", "test-id"])
                                  ]),
                                  key: "0"
                                }
                              : undefined
                          ]), 1032 /* PROPS, DYNAMIC_SLOTS */, ["checked", "click-action", "description", "disabled", "label", "test-id"]))
                        : ($setup.isSelectMenuItem(item))
                          ? (openBlock(), createBlock($setup["ActionSettingsWheelSelectItem"], {
                              key: 3,
                              icon: item.icon,
                              label: item.label,
                              value: item.value,
                              options: item.options,
                              "change-action": item.changeAction,
                              disabled: item.disabled,
                              "test-id": item.testId
                            }, null, 8 /* PROPS */, ["icon", "label", "value", "options", "change-action", "disabled", "test-id"]))
                          : (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                              key: 4,
                              icon: item.icon,
                              label: item.label,
                              "detail-value": item.detailValue,
                              template: item.template,
                              "click-action": item.clickAction,
                              disabled: item.disabled,
                              "test-id": item.testId
                            }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "template", "click-action", "disabled", "test-id"]))
                ], 64 /* STABLE_FRAGMENT */))
              }), 128 /* KEYED_FRAGMENT */))
            ], 64 /* STABLE_FRAGMENT */))
          }), 128 /* KEYED_FRAGMENT */)),
          (openBlock(true), createElementBlock(Fragment, null, renderList($setup.standaloneMenuActions, (item) => {
            return (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
              key: item.key,
              icon: item.icon,
              label: item.label,
              "detail-value": item.detailValue,
              template: item.template,
              "click-action": item.clickAction,
              disabled: item.disabled
            }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "template", "click-action", "disabled"]))
          }), 128 /* KEYED_FRAGMENT */))
        ], 64 /* STABLE_FRAGMENT */))
      : (openBlock(), createElementBlock("div", {
          key: 1,
          class: normalizeClass(["dropdown is-right", $setup.dropdownClass]),
          ref: "dropdownRoot"
        }, [
          createBaseVNode("div", _hoisted_6$d, [
            createBaseVNode("button", {
              type: "button",
              class: normalizeClass([$setup.getTriggerButtonClass, "is-inverted"]),
              "aria-haspopup": "true",
              "aria-controls": "dropdown-menu",
              "aria-expanded": $setup.isDropdownOpen ? 'true' : 'false',
              onClick: withModifiers($setup.toggleDropdown, ["stop"])
            }, [
              createBaseVNode("span", _hoisted_8$d, [
                createBaseVNode("i", {
                  class: normalizeClass($setup.props.icon)
                }, null, 2 /* CLASS */)
              ]),
              ($setup.props.label.length > 0)
                ? (openBlock(), createElementBlock("span", _hoisted_9$c, toDisplayString($setup.props.label), 1 /* TEXT */))
                : createCommentVNode("v-if", true)
            ], 10 /* CLASS, PROPS */, _hoisted_7$d)
          ]),
          createBaseVNode("div", {
            class: "dropdown-menu",
            id: "dropdown-menu",
            role: "menu",
            style: normalizeStyle($setup.dropdownMenuStyle)
          }, [
            createBaseVNode("div", {
              ref: "dropdownContent",
              class: normalizeClass(["dropdown-content", $setup.dropdownContentClass]),
              style: normalizeStyle($setup.dropdownContentStyle),
              onDropdownActionSelected: $setup.onActionSelected
            }, [
              ($setup.hasDropdownContent)
                ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                    ($setup.isDesktopFlyoutLayout && $setup.desktopFlyoutMenuSections.length > 0)
                      ? (openBlock(), createElementBlock("div", _hoisted_10$b, [
                          ($setup.activeDesktopFlyoutSubsection)
                            ? (openBlock(), createElementBlock("div", {
                                key: 0,
                                class: "action-settings-wheel-nested-panel",
                                "data-testid": 
                    $setup.activeDesktopFlyoutSubsection.testId
                      ? `${$setup.activeDesktopFlyoutSubsection.testId}-panel`
                      : `action-settings-wheel-subsection-panel-${$setup.activeDesktopFlyoutSubsection.key}`
                  
                              }, [
                                createBaseVNode("p", _hoisted_12$a, toDisplayString($setup.activeDesktopFlyoutSubsection.label), 1 /* TEXT */),
                                ($setup.activeDesktopFlyoutSubsection.description)
                                  ? (openBlock(), createElementBlock("p", _hoisted_13$9, toDisplayString($setup.activeDesktopFlyoutSubsection.description), 1 /* TEXT */))
                                  : createCommentVNode("v-if", true),
                                createBaseVNode("div", _hoisted_14$9, [
                                  (openBlock(true), createElementBlock(Fragment, null, renderList($setup.activeDesktopFlyoutSubsection.items || [], (subItem) => {
                                    return (openBlock(), createElementBlock(Fragment, {
                                      key: subItem.key
                                    }, [
                                      ($setup.isLabelMenuItem(subItem))
                                        ? (openBlock(), createBlock($setup["ActionSettingsWheelItemLabel"], {
                                            key: 0,
                                            icon: subItem.icon,
                                            label: subItem.label,
                                            "detail-value": subItem.detailValue,
                                            appearance: subItem.appearance,
                                            template: subItem.template,
                                            "data-testid": subItem.testId || undefined
                                          }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "appearance", "template", "data-testid"]))
                                        : ($setup.isToggleMenuItem(subItem))
                                          ? (openBlock(), createBlock($setup["ActionSettingsWheelToggleItem"], {
                                              key: 1,
                                              checked: subItem.value,
                                              "click-action": subItem.clickAction,
                                              description: subItem.description,
                                              disabled: subItem.disabled,
                                              label: subItem.label,
                                              "test-id": subItem.testId
                                            }, null, 8 /* PROPS */, ["checked", "click-action", "description", "disabled", "label", "test-id"]))
                                          : ($setup.isSelectMenuItem(subItem))
                                            ? (openBlock(), createBlock($setup["ActionSettingsWheelSelectItem"], {
                                                key: 2,
                                                icon: subItem.icon,
                                                label: subItem.label,
                                                value: subItem.value,
                                                options: subItem.options,
                                                "change-action": subItem.changeAction,
                                                disabled: subItem.disabled,
                                                "test-id": subItem.testId
                                              }, null, 8 /* PROPS */, ["icon", "label", "value", "options", "change-action", "disabled", "test-id"]))
                                            : (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                                                key: 3,
                                                icon: subItem.icon,
                                                label: subItem.label,
                                                "detail-value": subItem.detailValue,
                                                template: subItem.template,
                                                "click-action": subItem.clickAction,
                                                disabled: subItem.disabled,
                                                "test-id": subItem.testId
                                              }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "template", "click-action", "disabled", "test-id"]))
                                    ], 64 /* STABLE_FRAGMENT */))
                                  }), 128 /* KEYED_FRAGMENT */))
                                ])
                              ], 8 /* PROPS */, _hoisted_11$b))
                            : createCommentVNode("v-if", true),
                          createBaseVNode("div", _hoisted_15$9, [
                            (openBlock(true), createElementBlock(Fragment, null, renderList($setup.desktopFlyoutMenuSections, (section) => {
                              return (openBlock(), createElementBlock("div", {
                                key: section.key,
                                class: normalizeClass(["action-settings-wheel-flyout__submenu", {
                    'is-active': $setup.activeDesktopFlyoutSection?.key === section.key,
                    'action-settings-wheel-flyout__submenu--attachments': section.key === 'attachments',
                    'action-settings-wheel-flyout__submenu--rules': section.key === 'rules',
                    'action-settings-wheel-flyout__submenu--has-nested': $setup.hasSubsectionMenuItems(section),
                  }]),
                                "data-testid": `action-settings-wheel-submenu-${section.key}`
                              }, [
                                createBaseVNode("p", _hoisted_17$7, toDisplayString($setup.SessionUser.functions.ucFirst(section.label)), 1 /* TEXT */),
                                createBaseVNode("div", _hoisted_18$7, [
                                  (section.key === 'attachments')
                                    ? (openBlock(true), createElementBlock(Fragment, { key: 0 }, renderList(section.attachments || [], (attachment) => {
                                        return (openBlock(), createElementBlock("button", {
                                          key: `attachment-row-${attachment.id}`,
                                          type: "button",
                                          class: normalizeClass(["action-settings-wheel-section-trigger action-settings-wheel-section-trigger--attachment", { 'is-active': $setup.activeAttachmentId === attachment.id }]),
                                          "data-testid": `action-settings-wheel-attachment-row-${attachment.id}`,
                                          title: $setup.getAttachmentLabel(attachment),
                                          onMouseenter: $event => ($setup.setActiveAttachment(attachment)),
                                          onFocus: $event => ($setup.setActiveAttachment(attachment)),
                                          onClick: withModifiers($event => ($setup.setActiveAttachment(attachment)), ["stop","prevent"])
                                        }, [
                                          _cache[5] || (_cache[5] = createBaseVNode("span", { class: "action-settings-wheel-section-trigger__arrow" }, [
                                            createBaseVNode("i", {
                                              class: "fas fa-chevron-left",
                                              "aria-hidden": "true"
                                            })
                                          ], -1 /* CACHED */)),
                                          _cache[6] || (_cache[6] = createBaseVNode("span", { class: "action-settings-wheel-section-trigger__icon" }, [
                                            createBaseVNode("i", {
                                              class: "fas fa-paperclip",
                                              "aria-hidden": "true"
                                            })
                                          ], -1 /* CACHED */)),
                                          createBaseVNode("span", _hoisted_20$5, toDisplayString($setup.getAttachmentLabel(attachment)), 1 /* TEXT */)
                                        ], 42 /* CLASS, PROPS, NEED_HYDRATION */, _hoisted_19$6))
                                      }), 128 /* KEYED_FRAGMENT */))
                                    : (openBlock(true), createElementBlock(Fragment, { key: 1 }, renderList(section.items, (item) => {
                                        return (openBlock(), createElementBlock(Fragment, {
                                          key: item.key
                                        }, [
                                          ($setup.isSubsectionMenuItem(item))
                                            ? (openBlock(), createElementBlock("button", {
                                                key: 0,
                                                type: "button",
                                                class: normalizeClass(["action-settings-wheel-section-trigger action-settings-wheel-section-trigger--nested", { 'is-active': $setup.activeDesktopFlyoutSubsection?.key === item.key }]),
                                                "data-testid": item.testId || `action-settings-wheel-subsection-${item.key}`,
                                                onMouseenter: $event => ($setup.setActiveDesktopFlyoutSubsection(item.key)),
                                                onFocus: $event => ($setup.setActiveDesktopFlyoutSubsection(item.key)),
                                                onClick: withModifiers($event => ($setup.setActiveDesktopFlyoutSubsection(item.key)), ["stop","prevent"])
                                              }, [
                                                _cache[7] || (_cache[7] = createBaseVNode("span", { class: "action-settings-wheel-section-trigger__arrow" }, [
                                                  createBaseVNode("i", {
                                                    class: "fas fa-chevron-left",
                                                    "aria-hidden": "true"
                                                  })
                                                ], -1 /* CACHED */)),
                                                createBaseVNode("span", _hoisted_22$5, [
                                                  createBaseVNode("span", _hoisted_23$5, toDisplayString(item.label), 1 /* TEXT */),
                                                  (item.description)
                                                    ? (openBlock(), createElementBlock("span", _hoisted_24$5, toDisplayString(item.description), 1 /* TEXT */))
                                                    : createCommentVNode("v-if", true)
                                                ])
                                              ], 42 /* CLASS, PROPS, NEED_HYDRATION */, _hoisted_21$5))
                                            : ($setup.isLabelMenuItem(item))
                                              ? (openBlock(), createBlock($setup["ActionSettingsWheelItemLabel"], {
                                                  key: 1,
                                                  icon: item.icon,
                                                  label: item.label,
                                                  "detail-value": item.detailValue,
                                                  appearance: item.appearance,
                                                  template: item.template,
                                                  "data-testid": item.testId || undefined
                                                }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "appearance", "template", "data-testid"]))
                                              : ($setup.isToggleMenuItem(item))
                                                ? (openBlock(), createBlock($setup["ActionSettingsWheelToggleItem"], {
                                                    key: 2,
                                                    checked: item.value,
                                                    "click-action": item.clickAction,
                                                    description: item.description,
                                                    disabled: item.disabled,
                                                    label: item.label,
                                                    "test-id": item.testId
                                                  }, createSlots({ _: 2 /* DYNAMIC */ }, [
                                                    (item.customerRuleAttribute)
                                                      ? {
                                                          name: "label",
                                                          fn: withCtx(({ label }) => [
                                                            createVNode($setup["CustomerRuleTooltip"], {
                                                              attribute: item.customerRuleAttribute,
                                                              active: item.customerRuleActive,
                                                              "customer-number": item.customerRuleCustomerNumber,
                                                              "department-id": item.customerRuleDepartmentId,
                                                              "test-id": `${item.testId}-tooltip`
                                                            }, {
                                                              default: withCtx(() => [
                                                                createBaseVNode("span", null, toDisplayString(label), 1 /* TEXT */)
                                                              ]),
                                                              _: 2 /* DYNAMIC */
                                                            }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["attribute", "active", "customer-number", "department-id", "test-id"])
                                                          ]),
                                                          key: "0"
                                                        }
                                                      : undefined
                                                  ]), 1032 /* PROPS, DYNAMIC_SLOTS */, ["checked", "click-action", "description", "disabled", "label", "test-id"]))
                                                : ($setup.isSelectMenuItem(item))
                                                  ? (openBlock(), createBlock($setup["ActionSettingsWheelSelectItem"], {
                                                      key: 3,
                                                      icon: item.icon,
                                                      label: item.label,
                                                      value: item.value,
                                                      options: item.options,
                                                      "change-action": item.changeAction,
                                                      disabled: item.disabled,
                                                      "test-id": item.testId
                                                    }, null, 8 /* PROPS */, ["icon", "label", "value", "options", "change-action", "disabled", "test-id"]))
                                                  : (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                                                      key: 4,
                                                      icon: item.icon,
                                                      label: item.label,
                                                      "detail-value": item.detailValue,
                                                      template: item.template,
                                                      "click-action": item.clickAction,
                                                      disabled: item.disabled,
                                                      "test-id": item.testId
                                                    }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "template", "click-action", "disabled", "test-id"]))
                                        ], 64 /* STABLE_FRAGMENT */))
                                      }), 128 /* KEYED_FRAGMENT */))
                                ]),
                                (section.key === 'attachments' && $setup.activeDesktopFlyoutSection?.key === 'attachments' && $setup.activeAttachment)
                                  ? (openBlock(), createElementBlock("div", _hoisted_25$5, [
                                      createBaseVNode("p", {
                                        class: "action-settings-wheel-attachment-panel__title",
                                        title: $setup.getAttachmentLabel($setup.activeAttachment)
                                      }, toDisplayString($setup.getAttachmentLabel($setup.activeAttachment)), 9 /* TEXT, PROPS */, _hoisted_26$5),
                                      createBaseVNode("div", _hoisted_27$5, [
                                        ($setup.previewLoadingAttachmentId === $setup.activeAttachment.id)
                                          ? (openBlock(), createElementBlock("span", _hoisted_28$5, toDisplayString($setup.t("global.loading")), 1 /* TEXT */))
                                          : ($setup.activeAttachmentPreviewKind === 'image' && $setup.activeAttachmentPreviewSource)
                                            ? (openBlock(), createElementBlock("img", {
                                                key: 1,
                                                src: $setup.activeAttachmentPreviewSource,
                                                alt: "",
                                                class: "action-settings-wheel-attachment-panel__image"
                                              }, null, 8 /* PROPS */, _hoisted_29$4))
                                            : ($setup.activeAttachmentPreviewKind === 'document' && $setup.activeAttachmentPreviewSource)
                                              ? (openBlock(), createElementBlock("iframe", {
                                                  key: 2,
                                                  src: $setup.activeAttachmentPreviewSource,
                                                  title: "Attachment preview",
                                                  class: "action-settings-wheel-attachment-panel__document"
                                                }, null, 8 /* PROPS */, _hoisted_30$4))
                                              : ($setup.activeAttachmentPreviewKind === 'link')
                                                ? (openBlock(), createElementBlock("a", {
                                                    key: 3,
                                                    href: $setup.activeAttachment.content?.other,
                                                    target: "_blank",
                                                    rel: "noopener noreferrer",
                                                    class: "action-settings-wheel-attachment-panel__text action-settings-wheel-attachment-panel__link"
                                                  }, toDisplayString($setup.activeAttachment.content?.other), 9 /* TEXT, PROPS */, _hoisted_31$4))
                                                : (['image', 'document'].includes($setup.activeAttachmentPreviewKind))
                                                  ? (openBlock(), createElementBlock("div", _hoisted_32$4, [
                                                      createBaseVNode("span", _hoisted_33$4, [
                                                        createBaseVNode("i", {
                                                          class: normalizeClass($setup.getAttachmentPreviewPlaceholderIcon($setup.activeAttachment)),
                                                          "aria-hidden": "true"
                                                        }, null, 2 /* CLASS */)
                                                      ]),
                                                      createBaseVNode("span", _hoisted_34$4, toDisplayString($setup.getAttachmentPreviewPlaceholderLabel($setup.activeAttachment)), 1 /* TEXT */)
                                                    ]))
                                                  : ($setup.activeAttachmentPreviewKind === 'office')
                                                    ? (openBlock(), createElementBlock("span", _hoisted_35$4, toDisplayString($setup.t("admin.pos.attachments_office_preview_unavailable")), 1 /* TEXT */))
                                                    : ($setup.activeAttachmentPreviewKind === 'text')
                                                      ? (openBlock(), createElementBlock("span", _hoisted_36$3, toDisplayString($setup.formatAttachmentText($setup.activeAttachment)), 1 /* TEXT */))
                                                      : (openBlock(), createElementBlock("span", _hoisted_37$3, toDisplayString($setup.t("admin.pos.attachments_no_preview")), 1 /* TEXT */))
                                      ]),
                                      createBaseVNode("div", _hoisted_38$3, [
                                        createBaseVNode("button", {
                                          type: "button",
                                          class: "action-settings-wheel-attachment-action",
                                          "data-testid": `action-settings-wheel-attachment-action-preview-${$setup.activeAttachment.id}`,
                                          onClick: _cache[0] || (_cache[0] = withModifiers($event => ($setup.previewAttachment($setup.activeAttachment)), ["stop","prevent"]))
                                        }, [
                                          _cache[8] || (_cache[8] = createBaseVNode("span", { class: "action-settings-wheel-attachment-action__icon" }, [
                                            createBaseVNode("i", {
                                              class: "fas fa-eye",
                                              "aria-hidden": "true"
                                            })
                                          ], -1 /* CACHED */)),
                                          createBaseVNode("span", null, toDisplayString($setup.t("global.preview")), 1 /* TEXT */)
                                        ], 8 /* PROPS */, _hoisted_39$3),
                                        createBaseVNode("button", {
                                          type: "button",
                                          class: "action-settings-wheel-attachment-action",
                                          "data-testid": `action-settings-wheel-attachment-action-download-${$setup.activeAttachment.id}`,
                                          onClick: _cache[1] || (_cache[1] = withModifiers($event => ($setup.downloadAttachment($setup.activeAttachment)), ["stop","prevent"]))
                                        }, [
                                          _cache[9] || (_cache[9] = createBaseVNode("span", { class: "action-settings-wheel-attachment-action__icon" }, [
                                            createBaseVNode("i", {
                                              class: "fas fa-download",
                                              "aria-hidden": "true"
                                            })
                                          ], -1 /* CACHED */)),
                                          createBaseVNode("span", null, toDisplayString($setup.t("common.download")), 1 /* TEXT */)
                                        ], 8 /* PROPS */, _hoisted_40$3),
                                        createBaseVNode("button", {
                                          type: "button",
                                          class: "action-settings-wheel-attachment-action",
                                          "data-testid": `action-settings-wheel-attachment-action-print-${$setup.activeAttachment.id}`,
                                          onClick: _cache[2] || (_cache[2] = withModifiers($event => ($setup.printAttachment($setup.activeAttachment)), ["stop","prevent"]))
                                        }, [
                                          _cache[10] || (_cache[10] = createBaseVNode("span", { class: "action-settings-wheel-attachment-action__icon" }, [
                                            createBaseVNode("i", {
                                              class: "fas fa-print",
                                              "aria-hidden": "true"
                                            })
                                          ], -1 /* CACHED */)),
                                          createBaseVNode("span", null, toDisplayString($setup.t("global.print")), 1 /* TEXT */)
                                        ], 8 /* PROPS */, _hoisted_41$3),
                                        ($setup.SessionUser.canAccessAdmin() || $setup.SessionUser.canAccessSuperUser())
                                          ? (openBlock(), createElementBlock("button", {
                                              key: 0,
                                              type: "button",
                                              class: "action-settings-wheel-attachment-action action-settings-wheel-attachment-action--danger",
                                              disabled: $setup.deletingAttachmentId === $setup.activeAttachment.id,
                                              "data-testid": `action-settings-wheel-attachment-action-delete-${$setup.activeAttachment.id}`,
                                              onClick: _cache[3] || (_cache[3] = withModifiers($event => ($setup.removeAttachment($setup.activeAttachment)), ["stop","prevent"]))
                                            }, [
                                              _cache[11] || (_cache[11] = createBaseVNode("span", { class: "action-settings-wheel-attachment-action__icon" }, [
                                                createBaseVNode("i", {
                                                  class: "fas fa-trash-alt",
                                                  "aria-hidden": "true"
                                                })
                                              ], -1 /* CACHED */)),
                                              createBaseVNode("span", null, toDisplayString($setup.t("global.delete")), 1 /* TEXT */)
                                            ], 8 /* PROPS */, _hoisted_42$3))
                                          : createCommentVNode("v-if", true)
                                      ])
                                    ]))
                                  : createCommentVNode("v-if", true)
                              ], 10 /* CLASS, PROPS */, _hoisted_16$9))
                            }), 128 /* KEYED_FRAGMENT */))
                          ]),
                          createBaseVNode("div", _hoisted_43$3, [
                            ($setup.hasCustomActionsSlot)
                              ? renderSlot(_ctx.$slots, "actions", { key: 0 }, undefined, true)
                              : createCommentVNode("v-if", true),
                            (openBlock(true), createElementBlock(Fragment, null, renderList($setup.desktopFlyoutMenuSections, (section) => {
                              return (openBlock(), createElementBlock("button", {
                                key: section.key,
                                type: "button",
                                class: normalizeClass(["action-settings-wheel-section-trigger", { 'is-active': $setup.activeDesktopFlyoutSection?.key === section.key }]),
                                "data-testid": `action-settings-wheel-section-${section.key}`,
                                onMouseenter: $event => ($setup.setActiveDesktopFlyoutSection(section.key)),
                                onFocus: $event => ($setup.setActiveDesktopFlyoutSection(section.key)),
                                onClick: withModifiers($event => ($setup.setActiveDesktopFlyoutSection(section.key)), ["stop","prevent"])
                              }, [
                                _cache[12] || (_cache[12] = createBaseVNode("span", { class: "action-settings-wheel-section-trigger__arrow" }, [
                                  createBaseVNode("i", {
                                    class: "fas fa-chevron-left",
                                    "aria-hidden": "true"
                                  })
                                ], -1 /* CACHED */)),
                                createBaseVNode("span", _hoisted_45$3, toDisplayString($setup.SessionUser.functions.ucFirst(section.label)), 1 /* TEXT */)
                              ], 42 /* CLASS, PROPS, NEED_HYDRATION */, _hoisted_44$3))
                            }), 128 /* KEYED_FRAGMENT */)),
                            ($setup.standaloneMenuActions.length > 0)
                              ? (openBlock(), createElementBlock("div", _hoisted_46$3, [
                                  (openBlock(true), createElementBlock(Fragment, null, renderList($setup.standaloneMenuActions, (item) => {
                                    return (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                                      key: item.key,
                                      icon: item.icon,
                                      label: item.label,
                                      "detail-value": item.detailValue,
                                      template: item.template,
                                      "click-action": item.clickAction,
                                      disabled: item.disabled
                                    }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "template", "click-action", "disabled"]))
                                  }), 128 /* KEYED_FRAGMENT */))
                                ]))
                              : createCommentVNode("v-if", true)
                          ])
                        ]))
                      : (openBlock(), createElementBlock("div", _hoisted_47$3, [
                          ($setup.hasCustomActionsSlot)
                            ? renderSlot(_ctx.$slots, "actions", { key: 0 }, undefined, true)
                            : createCommentVNode("v-if", true),
                          (openBlock(true), createElementBlock(Fragment, null, renderList($setup.flatBuiltInMenuSections, (section) => {
                            return (openBlock(), createElementBlock(Fragment, {
                              key: section.key
                            }, [
                              createVNode($setup["ActionSettingsWheelItemLabel"], {
                                label: section.label,
                                "data-testid": `action-settings-wheel-section-${section.key}`
                              }, null, 8 /* PROPS */, ["label", "data-testid"]),
                              (openBlock(true), createElementBlock(Fragment, null, renderList(section.items, (item) => {
                                return (openBlock(), createElementBlock(Fragment, {
                                  key: item.key
                                }, [
                                  ($setup.isSubsectionMenuItem(item))
                                    ? (openBlock(), createElementBlock("div", {
                                        key: 0,
                                        class: "action-settings-wheel-subsection",
                                        "data-testid": item.testId || `action-settings-wheel-subsection-${item.key}`
                                      }, [
                                        createBaseVNode("p", _hoisted_49$2, toDisplayString(item.label), 1 /* TEXT */),
                                        (item.description)
                                          ? (openBlock(), createElementBlock("p", _hoisted_50$2, toDisplayString(item.description), 1 /* TEXT */))
                                          : createCommentVNode("v-if", true),
                                        (openBlock(true), createElementBlock(Fragment, null, renderList(item.items || [], (subItem) => {
                                          return (openBlock(), createElementBlock(Fragment, {
                                            key: subItem.key
                                          }, [
                                            ($setup.isLabelMenuItem(subItem))
                                              ? (openBlock(), createBlock($setup["ActionSettingsWheelItemLabel"], {
                                                  key: 0,
                                                  icon: subItem.icon,
                                                  label: subItem.label,
                                                  "detail-value": subItem.detailValue,
                                                  appearance: subItem.appearance,
                                                  template: subItem.template,
                                                  "data-testid": subItem.testId || undefined
                                                }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "appearance", "template", "data-testid"]))
                                              : ($setup.isToggleMenuItem(subItem))
                                                ? (openBlock(), createBlock($setup["ActionSettingsWheelToggleItem"], {
                                                    key: 1,
                                                    checked: subItem.value,
                                                    "click-action": subItem.clickAction,
                                                    description: subItem.description,
                                                    disabled: subItem.disabled,
                                                    label: subItem.label,
                                                    "test-id": subItem.testId
                                                  }, null, 8 /* PROPS */, ["checked", "click-action", "description", "disabled", "label", "test-id"]))
                                                : ($setup.isSelectMenuItem(subItem))
                                                  ? (openBlock(), createBlock($setup["ActionSettingsWheelSelectItem"], {
                                                      key: 2,
                                                      icon: subItem.icon,
                                                      label: subItem.label,
                                                      value: subItem.value,
                                                      options: subItem.options,
                                                      "change-action": subItem.changeAction,
                                                      disabled: subItem.disabled,
                                                      "test-id": subItem.testId
                                                    }, null, 8 /* PROPS */, ["icon", "label", "value", "options", "change-action", "disabled", "test-id"]))
                                                  : (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                                                      key: 3,
                                                      icon: subItem.icon,
                                                      label: subItem.label,
                                                      "detail-value": subItem.detailValue,
                                                      template: subItem.template,
                                                      "click-action": subItem.clickAction,
                                                      disabled: subItem.disabled,
                                                      "test-id": subItem.testId
                                                    }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "template", "click-action", "disabled", "test-id"]))
                                          ], 64 /* STABLE_FRAGMENT */))
                                        }), 128 /* KEYED_FRAGMENT */))
                                      ], 8 /* PROPS */, _hoisted_48$3))
                                    : ($setup.isLabelMenuItem(item))
                                      ? (openBlock(), createBlock($setup["ActionSettingsWheelItemLabel"], {
                                          key: 1,
                                          icon: item.icon,
                                          label: item.label,
                                          "detail-value": item.detailValue,
                                          appearance: item.appearance,
                                          template: item.template,
                                          "data-testid": item.testId || undefined
                                        }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "appearance", "template", "data-testid"]))
                                      : ($setup.isToggleMenuItem(item))
                                        ? (openBlock(), createBlock($setup["ActionSettingsWheelToggleItem"], {
                                            key: 2,
                                            checked: item.value,
                                            "click-action": item.clickAction,
                                            description: item.description,
                                            disabled: item.disabled,
                                            label: item.label,
                                            "test-id": item.testId
                                          }, createSlots({ _: 2 /* DYNAMIC */ }, [
                                            (item.customerRuleAttribute)
                                              ? {
                                                  name: "label",
                                                  fn: withCtx(({ label }) => [
                                                    createVNode($setup["CustomerRuleTooltip"], {
                                                      attribute: item.customerRuleAttribute,
                                                      active: item.customerRuleActive,
                                                      "customer-number": item.customerRuleCustomerNumber,
                                                      "department-id": item.customerRuleDepartmentId,
                                                      "test-id": `${item.testId}-tooltip`
                                                    }, {
                                                      default: withCtx(() => [
                                                        createBaseVNode("span", null, toDisplayString(label), 1 /* TEXT */)
                                                      ]),
                                                      _: 2 /* DYNAMIC */
                                                    }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["attribute", "active", "customer-number", "department-id", "test-id"])
                                                  ]),
                                                  key: "0"
                                                }
                                              : undefined
                                          ]), 1032 /* PROPS, DYNAMIC_SLOTS */, ["checked", "click-action", "description", "disabled", "label", "test-id"]))
                                        : ($setup.isSelectMenuItem(item))
                                          ? (openBlock(), createBlock($setup["ActionSettingsWheelSelectItem"], {
                                              key: 3,
                                              icon: item.icon,
                                              label: item.label,
                                              value: item.value,
                                              options: item.options,
                                              "change-action": item.changeAction,
                                              disabled: item.disabled,
                                              "test-id": item.testId
                                            }, null, 8 /* PROPS */, ["icon", "label", "value", "options", "change-action", "disabled", "test-id"]))
                                          : (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                                              key: 4,
                                              icon: item.icon,
                                              label: item.label,
                                              "detail-value": item.detailValue,
                                              template: item.template,
                                              "click-action": item.clickAction,
                                              disabled: item.disabled,
                                              "test-id": item.testId
                                            }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "template", "click-action", "disabled", "test-id"]))
                                ], 64 /* STABLE_FRAGMENT */))
                              }), 128 /* KEYED_FRAGMENT */))
                            ], 64 /* STABLE_FRAGMENT */))
                          }), 128 /* KEYED_FRAGMENT */)),
                          (openBlock(true), createElementBlock(Fragment, null, renderList($setup.standaloneMenuActions, (item) => {
                            return (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                              key: item.key,
                              icon: item.icon,
                              label: item.label,
                              "detail-value": item.detailValue,
                              template: item.template,
                              "click-action": item.clickAction,
                              disabled: item.disabled
                            }, null, 8 /* PROPS */, ["icon", "label", "detail-value", "template", "click-action", "disabled"]))
                          }), 128 /* KEYED_FRAGMENT */))
                        ]))
                  ], 64 /* STABLE_FRAGMENT */))
                : (openBlock(), createElementBlock("div", _hoisted_51$2, [
                    createBaseVNode("p", _hoisted_52$2, toDisplayString($setup.t("admin.pos.settings_wheel.no_actions_defined")), 1 /* TEXT */)
                  ]))
            ], 38 /* CLASS, STYLE, NEED_HYDRATION */)
          ], 4 /* STYLE */)
        ], 2 /* CLASS */)),
    ($setup.customerModalVisible)
      ? (openBlock(), createBlock($setup["CustomerModal"], {
          key: 2,
          user_id: $setup.userIdFromCustomerNumber,
          onCloseModal: _cache[4] || (_cache[4] = $event => ($setup.customerModalVisible = false))
        }, null, 8 /* PROPS */, ["user_id"]))
      : createCommentVNode("v-if", true)
  ]))
}
const ActionSettingsWheelButton = /*#__PURE__*/_export_sfc(_sfc_main$O, [['render',_sfc_render$h],['__scopeId',"data-v-5423d2e1"],['__file',"ActionSettingsWheelButton.vue"]]);

const INVOICE_COLLECTION_BULK_ACTIONS = Object.freeze({
  CLEAN_CUSTOMER_RULES: "remove_customer_rule_violations",
  MERGE: "merge_collections",
  SPLIT_BY_MONTH: "split_by_month",
  RESET_HIDDEN_PRICES: "reset_hidden_item_prices",
  QUEUE_ECONOMIC: "queue_economic",
});

const _sfc_main$N = {
  __name: 'InvoiceCollectionSelectionActionWheel',
  props: {
  selectedInvoiceCollectionIds: {
    type: Array,
    default: () => [],
  },
  totalInvoiceCollectionCount: {
    type: Number,
    default: 0,
  },
  allSelected: {
    type: Boolean,
    default: false,
  },
  allExpanded: {
    type: Boolean,
    default: false,
  },
  invoiceQueueBusy: {
    type: Boolean,
    default: false,
  },
},
  emits: ["invoiceSelected", "bulkAction", "toggleSelectAll", "toggleExpandAll"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const props = __props;

const emit = __emit;
const { t } = useI18n();

const selectedCount = computed(() => props.selectedInvoiceCollectionIds.length);
const hasSelectableCollections = computed(() => props.totalInvoiceCollectionCount > 0);
const hasSelectedCollections = computed(() => selectedCount.value > 0);
const hasMultipleSelectedCollections = computed(() => selectedCount.value > 1);
const triggerLabel = computed(() =>
  t("invoicing_period.invoice_collection_actions.menu.label", { count: selectedCount.value })
);
const selectAllLabel = computed(() =>
  props.allSelected
    ? t("invoicing_period.invoice_collection_actions.menu.unselect_all")
    : t("invoicing_period.invoice_collection_actions.menu.select_all")
);
const expandAllLabel = computed(() =>
  props.allExpanded
    ? t("invoicing_period.invoice_collection_actions.menu.collapse_all")
    : t("invoicing_period.invoice_collection_actions.menu.expand_all")
);

const emitBulkAction = (action) => emit("bulkAction", action);

const __returned__ = { props, emit, t, selectedCount, hasSelectableCollections, hasSelectedCollections, hasMultipleSelectedCollections, triggerLabel, selectAllLabel, expandAllLabel, emitBulkAction, computed, get useI18n() { return useI18n }, ActionSettingsWheelButton, ActionSettingsWheelItem, ActionSettingsWheelItemLabel, get INVOICE_COLLECTION_BULK_ACTIONS() { return INVOICE_COLLECTION_BULK_ACTIONS } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$g = {
  key: 0,
  class: "invoice-collection-selection-action-wheel",
  "data-testid": "invoice-collection-selection-action-wheel"
};

function _sfc_render$g(_ctx, _cache, $props, $setup, $data, $options) {
  return ($setup.hasSelectableCollections)
    ? (openBlock(), createElementBlock("div", _hoisted_1$g, [
        createVNode($setup["ActionSettingsWheelButton"], {
          icon: "fas fa-sliders-h",
          label: $setup.triggerLabel
        }, {
          actions: withCtx(() => [
            createVNode($setup["ActionSettingsWheelItemLabel"], {
              label: $setup.t('invoicing_period.invoice_collection_actions.menu.selection_section'),
              "data-testid": "invoice-collection-selection-action-wheel-selection-section"
            }, null, 8 /* PROPS */, ["label"]),
            createVNode($setup["ActionSettingsWheelItem"], {
              icon: "fas fa-check-double",
              label: $setup.selectAllLabel,
              "click-action": () => $setup.emit('toggleSelectAll'),
              "test-id": "invoice-collection-selection-action-wheel-select-all"
            }, null, 8 /* PROPS */, ["label", "click-action"]),
            createVNode($setup["ActionSettingsWheelItem"], {
              icon: $props.allExpanded ? 'fas fa-compress-alt' : 'fas fa-expand-alt',
              label: $setup.expandAllLabel,
              "click-action": () => $setup.emit('toggleExpandAll'),
              "test-id": "invoice-collection-selection-action-wheel-expand-all"
            }, null, 8 /* PROPS */, ["icon", "label", "click-action"]),
            ($setup.hasSelectedCollections)
              ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                  createVNode($setup["ActionSettingsWheelItemLabel"], {
                    label: $setup.t('invoicing_period.invoice_collection_actions.menu.modification_section'),
                    "data-testid": "invoice-collection-selection-action-wheel-modification-section"
                  }, null, 8 /* PROPS */, ["label"]),
                  createVNode($setup["ActionSettingsWheelItem"], {
                    icon: "fas fa-file-invoice-dollar",
                    label: $setup.t('invoicing_period.invoice_collection_actions.actions.queue_economic'),
                    "click-action": () => $setup.emit('invoiceSelected'),
                    disabled: $props.invoiceQueueBusy,
                    "test-id": "invoice-collection-selection-action-wheel-invoice-selected"
                  }, null, 8 /* PROPS */, ["label", "click-action", "disabled"]),
                  createVNode($setup["ActionSettingsWheelItem"], {
                    icon: "fas fa-broom",
                    label: $setup.t('invoicing_period.invoice_collection_actions.actions.remove_customer_rule_violations'),
                    "click-action": () => $setup.emitBulkAction($setup.INVOICE_COLLECTION_BULK_ACTIONS.CLEAN_CUSTOMER_RULES),
                    "test-id": "invoice-collection-selection-action-wheel-clean-rules"
                  }, null, 8 /* PROPS */, ["label", "click-action"]),
                  ($setup.hasMultipleSelectedCollections)
                    ? (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                        key: 0,
                        icon: "fas fa-compress-arrows-alt",
                        label: $setup.t('invoicing_period.invoice_collection_actions.actions.merge_collections'),
                        "click-action": () => $setup.emitBulkAction($setup.INVOICE_COLLECTION_BULK_ACTIONS.MERGE),
                        "test-id": "invoice-collection-selection-action-wheel-merge"
                      }, null, 8 /* PROPS */, ["label", "click-action"]))
                    : createCommentVNode("v-if", true),
                  createVNode($setup["ActionSettingsWheelItem"], {
                    icon: "fas fa-calendar-alt",
                    label: $setup.t('invoicing_period.invoice_collection_actions.actions.split_by_month'),
                    "click-action": () => $setup.emitBulkAction($setup.INVOICE_COLLECTION_BULK_ACTIONS.SPLIT_BY_MONTH),
                    "test-id": "invoice-collection-selection-action-wheel-split-by-month"
                  }, null, 8 /* PROPS */, ["label", "click-action"]),
                  createVNode($setup["ActionSettingsWheelItem"], {
                    icon: "fas fa-undo",
                    label: $setup.t('invoicing_period.invoice_collection_actions.actions.reset_hidden_item_prices'),
                    "click-action": () => $setup.emitBulkAction($setup.INVOICE_COLLECTION_BULK_ACTIONS.RESET_HIDDEN_PRICES),
                    "test-id": "invoice-collection-selection-action-wheel-reset-hidden-prices"
                  }, null, 8 /* PROPS */, ["label", "click-action"])
                ], 64 /* STABLE_FRAGMENT */))
              : createCommentVNode("v-if", true)
          ]),
          _: 1 /* STABLE */
        }, 8 /* PROPS */, ["label"])
      ]))
    : createCommentVNode("v-if", true)
}
const InvoiceCollectionSelectionActionWheel = /*#__PURE__*/_export_sfc(_sfc_main$N, [['render',_sfc_render$g],['__file',"InvoiceCollectionSelectionActionWheel.vue"]]);

const acceptedOrderAttachmentFileTypes = "image/*,application/pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx";

const _sfc_main$M = {
  __name: 'OrderAttachmentsActionButton',
  props: {
  order: {
    type: Object,
    required: true,
  },
  refreshFunction: {
    type: Function,
    default: () => {},
  },
  dataTestId: {
    type: String,
    default: "",
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const imageExtensions = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg"];
const officeExtensions = [".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx"];
const safePreviewBlobTypesByKind = {
  image: {
    fallback: "image/png",
    allowed: new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp", "image/svg+xml"]),
  },
  document: {
    fallback: "application/pdf",
    allowed: new Set(["application/pdf"]),
  },
};

const props = __props;

const { t } = useI18n();

const dropdownRoot = ref(null);
const isDropdownOpen = ref(false);
const attachments = ref([]);
const attachmentsLoaded = ref(false);
const isLoadingAttachments = ref(false);
const activePreviewAttachmentId = ref(null);
const previewLoadingAttachmentId = ref(null);
const previewSourcesById = ref({});
const previewRequestsInFlight = new Set();
const generatedObjectUrls = new Set();

const normalizeAttachments = (order) => (Array.isArray(order?.attachments) ? order.attachments : []);

const isObjectUrl = (value) => typeof value === "string" && value.startsWith("blob:");

const releaseObjectUrl = (value) => {
  if (!isObjectUrl(value)) {
    return;
  }

  URL.revokeObjectURL(value);
  generatedObjectUrls.delete(value);
};

const clearPreviewState = () => {
  Object.values(previewSourcesById.value).forEach((value) => {
    releaseObjectUrl(value);
  });
  previewSourcesById.value = {};
  activePreviewAttachmentId.value = null;
  previewLoadingAttachmentId.value = null;
};

const resetAttachmentsFromOrder = () => {
  const normalizedAttachments = normalizeAttachments(props.order);
  attachments.value = normalizedAttachments;
  attachmentsLoaded.value = normalizedAttachments.length > 0;
};

resetAttachmentsFromOrder();

watch(
  () => [props.order?.id, props.order?.attachments],
  () => {
    resetAttachmentsFromOrder();
    clearPreviewState();
    isDropdownOpen.value = false;
  }
);

const canAddOrderAttachments = computed(() => {
  return !!props.order?.id && (SessionUser.canAccessAdmin() || SessionUser.canAccessSuperUser());
});

const canAccessOrderAttachments = computed(() => {
  return (
    SessionUser.canAccessAdmin() ||
    SessionUser.canAccessSuperUser() ||
    SessionUser.hasPermission("download_order_attachments_own") ||
    SessionUser.hasPermission("download_order_attachments")
  );
});

const hasAttachmentIndicator = computed(() => {
  if (attachments.value.length > 0 || props.order?.has_attachments === true) {
    return true;
  }

  return [props.order?.attachments_count, props.order?.attachment_count, props.order?.attachmentsCount].some(
    (value) => {
      const normalizedValue = Number.parseInt(value, 10);
      return Number.isInteger(normalizedValue) && normalizedValue > 0;
    }
  );
});

const shouldShowButton = computed(() => {
  if (hasAttachmentIndicator.value) {
    return canAccessOrderAttachments.value || canAddOrderAttachments.value;
  }

  return canAddOrderAttachments.value;
});

const triggerIcon = computed(() => (hasAttachmentIndicator.value ? "fas fa-paperclip" : "fas fa-plus"));
const isTextTriggerButton = computed(() => !hasAttachmentIndicator.value);
const triggerButtonClass = computed(() => ({
  button: true,
  "is-small": true,
  "is-dark": hasAttachmentIndicator.value,
  "action-settings-wheel-trigger": true,
  "action-settings-wheel-trigger--text": isTextTriggerButton.value,
  "action-settings-wheel-trigger--icon-only": true,
}));
const activePreviewAttachment = computed(() => {
  return attachments.value.find((attachment) => attachment.id === activePreviewAttachmentId.value) || null;
});

const getAttachmentLabel = (attachment) => {
  return (
    attachment?.content?.document ||
    attachment?.content?.image ||
    attachment?.content?.other ||
    `Attachment ${attachment?.id ?? ""}`.trim()
  );
};

const getAttachmentExtension = (attachment) => {
  const match = getAttachmentLabel(attachment)
    .toLowerCase()
    .match(/(\.[a-z0-9]+)$/);

  return match?.[1] || "";
};

const getAttachmentPreviewKind = (attachment) => {
  const extension = getAttachmentExtension(attachment);

  if (attachment?.content?.image || imageExtensions.includes(extension)) {
    return "image";
  }

  if (attachment?.content?.document || extension === ".pdf") {
    return officeExtensions.includes(extension) ? "office" : "document";
  }

  if (officeExtensions.includes(extension)) {
    return "office";
  }

  if (String(attachment?.content?.other || "").startsWith("http")) {
    return "link";
  }

  if (attachment?.content?.other) {
    return "text";
  }

  return "none";
};

const activePreviewKind = computed(() => {
  if (!activePreviewAttachment.value) {
    return "none";
  }

  return getAttachmentPreviewKind(activePreviewAttachment.value);
});

const activePreviewSource = computed(() => {
  if (!activePreviewAttachment.value) {
    return null;
  }

  return previewSourcesById.value[activePreviewAttachment.value.id] ?? null;
});

const closeDropdown = () => {
  isDropdownOpen.value = false;
  activePreviewAttachmentId.value = null;
  previewLoadingAttachmentId.value = null;
};

const onActionSelected = () => {
  closeDropdown();
};

const onDocumentClick = (event) => {
  if (!isDropdownOpen.value) {
    return;
  }

  if (dropdownRoot.value && !dropdownRoot.value.contains(event.target)) {
    closeDropdown();
  }
};

const onDocumentKeydown = (event) => {
  if (event.key === "Escape") {
    closeDropdown();
  }
};

onMounted(() => {
  document.addEventListener("click", onDocumentClick);
  document.addEventListener("keydown", onDocumentKeydown);
});

onBeforeUnmount(() => {
  document.removeEventListener("click", onDocumentClick);
  document.removeEventListener("keydown", onDocumentKeydown);
  clearPreviewState();
});

const ensureAttachmentsLoaded = async (force = false) => {
  const shouldRefetchAttachmentList = attachments.value.length === 0;

  if (
    !props.order?.id ||
    (attachmentsLoaded.value && !force && !shouldRefetchAttachmentList) ||
    isLoadingAttachments.value
  ) {
    return attachments.value;
  }

  isLoadingAttachments.value = true;

  try {
    const response = await SessionUser.objects.orders.functions.fetchAttachments(props.order.id);
    attachments.value = Array.isArray(response) ? response : [];
    attachmentsLoaded.value = true;
  } catch (error) {
    console.error("Error loading order attachments:", error);
  } finally {
    isLoadingAttachments.value = false;
  }

  return attachments.value;
};

watch(
  () => [props.order?.id, props.order?.attachments, canAccessOrderAttachments.value, canAddOrderAttachments.value],
  () => {
    if (!props.order?.id || (!canAccessOrderAttachments.value && !canAddOrderAttachments.value)) {
      return;
    }

    if (attachments.value.length > 0) {
      return;
    }

    void ensureAttachmentsLoaded();
  },
  { immediate: true }
);

const readAttachmentFileAsBase64 = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      resolve(event.target?.result ?? null);
    };
    reader.onerror = () => {
      reject(new Error("Failed to read attachment file"));
    };
    reader.readAsDataURL(file);
  });

const refreshAfterMutation = async () => {
  await ensureAttachmentsLoaded(true);
  await props.refreshFunction();
};

const uploadOrderAttachmentFile = async (file) => {
  try {
    const base64File = await readAttachmentFileAsBase64(file);
    const response = await SessionUser.objects.orders.functions.uploadAttachment(props.order.id, file.name, base64File);

    if (!response) {
      throw new Error("Attachment upload failed");
    }

    await refreshAfterMutation();
  } catch (error) {
    console.error("Error uploading order attachment:", error);
    Swal.fire({
      title: t("common.error"),
      text: t("admin.pos.attachments_upload_error"),
      icon: "error",
    });
  }
};

const openOrderAttachmentFilePicker = () => {
  const fileInput = document.createElement("input");
  fileInput.type = "file";
  fileInput.accept = acceptedOrderAttachmentFileTypes;
  fileInput.onchange = async (event) => {
    const target = event.target;
    if (target instanceof HTMLInputElement && target.files && target.files[0]) {
      await uploadOrderAttachmentFile(target.files[0]);
    }
  };
  fileInput.click();
};

const showAddOrderAttachmentsForm = () => {
  return SessionUser.objects.orders.functions.showAttachWashCertificateForm(props.order.id, async () => {
    await refreshAfterMutation();
  });
};

const hasCachedPreviewSource = (attachmentId) => {
  return Object.prototype.hasOwnProperty.call(previewSourcesById.value, attachmentId);
};

const createSafePreviewBlob = (fileBlob, previewKind) => {
  const previewBlobTypes = safePreviewBlobTypesByKind[previewKind];
  if (!previewBlobTypes) {
    return null;
  }

  const normalizedBlobType = String(fileBlob.type || "").toLowerCase();
  const safeBlobType = previewBlobTypes.allowed.has(normalizedBlobType)
    ? normalizedBlobType
    : previewBlobTypes.fallback;

  return new Blob([fileBlob], { type: safeBlobType });
};

const createEmbeddablePreviewUrl = async (downloadLink, previewKind) => {
  if (!downloadLink) {
    return null;
  }

  try {
    const response = await fetch(downloadLink, { method: "GET" });
    if (!response.ok) {
      return null;
    }

    const fileBlob = await response.blob();
    if (!fileBlob || fileBlob.size === 0) {
      return null;
    }

    const safePreviewBlob = createSafePreviewBlob(fileBlob, previewKind);
    if (!safePreviewBlob) {
      return null;
    }

    const objectUrl = URL.createObjectURL(safePreviewBlob);
    generatedObjectUrls.add(objectUrl);
    return objectUrl;
  } catch (error) {
    console.warn("Unable to create embeddable preview blob", error);
    return null;
  }
};

const ensurePreviewSource = async (attachment) => {
  if (!props.order?.id || !attachment) {
    return null;
  }

  const previewKind = getAttachmentPreviewKind(attachment);
  if (!["image", "document"].includes(previewKind)) {
    return null;
  }

  if (hasCachedPreviewSource(attachment.id) || previewRequestsInFlight.has(attachment.id)) {
    return previewSourcesById.value[attachment.id] ?? null;
  }

  previewRequestsInFlight.add(attachment.id);
  previewLoadingAttachmentId.value = attachment.id;

  try {
    const downloadLink = await SessionUser.objects.orders.functions.downloadAttachment(
      props.order.id,
      attachment.id,
      false
    );
    const previewSource = await createEmbeddablePreviewUrl(downloadLink, previewKind);
    previewSourcesById.value = {
      ...previewSourcesById.value,
      [attachment.id]: previewSource,
    };
    return previewSource;
  } catch (error) {
    console.warn("Unable to load attachment preview", attachment.id, error);
    previewSourcesById.value = {
      ...previewSourcesById.value,
      [attachment.id]: null,
    };
    return null;
  } finally {
    previewRequestsInFlight.delete(attachment.id);
    if (previewLoadingAttachmentId.value === attachment.id) {
      previewLoadingAttachmentId.value = null;
    }
  }
};

const onAttachmentHover = async (attachment) => {
  activePreviewAttachmentId.value = attachment.id;
  await ensurePreviewSource(attachment);
};

const downloadOrderAttachment = async (attachment) => {
  const downloadLink = await SessionUser.objects.orders.functions.downloadAttachment(
    props.order.id,
    attachment.id,
    false
  );
  if (!downloadLink) {
    return;
  }

  const link = document.createElement("a");
  link.href = downloadLink;
  link.target = "_blank";
  link.rel = "noopener noreferrer";
  link.download = getAttachmentLabel(attachment);
  document.body.appendChild(link);
  link.click();
  link.remove();
};

const toggleDropdown = async () => {
  if (isDropdownOpen.value) {
    closeDropdown();
    return;
  }

  isDropdownOpen.value = true;

  if (hasAttachmentIndicator.value) {
    await ensureAttachmentsLoaded();
  }
};

const __returned__ = { acceptedOrderAttachmentFileTypes, imageExtensions, officeExtensions, safePreviewBlobTypesByKind, props, t, dropdownRoot, isDropdownOpen, attachments, attachmentsLoaded, isLoadingAttachments, activePreviewAttachmentId, previewLoadingAttachmentId, previewSourcesById, previewRequestsInFlight, generatedObjectUrls, normalizeAttachments, isObjectUrl, releaseObjectUrl, clearPreviewState, resetAttachmentsFromOrder, canAddOrderAttachments, canAccessOrderAttachments, hasAttachmentIndicator, shouldShowButton, triggerIcon, isTextTriggerButton, triggerButtonClass, activePreviewAttachment, getAttachmentLabel, getAttachmentExtension, getAttachmentPreviewKind, activePreviewKind, activePreviewSource, closeDropdown, onActionSelected, onDocumentClick, onDocumentKeydown, ensureAttachmentsLoaded, readAttachmentFileAsBase64, refreshAfterMutation, uploadOrderAttachmentFile, openOrderAttachmentFilePicker, showAddOrderAttachmentsForm, hasCachedPreviewSource, createSafePreviewBlob, createEmbeddablePreviewUrl, ensurePreviewSource, onAttachmentHover, downloadOrderAttachment, toggleDropdown, computed, onBeforeUnmount, onMounted, ref, watch, get useI18n() { return useI18n }, get Swal() { return Swal }, ActionSettingsWheelItem, ActionSettingsWheelItemLabel, SessionUser };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$f = ["data-testid"];
const _hoisted_2$d = { class: "dropdown-trigger" };
const _hoisted_3$d = ["aria-expanded"];
const _hoisted_4$d = { class: "icon" };
const _hoisted_5$c = {
  class: "dropdown-menu order-attachments-dropdown-menu",
  id: "dropdown-menu",
  role: "menu"
};
const _hoisted_6$c = ["data-testid", "onMouseenter", "onFocusin"];
const _hoisted_7$c = ["data-testid"];
const _hoisted_8$c = { class: "order-attachments-preview-panel__header" };
const _hoisted_9$b = { class: "order-attachments-preview-panel__content" };
const _hoisted_10$a = {
  key: 0,
  class: "order-attachments-preview-panel__text"
};
const _hoisted_11$a = ["src"];
const _hoisted_12$9 = ["src"];
const _hoisted_13$8 = ["href"];
const _hoisted_14$8 = {
  key: 4,
  class: "order-attachments-preview-panel__text"
};
const _hoisted_15$8 = {
  key: 5,
  class: "order-attachments-preview-panel__text"
};
const _hoisted_16$8 = {
  key: 6,
  class: "order-attachments-preview-panel__text"
};

function _sfc_render$f(_ctx, _cache, $props, $setup, $data, $options) {
  return ($setup.shouldShowButton)
    ? (openBlock(), createElementBlock("div", {
        key: 0,
        ref: "dropdownRoot",
        class: normalizeClass(["dropdown is-right", { 'is-active': $setup.isDropdownOpen }]),
        "data-testid": $setup.props.dataTestId
      }, [
        createBaseVNode("div", _hoisted_2$d, [
          createBaseVNode("button", {
            type: "button",
            class: normalizeClass($setup.triggerButtonClass),
            "aria-haspopup": "true",
            "aria-controls": "dropdown-menu",
            "aria-expanded": $setup.isDropdownOpen ? 'true' : 'false',
            onClick: withModifiers($setup.toggleDropdown, ["stop"])
          }, [
            createBaseVNode("span", _hoisted_4$d, [
              createBaseVNode("i", {
                class: normalizeClass($setup.triggerIcon)
              }, null, 2 /* CLASS */)
            ])
          ], 10 /* CLASS, PROPS */, _hoisted_3$d)
        ]),
        createBaseVNode("div", _hoisted_5$c, [
          createBaseVNode("div", {
            class: "dropdown-content",
            onDropdownActionSelected: $setup.onActionSelected
          }, [
            ($setup.canAddOrderAttachments)
              ? (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                  key: 0,
                  label: $setup.t('admin.pos.settings_wheel.attach_wash_certificate'),
                  icon: "fas fa-plus",
                  "click-action": $setup.showAddOrderAttachmentsForm,
                  disabled: false
                }, null, 8 /* PROPS */, ["label"]))
              : createCommentVNode("v-if", true),
            ($setup.canAddOrderAttachments)
              ? (openBlock(), createBlock($setup["ActionSettingsWheelItem"], {
                  key: 1,
                  label: $setup.t('admin.pos.attachments_upload_action'),
                  icon: "fas fa-upload",
                  "click-action": $setup.openOrderAttachmentFilePicker,
                  disabled: false
                }, null, 8 /* PROPS */, ["label"]))
              : createCommentVNode("v-if", true),
            ($setup.attachments.length > 0)
              ? (openBlock(), createElementBlock(Fragment, { key: 2 }, [
                  createVNode($setup["ActionSettingsWheelItemLabel"], {
                    label: $setup.t('admin.pos.settings_wheel.attached_files')
                  }, null, 8 /* PROPS */, ["label"]),
                  (openBlock(true), createElementBlock(Fragment, null, renderList($setup.attachments, (attachment) => {
                    return (openBlock(), createElementBlock("div", {
                      key: attachment.id,
                      class: "order-attachments-previewable-item",
                      "data-testid": `pos-order-list-attachment-item-${$setup.props.order.id}-${attachment.id}`,
                      onMouseenter: $event => ($setup.onAttachmentHover(attachment)),
                      onFocusin: $event => ($setup.onAttachmentHover(attachment))
                    }, [
                      createVNode($setup["ActionSettingsWheelItem"], {
                        label: $setup.getAttachmentLabel(attachment),
                        icon: "fas fa-paperclip",
                        "click-action": () => $setup.downloadOrderAttachment(attachment),
                        disabled: false
                      }, null, 8 /* PROPS */, ["label", "click-action"])
                    ], 40 /* PROPS, NEED_HYDRATION */, _hoisted_6$c))
                  }), 128 /* KEYED_FRAGMENT */))
                ], 64 /* STABLE_FRAGMENT */))
              : createCommentVNode("v-if", true)
          ], 32 /* NEED_HYDRATION */),
          ($setup.activePreviewAttachment)
            ? (openBlock(), createElementBlock("div", {
                key: 0,
                class: "order-attachments-preview-panel",
                "data-testid": `pos-order-list-attachment-preview-${$setup.props.order.id}`
              }, [
                createBaseVNode("div", _hoisted_8$c, toDisplayString($setup.getAttachmentLabel($setup.activePreviewAttachment)), 1 /* TEXT */),
                createBaseVNode("div", _hoisted_9$b, [
                  ($setup.previewLoadingAttachmentId === $setup.activePreviewAttachment.id)
                    ? (openBlock(), createElementBlock("span", _hoisted_10$a, toDisplayString($setup.t("global.loading")), 1 /* TEXT */))
                    : ($setup.activePreviewKind === 'image' && $setup.activePreviewSource)
                      ? (openBlock(), createElementBlock("img", {
                          key: 1,
                          src: $setup.activePreviewSource,
                          alt: "",
                          class: "order-attachments-preview-panel__image"
                        }, null, 8 /* PROPS */, _hoisted_11$a))
                      : ($setup.activePreviewKind === 'document' && $setup.activePreviewSource)
                        ? (openBlock(), createElementBlock("iframe", {
                            key: 2,
                            src: $setup.activePreviewSource,
                            class: "order-attachments-preview-panel__document",
                            title: "Attachment preview",
                            sandbox: ""
                          }, null, 8 /* PROPS */, _hoisted_12$9))
                        : ($setup.activePreviewKind === 'link')
                          ? (openBlock(), createElementBlock("a", {
                              key: 3,
                              href: $setup.activePreviewAttachment.content?.other,
                              target: "_blank",
                              rel: "noopener noreferrer",
                              class: "order-attachments-preview-panel__link"
                            }, toDisplayString($setup.activePreviewAttachment.content?.other), 9 /* TEXT, PROPS */, _hoisted_13$8))
                          : ($setup.activePreviewKind === 'office')
                            ? (openBlock(), createElementBlock("span", _hoisted_14$8, toDisplayString($setup.t("admin.pos.attachments_office_preview_unavailable")), 1 /* TEXT */))
                            : ($setup.activePreviewKind === 'text')
                              ? (openBlock(), createElementBlock("span", _hoisted_15$8, toDisplayString($setup.activePreviewAttachment.content?.other), 1 /* TEXT */))
                              : (openBlock(), createElementBlock("span", _hoisted_16$8, toDisplayString($setup.t("admin.pos.attachments_no_preview")), 1 /* TEXT */))
                ])
              ], 8 /* PROPS */, _hoisted_7$c))
            : createCommentVNode("v-if", true)
        ])
      ], 10 /* CLASS, PROPS */, _hoisted_1$f))
    : createCommentVNode("v-if", true)
}
const OrderAttachmentsActionButton = /*#__PURE__*/_export_sfc(_sfc_main$M, [['render',_sfc_render$f],['__scopeId',"data-v-598238fb"],['__file',"OrderAttachmentsActionButton.vue"]]);

const searchCustomerResults = ref([]);
const searchCustomerPagination = ref([]);
const searchCustomerMeta = ref([]);
const isSearching = ref(false);

const searchCustomer = (search = null, filter = false) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  if (!search) {
    // Reset the search results
    searchCustomerResults.value = [];
    return null;
  }
  // If the filter is set to false, we want to predict the filter
  if (!filter) {
  }
  // Reset the search results
  searchCustomerResults.value = [];
  isSearching.value = true;
  // Search for the customer
  return authenticatedRequest(
      '/customers?search=' + search,
  )
      .then((response) => {
        searchCustomerResults.value = response.data.data;
        searchCustomerPagination.value = response.data.meta.pagination;
        searchCustomerMeta.value = response.data.meta;
        isSearching.value = false;
        return searchCustomerResults.value
      })
      .catch((error) => {
        isSearching.value = false;
        parseError(error);
      });
};

const _sfc_main$L = {};
const customerSearch = /*#__PURE__*/_export_sfc(_sfc_main$L, [['__file',"customerSearch.vue"]]);

const _sfc_main$K = {
  __name: 'AssignDraftOrderCustomerModal',
  props: {
  order: {
    type: Object,
    required: true,
  },
  title: {
    type: String,
    default: null,
  },
  subtitle: {
    type: String,
    default: null,
  },
  submitLabel: {
    type: String,
    default: null,
  },
  errorMessageText: {
    type: String,
    default: null,
  },
  newCollectionName: {
    type: String,
    default: null,
  },
  newCollectionDescription: {
    type: String,
    default: null,
  },
  submitAction: {
    type: Function,
    default: null,
  },
},
  emits: ["close", "assigned"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const props = __props;

const emit = __emit;

const { t } = useI18n();

const customerSearchQuery = ref("");
const selectedCustomer = ref(null);
const invoiceCollections = ref([]);
const selectedInvoiceCollectionId = ref(null);
const recalculatePrices = ref(true);
const isLoadingInvoiceCollections = ref(false);
const isSaving = ref(false);
const isCreatingInvoiceCollection = ref(false);
const errorMessage = ref("");
const invoiceCollectionsContainer = ref(null);
const modalTitle = computed(() => props.title || t("admin.pos.drafts_assignment.title"));
const modalSubtitle = computed(
  () => props.subtitle || t("admin.pos.drafts_assignment.subtitle", { orderId: props.order.id })
);
const modalSubmitLabel = computed(() => props.submitLabel || t("admin.pos.drafts_assignment.submit"));
const assignmentErrorText = computed(() => props.errorMessageText || t("admin.pos.drafts_assignment.error"));
const createdInvoiceCollectionName = computed(
  () => props.newCollectionName || t("admin.pos.drafts_assignment.new_collection_name")
);
const createdInvoiceCollectionDescription = computed(
  () => props.newCollectionDescription || t("admin.pos.drafts_assignment.new_collection_description")
);

const normalizePositiveInteger = (value) => {
  const parsedValue = Number.parseInt(value, 10);
  return Number.isInteger(parsedValue) && parsedValue > 0 ? parsedValue : null;
};

const normalizeNonNegativeInteger = (value) => {
  const parsedValue = Number.parseInt(value, 10);
  return Number.isInteger(parsedValue) && parsedValue >= 0 ? parsedValue : null;
};

const normalizeFiniteNumber = (value) => {
  if (value === null || value === undefined || value === "") {
    return null;
  }

  const parsedValue = Number(value);
  return Number.isFinite(parsedValue) ? parsedValue : null;
};

const normalizeCustomerResult = (customer) => {
  const customerNumber = normalizePositiveInteger(customer?.customerNumber ?? customer?.customer_number);
  if (!customerNumber) {
    return null;
  }

  return {
    customerNumber,
    name: customer?.name ?? customer?.customer_name ?? `#${customerNumber}`,
    address: customer?.address ?? "",
    city: customer?.city ?? "",
  };
};

const buildCustomerLabel = (customer) => {
  if (!customer) {
    return "";
  }

  return `${customer.name} (${customer.customerNumber})`;
};

const formatInvoiceCollectionMeta = (invoiceCollection) => {
  if (!invoiceCollection) {
    return "";
  }

  const meta = [];
  if (invoiceCollection.closed_at) {
    meta.push(`${t("global.closed")}: ${invoiceCollection.closed_at}`);
  } else {
    meta.push(t("common.open"));
  }

  if (invoiceCollection.created_at) {
    meta.push(invoiceCollection.created_at);
  }

  return meta.join(" • ");
};

const getInvoiceCollectionOrderCount = (invoiceCollection) => {
  if (!invoiceCollection) {
    return null;
  }

  const directCount = normalizeNonNegativeInteger(
    invoiceCollection.orders_count
    ?? invoiceCollection.order_count
    ?? invoiceCollection.objects
  );
  if (directCount !== null) {
    return directCount;
  }

  if (Array.isArray(invoiceCollection.orders)) {
    return invoiceCollection.orders.length;
  }

  return normalizeNonNegativeInteger(invoiceCollection.orders);
};

const formatInvoiceCollectionOrderCount = (invoiceCollection) => {
  const orderCount = getInvoiceCollectionOrderCount(invoiceCollection);
  return orderCount === null ? t("global.no_data") : orderCount;
};

const getInvoiceCollectionTotalNetAmount = (invoiceCollection) => {
  if (!invoiceCollection) {
    return null;
  }

  return normalizeFiniteNumber(
    invoiceCollection.total_net_amount
    ?? invoiceCollection.total
    ?? invoiceCollection.net_total_amount
  );
};

const formatInvoiceCollectionTotalNetAmount = (invoiceCollection) => {
  const totalNetAmount = getInvoiceCollectionTotalNetAmount(invoiceCollection);
  return totalNetAmount === null
    ? t("global.no_data")
    : SessionUser.functions.currency.toLocal(totalNetAmount);
};

const sortedInvoiceCollections = computed(() => {
  return [...invoiceCollections.value].sort((left, right) => {
    const leftIsOpen = left?.closed_at === null;
    const rightIsOpen = right?.closed_at === null;
    if (leftIsOpen !== rightIsOpen) {
      return leftIsOpen ? -1 : 1;
    }

    return normalizePositiveInteger(right?.id) - normalizePositiveInteger(left?.id);
  });
});

const hasInvoiceCollection = (invoiceCollectionId) => {
  const normalizedInvoiceCollectionId = normalizePositiveInteger(invoiceCollectionId);
  if (!normalizedInvoiceCollectionId) {
    return false;
  }

  return invoiceCollections.value.some(
    (invoiceCollection) => normalizePositiveInteger(invoiceCollection?.id) === normalizedInvoiceCollectionId
  );
};

const buildCreatedInvoiceCollectionFallback = (invoiceCollection) => {
  const createdInvoiceCollectionId = normalizePositiveInteger(invoiceCollection?.id);
  if (!createdInvoiceCollectionId) {
    return null;
  }

  return {
    id: createdInvoiceCollectionId,
    customer_number: normalizePositiveInteger(invoiceCollection?.customer_number)
      ?? normalizePositiveInteger(selectedCustomer.value?.customerNumber),
    customer_name: invoiceCollection?.customer_name ?? selectedCustomer.value?.name ?? `#${createdInvoiceCollectionId}`,
    created_at: invoiceCollection?.created_at ?? null,
    closed_at: invoiceCollection?.closed_at ?? null,
    total_net_amount: getInvoiceCollectionTotalNetAmount(invoiceCollection) ?? 0,
    orders: getInvoiceCollectionOrderCount(invoiceCollection) ?? 0,
    ...invoiceCollection,
  };
};

const scrollInvoiceCollectionIntoView = async (invoiceCollectionId) => {
  const normalizedInvoiceCollectionId = normalizePositiveInteger(invoiceCollectionId);
  if (!normalizedInvoiceCollectionId) {
    return;
  }

  await nextTick();

  const invoiceCollectionOption = invoiceCollectionsContainer.value?.querySelector(
    `[data-testid="draft-order-invoice-collection-option-${normalizedInvoiceCollectionId}"]`
  );

  if (invoiceCollectionOption instanceof HTMLElement) {
    invoiceCollectionOption.scrollIntoView({
      block: "start",
      inline: "nearest",
    });
  }
};

const canSubmit = computed(() => {
  return Boolean(selectedCustomer.value && selectedInvoiceCollectionId.value && !isSaving.value);
});

const closeModal = () => {
  if (isSaving.value) {
    return;
  }

  emit("close");
};

const resetInvoiceCollectionSelection = () => {
  invoiceCollections.value = [];
  selectedInvoiceCollectionId.value = null;
};

const onCustomerSearchInput = async () => {
  errorMessage.value = "";

  if (
    selectedCustomer.value
    && customerSearchQuery.value.trim() !== buildCustomerLabel(selectedCustomer.value)
  ) {
    selectedCustomer.value = null;
    resetInvoiceCollectionSelection();
  }

  const query = customerSearchQuery.value.trim();
  if (!query) {
    searchCustomer(null);
    return;
  }

  await searchCustomer(query);
};

const loadInvoiceCollections = async (preferredInvoiceCollectionId = null) => {
  const customerNumber = normalizePositiveInteger(selectedCustomer.value?.customerNumber);
  if (!customerNumber) {
    resetInvoiceCollectionSelection();
    return;
  }

  isLoadingInvoiceCollections.value = true;
  errorMessage.value = "";

  try {
    const response = await authenticatedRequest("/collected-invoices", "GET", {
      page: 1,
      limit: 100,
      order: "closed_at:asc",
      filters: `customer_number:${customerNumber},booked_invoice_id:is_null`,
    });

    const resolvedCollections = Array.isArray(response?.data?.data) ? response.data.data : [];
    invoiceCollections.value = resolvedCollections;

    const preferredId = normalizePositiveInteger(preferredInvoiceCollectionId);
    const currentOrderCollectionId = normalizePositiveInteger(props.order?.invoice_collection_id);
    const matchingCurrentCollection = currentOrderCollectionId
      ? resolvedCollections.find((collection) => normalizePositiveInteger(collection?.id) === currentOrderCollectionId)
      : null;
    const firstOpenCollection = resolvedCollections.find((collection) => collection?.closed_at === null);

    selectedInvoiceCollectionId.value = preferredId
      ?? normalizePositiveInteger(matchingCurrentCollection?.id)
      ?? normalizePositiveInteger(firstOpenCollection?.id)
      ?? normalizePositiveInteger(resolvedCollections[0]?.id);
  } catch (error) {
    invoiceCollections.value = [];
    selectedInvoiceCollectionId.value = null;
    errorMessage.value = SessionUser.functions.parseErrorMessage(error) || t("admin.pos.drafts_assignment.error");
  } finally {
    isLoadingInvoiceCollections.value = false;
  }
};

const selectCustomer = async (customer) => {
  const normalizedCustomer = normalizeCustomerResult(customer);
  if (!normalizedCustomer) {
    return;
  }

  selectedCustomer.value = normalizedCustomer;
  customerSearchQuery.value = buildCustomerLabel(normalizedCustomer);
  searchCustomer(null);
  await loadInvoiceCollections();
};

const createInvoiceCollection = async () => {
  const customerNumber = normalizePositiveInteger(selectedCustomer.value?.customerNumber);
  if (!customerNumber || isCreatingInvoiceCollection.value) {
    return;
  }

  isCreatingInvoiceCollection.value = true;
  errorMessage.value = "";

  try {
    const response = await SessionUser.objects.collectedOrderInvoices.add(
      customerNumber,
      createdInvoiceCollectionName.value,
      createdInvoiceCollectionDescription.value,
      null
    );

    const createdInvoiceCollection = buildCreatedInvoiceCollectionFallback(response?.data?.data ?? response?.data);
    const createdInvoiceCollectionId = normalizePositiveInteger(createdInvoiceCollection?.id);
    await loadInvoiceCollections(createdInvoiceCollectionId);

    if (createdInvoiceCollectionId && createdInvoiceCollection && !hasInvoiceCollection(createdInvoiceCollectionId)) {
      invoiceCollections.value = [createdInvoiceCollection, ...invoiceCollections.value];
    }

    if (createdInvoiceCollectionId) {
      selectedInvoiceCollectionId.value = createdInvoiceCollectionId;
      await scrollInvoiceCollectionIntoView(createdInvoiceCollectionId);
    }
  } catch (error) {
    errorMessage.value = SessionUser.functions.parseErrorMessage(error) || assignmentErrorText.value;
  } finally {
    isCreatingInvoiceCollection.value = false;
  }
};

const submitAssignment = async () => {
  if (!canSubmit.value) {
    return;
  }

  isSaving.value = true;
  errorMessage.value = "";

  try {
    const submitAction = props.submitAction || SessionUser.objects.orders.functions.assignDraftCustomer;
    const response = await submitAction({
      order_id: normalizePositiveInteger(props.order?.id),
      customer_id: normalizePositiveInteger(selectedCustomer.value?.customerNumber),
      invoice_collection_id: normalizePositiveInteger(selectedInvoiceCollectionId.value),
      department_id: normalizePositiveInteger(props.order?.department_id),
      recalculate_prices: recalculatePrices.value,
    });

    emit("assigned", response);
  } catch (error) {
    errorMessage.value = SessionUser.functions.parseErrorMessage(error) || assignmentErrorText.value;
  } finally {
    isSaving.value = false;
  }
};

onBeforeUnmount(() => {
  searchCustomer(null);
});

const __returned__ = { props, emit, t, customerSearchQuery, selectedCustomer, invoiceCollections, selectedInvoiceCollectionId, recalculatePrices, isLoadingInvoiceCollections, isSaving, isCreatingInvoiceCollection, errorMessage, invoiceCollectionsContainer, modalTitle, modalSubtitle, modalSubmitLabel, assignmentErrorText, createdInvoiceCollectionName, createdInvoiceCollectionDescription, normalizePositiveInteger, normalizeNonNegativeInteger, normalizeFiniteNumber, normalizeCustomerResult, buildCustomerLabel, formatInvoiceCollectionMeta, getInvoiceCollectionOrderCount, formatInvoiceCollectionOrderCount, getInvoiceCollectionTotalNetAmount, formatInvoiceCollectionTotalNetAmount, sortedInvoiceCollections, hasInvoiceCollection, buildCreatedInvoiceCollectionFallback, scrollInvoiceCollectionIntoView, canSubmit, closeModal, resetInvoiceCollectionSelection, onCustomerSearchInput, loadInvoiceCollections, selectCustomer, createInvoiceCollection, submitAssignment, computed, nextTick, onBeforeUnmount, ref, get useI18n() { return useI18n }, authenticatedRequest, searchCustomer, searchCustomerResults, isSearching, SessionUser };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$e = {
  class: "modal is-active",
  "data-testid": "draft-order-assign-customer-modal"
};
const _hoisted_2$c = { class: "modal-card draft-order-assign-modal" };
const _hoisted_3$c = { class: "modal-card-head draft-order-assign-header" };
const _hoisted_4$c = { class: "draft-order-assign-heading" };
const _hoisted_5$b = {
  class: "modal-card-title",
  "data-testid": "draft-order-assign-title"
};
const _hoisted_6$b = { class: "is-size-7 has-text-grey mt-2" };
const _hoisted_7$b = { class: "modal-card-body" };
const _hoisted_8$b = {
  key: 0,
  class: "notification is-danger is-light mb-4",
  "data-testid": "draft-order-assign-error"
};
const _hoisted_9$a = { class: "field" };
const _hoisted_10$9 = {
  class: "label",
  for: "draft-order-assign-customer-search"
};
const _hoisted_11$9 = { class: "control has-icons-left" };
const _hoisted_12$8 = ["placeholder"];
const _hoisted_13$7 = {
  key: 1,
  class: "draft-order-assign-selected-customer mb-4",
  "data-testid": "draft-order-selected-customer"
};
const _hoisted_14$7 = { class: "is-flex is-justify-content-space-between is-align-items-start" };
const _hoisted_15$7 = { class: "has-text-weight-semibold" };
const _hoisted_16$7 = { class: "is-size-7 has-text-grey" };
const _hoisted_17$6 = { key: 0 };
const _hoisted_18$6 = { class: "tag is-link is-light" };
const _hoisted_19$5 = {
  key: 2,
  class: "draft-order-assign-search-results mb-5",
  "data-testid": "draft-order-customer-results"
};
const _hoisted_20$4 = ["data-testid", "onClick"];
const _hoisted_21$4 = { class: "is-block has-text-grey" };
const _hoisted_22$4 = {
  key: 3,
  class: "notification is-light mb-5"
};
const _hoisted_23$4 = { class: "field" };
const _hoisted_24$4 = { class: "label" };
const _hoisted_25$4 = {
  key: 0,
  class: "notification is-light"
};
const _hoisted_26$4 = {
  key: 1,
  class: "notification is-light"
};
const _hoisted_27$4 = {
  key: 2,
  class: "notification is-warning is-light"
};
const _hoisted_28$4 = ["disabled"];
const _hoisted_29$3 = {
  key: 3,
  ref: "invoiceCollectionsContainer",
  class: "draft-order-assign-collections",
  "data-testid": "draft-order-invoice-collection-list"
};
const _hoisted_30$3 = ["data-testid", "onClick"];
const _hoisted_31$3 = { class: "has-text-left" };
const _hoisted_32$3 = { class: "is-block has-text-grey" };
const _hoisted_33$3 = ["data-testid"];
const _hoisted_34$3 = { class: "draft-order-assign-collection-metric" };
const _hoisted_35$3 = { class: "draft-order-assign-collection-metric-label" };
const _hoisted_36$2 = { class: "draft-order-assign-collection-metric-value" };
const _hoisted_37$2 = { class: "draft-order-assign-collection-metric" };
const _hoisted_38$2 = { class: "draft-order-assign-collection-metric-label" };
const _hoisted_39$2 = { class: "draft-order-assign-collection-metric-value" };
const _hoisted_40$2 = { class: "is-flex is-justify-content-flex-end mt-3" };
const _hoisted_41$2 = ["disabled"];
const _hoisted_42$2 = { class: "draft-order-assign-switch mt-5" };
const _hoisted_43$2 = {
  class: "switch-label",
  for: "draft-order-recalculate-prices"
};
const _hoisted_44$2 = { class: "is-block has-text-grey" };
const _hoisted_45$2 = { class: "switch-control" };
const _hoisted_46$2 = { class: "modal-card-foot is-justify-content-flex-end draft-order-assign-footer" };
const _hoisted_47$2 = ["disabled"];
const _hoisted_48$2 = ["disabled"];

function _sfc_render$e(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$e, [
    createBaseVNode("div", {
      class: "modal-background",
      onClick: $setup.closeModal
    }),
    createBaseVNode("div", _hoisted_2$c, [
      createBaseVNode("header", _hoisted_3$c, [
        createBaseVNode("div", _hoisted_4$c, [
          createBaseVNode("p", _hoisted_5$b, toDisplayString($setup.modalTitle), 1 /* TEXT */),
          createBaseVNode("p", _hoisted_6$b, toDisplayString($setup.modalSubtitle), 1 /* TEXT */)
        ]),
        createBaseVNode("button", {
          class: "delete draft-order-assign-close",
          "aria-label": "close",
          "data-testid": "draft-order-assign-close",
          onClick: $setup.closeModal
        })
      ]),
      createBaseVNode("section", _hoisted_7$b, [
        ($setup.errorMessage)
          ? (openBlock(), createElementBlock("div", _hoisted_8$b, toDisplayString($setup.errorMessage), 1 /* TEXT */))
          : createCommentVNode("v-if", true),
        createBaseVNode("div", _hoisted_9$a, [
          createBaseVNode("label", _hoisted_10$9, toDisplayString($setup.t("admin.pos.drafts_assignment.search_customer_label")), 1 /* TEXT */),
          createBaseVNode("div", _hoisted_11$9, [
            withDirectives(createBaseVNode("input", {
              id: "draft-order-assign-customer-search",
              "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (($setup.customerSearchQuery) = $event)),
              class: "input",
              type: "text",
              placeholder: $setup.t('admin.pos.drafts_assignment.search_customer_placeholder'),
              "data-testid": "draft-order-assign-customer-search",
              onInput: $setup.onCustomerSearchInput
            }, null, 40 /* PROPS, NEED_HYDRATION */, _hoisted_12$8), [
              [vModelText, $setup.customerSearchQuery]
            ]),
            _cache[2] || (_cache[2] = createBaseVNode("span", { class: "icon is-left" }, [
              createBaseVNode("i", { class: "fas fa-search" })
            ], -1 /* CACHED */))
          ])
        ]),
        ($setup.selectedCustomer)
          ? (openBlock(), createElementBlock("div", _hoisted_13$7, [
              createBaseVNode("div", _hoisted_14$7, [
                createBaseVNode("div", null, [
                  createBaseVNode("p", _hoisted_15$7, toDisplayString($setup.t("admin.pos.drafts_assignment.selected_customer")), 1 /* TEXT */),
                  createBaseVNode("p", null, toDisplayString($setup.selectedCustomer.name), 1 /* TEXT */),
                  createBaseVNode("p", _hoisted_16$7, [
                    createTextVNode(" #" + toDisplayString($setup.selectedCustomer.customerNumber) + " ", 1 /* TEXT */),
                    ($setup.selectedCustomer.city)
                      ? (openBlock(), createElementBlock("span", _hoisted_17$6, " • " + toDisplayString($setup.selectedCustomer.city), 1 /* TEXT */))
                      : createCommentVNode("v-if", true)
                  ])
                ]),
                createBaseVNode("span", _hoisted_18$6, "#" + toDisplayString($setup.selectedCustomer.customerNumber), 1 /* TEXT */)
              ])
            ]))
          : createCommentVNode("v-if", true),
        ($setup.customerSearchQuery.trim() && $setup.searchCustomerResults.length > 0)
          ? (openBlock(), createElementBlock("div", _hoisted_19$5, [
              (openBlock(true), createElementBlock(Fragment, null, renderList($setup.searchCustomerResults, (customer) => {
                return (openBlock(), createElementBlock("button", {
                  key: customer.customerNumber || customer.customer_number,
                  type: "button",
                  class: "button is-fullwidth is-justify-content-flex-start draft-order-assign-search-result",
                  "data-testid": `draft-order-customer-option-${customer.customerNumber || customer.customer_number}`,
                  onClick: $event => ($setup.selectCustomer(customer))
                }, [
                  _cache[3] || (_cache[3] = createBaseVNode("span", { class: "icon mr-2" }, [
                    createBaseVNode("i", { class: "fas fa-user" })
                  ], -1 /* CACHED */)),
                  createBaseVNode("span", null, [
                    createBaseVNode("strong", null, toDisplayString(customer.name || customer.customer_name), 1 /* TEXT */),
                    createBaseVNode("small", _hoisted_21$4, " #" + toDisplayString(customer.customerNumber || customer.customer_number), 1 /* TEXT */)
                  ])
                ], 8 /* PROPS */, _hoisted_20$4))
              }), 128 /* KEYED_FRAGMENT */))
            ]))
          : ($setup.customerSearchQuery.trim() && !$setup.isSearching && !$setup.selectedCustomer)
            ? (openBlock(), createElementBlock("div", _hoisted_22$4, toDisplayString($setup.t("global.no_data")), 1 /* TEXT */))
            : createCommentVNode("v-if", true),
        createBaseVNode("div", _hoisted_23$4, [
          createBaseVNode("label", _hoisted_24$4, toDisplayString($setup.t("admin.pos.drafts_assignment.invoice_collection_label")), 1 /* TEXT */),
          (!$setup.selectedCustomer)
            ? (openBlock(), createElementBlock("div", _hoisted_25$4, toDisplayString($setup.t("admin.pos.drafts_assignment.customer_required")), 1 /* TEXT */))
            : ($setup.isLoadingInvoiceCollections)
              ? (openBlock(), createElementBlock("div", _hoisted_26$4, toDisplayString($setup.t("admin.pos.drafts_assignment.invoice_collection_loading")), 1 /* TEXT */))
              : ($setup.sortedInvoiceCollections.length === 0)
                ? (openBlock(), createElementBlock("div", _hoisted_27$4, [
                    createBaseVNode("p", null, toDisplayString($setup.t("admin.pos.drafts_assignment.invoice_collection_empty")), 1 /* TEXT */),
                    createBaseVNode("button", {
                      type: "button",
                      class: "button is-small is-warning is-light mt-3",
                      disabled: $setup.isCreatingInvoiceCollection,
                      "data-testid": "draft-order-create-invoice-collection",
                      onClick: $setup.createInvoiceCollection
                    }, [
                      _cache[4] || (_cache[4] = createBaseVNode("span", { class: "icon" }, [
                        createBaseVNode("i", { class: "fas fa-plus" })
                      ], -1 /* CACHED */)),
                      createBaseVNode("span", null, toDisplayString($setup.t("admin.pos.drafts_assignment.create_invoice_collection")), 1 /* TEXT */)
                    ], 8 /* PROPS */, _hoisted_28$4)
                  ]))
                : (openBlock(), createElementBlock("div", _hoisted_29$3, [
                    (openBlock(true), createElementBlock(Fragment, null, renderList($setup.sortedInvoiceCollections, (invoiceCollection) => {
                      return (openBlock(), createElementBlock("button", {
                        key: invoiceCollection.id,
                        type: "button",
                        class: normalizeClass(["button is-fullwidth is-justify-content-space-between draft-order-assign-collection", { 'is-link is-light is-selected': $setup.selectedInvoiceCollectionId === $setup.normalizePositiveInteger(invoiceCollection.id) }]),
                        "data-testid": `draft-order-invoice-collection-option-${invoiceCollection.id}`,
                        onClick: $event => ($setup.selectedInvoiceCollectionId = $setup.normalizePositiveInteger(invoiceCollection.id))
                      }, [
                        createBaseVNode("span", _hoisted_31$3, [
                          createBaseVNode("strong", null, "#" + toDisplayString(invoiceCollection.id), 1 /* TEXT */),
                          createBaseVNode("small", _hoisted_32$3, toDisplayString($setup.formatInvoiceCollectionMeta(invoiceCollection)), 1 /* TEXT */),
                          createBaseVNode("small", {
                            class: "has-text-grey draft-order-assign-collection-summary",
                            "data-testid": `draft-order-invoice-collection-summary-${invoiceCollection.id}`
                          }, [
                            createBaseVNode("span", _hoisted_34$3, [
                              createBaseVNode("span", _hoisted_35$3, toDisplayString($setup.t("admin.pos.drafts_assignment.invoice_collection_orders")), 1 /* TEXT */),
                              createBaseVNode("strong", _hoisted_36$2, toDisplayString($setup.formatInvoiceCollectionOrderCount(invoiceCollection)), 1 /* TEXT */)
                            ]),
                            createBaseVNode("span", _hoisted_37$2, [
                              createBaseVNode("span", _hoisted_38$2, toDisplayString($setup.t("admin.pos.drafts_assignment.invoice_collection_total")), 1 /* TEXT */),
                              createBaseVNode("strong", _hoisted_39$2, toDisplayString($setup.formatInvoiceCollectionTotalNetAmount(invoiceCollection)), 1 /* TEXT */)
                            ])
                          ], 8 /* PROPS */, _hoisted_33$3)
                        ]),
                        createBaseVNode("span", {
                          class: normalizeClass(["tag", invoiceCollection.closed_at ? 'is-light' : 'is-success is-light'])
                        }, toDisplayString(invoiceCollection.closed_at ? $setup.t("global.closed") : $setup.t("common.open")), 3 /* TEXT, CLASS */)
                      ], 10 /* CLASS, PROPS */, _hoisted_30$3))
                    }), 128 /* KEYED_FRAGMENT */)),
                    createBaseVNode("div", _hoisted_40$2, [
                      createBaseVNode("button", {
                        type: "button",
                        class: "button is-small is-light",
                        disabled: $setup.isCreatingInvoiceCollection,
                        "data-testid": "draft-order-create-invoice-collection",
                        onClick: $setup.createInvoiceCollection
                      }, [
                        _cache[5] || (_cache[5] = createBaseVNode("span", { class: "icon" }, [
                          createBaseVNode("i", { class: "fas fa-plus" })
                        ], -1 /* CACHED */)),
                        createBaseVNode("span", null, toDisplayString($setup.t("admin.pos.drafts_assignment.create_invoice_collection")), 1 /* TEXT */)
                      ], 8 /* PROPS */, _hoisted_41$2)
                    ])
                  ], 512 /* NEED_PATCH */))
        ]),
        createBaseVNode("div", _hoisted_42$2, [
          createBaseVNode("label", _hoisted_43$2, [
            createBaseVNode("span", null, [
              createBaseVNode("strong", null, toDisplayString($setup.t("admin.pos.drafts_assignment.recalculate_prices")), 1 /* TEXT */),
              createBaseVNode("small", _hoisted_44$2, toDisplayString($setup.t("admin.pos.drafts_assignment.recalculate_prices_help")), 1 /* TEXT */)
            ]),
            createBaseVNode("span", _hoisted_45$2, [
              withDirectives(createBaseVNode("input", {
                id: "draft-order-recalculate-prices",
                "onUpdate:modelValue": _cache[1] || (_cache[1] = $event => (($setup.recalculatePrices) = $event)),
                class: "switch is-rounded is-success",
                type: "checkbox",
                "data-testid": "draft-order-recalculate-prices"
              }, null, 512 /* NEED_PATCH */), [
                [vModelCheckbox, $setup.recalculatePrices]
              ]),
              _cache[6] || (_cache[6] = createBaseVNode("label", { for: "draft-order-recalculate-prices" }, null, -1 /* CACHED */))
            ])
          ])
        ])
      ]),
      createBaseVNode("footer", _hoisted_46$2, [
        createBaseVNode("button", {
          class: "button is-light",
          disabled: $setup.isSaving,
          "data-testid": "draft-order-assign-cancel",
          onClick: $setup.closeModal
        }, toDisplayString($setup.t("common.cancel")), 9 /* TEXT, PROPS */, _hoisted_47$2),
        createBaseVNode("button", {
          class: normalizeClass(["button is-link", { 'is-loading': $setup.isSaving }]),
          disabled: !$setup.canSubmit,
          "data-testid": "draft-order-assign-submit",
          onClick: $setup.submitAssignment
        }, [
          _cache[7] || (_cache[7] = createBaseVNode("span", { class: "icon" }, [
            createBaseVNode("i", { class: "fas fa-user-check" })
          ], -1 /* CACHED */)),
          createBaseVNode("span", null, toDisplayString($setup.modalSubmitLabel), 1 /* TEXT */)
        ], 10 /* CLASS, PROPS */, _hoisted_48$2)
      ])
    ])
  ]))
}
const AssignDraftOrderCustomerModal = /*#__PURE__*/_export_sfc(_sfc_main$K, [['render',_sfc_render$e],['__scopeId',"data-v-ba5893cf"],['__file',"AssignDraftOrderCustomerModal.vue"]]);

const LARGE_TABLE_HEADERS_STORAGE_KEY = "pleno.useLargeTableHeaders";
const LARGE_TABLE_HEADERS_BODY_CLASS = "pleno-large-table-headers";

const applyLargeTableHeadersClass = (value) => {
  if (typeof document === "undefined" || !document.body) {
    return;
  }

  document.body.classList.toggle(LARGE_TABLE_HEADERS_BODY_CLASS, Boolean(value));
};

const readStoredBoolean = () => {
  if (typeof window === "undefined" || !window.localStorage) {
    return false;
  }

  try {
    return window.localStorage.getItem(LARGE_TABLE_HEADERS_STORAGE_KEY) === "true";
  } catch {
    return false;
  }
};

const useLargeTableHeaders = ref(readStoredBoolean());
applyLargeTableHeadersClass(useLargeTableHeaders.value);

const setUseLargeTableHeaders = (value) => {
  const nextValue = Boolean(value);
  useLargeTableHeaders.value = nextValue;
  applyLargeTableHeadersClass(nextValue);

  if (typeof window === "undefined" || !window.localStorage) {
    return;
  }

  try {
    window.localStorage.setItem(LARGE_TABLE_HEADERS_STORAGE_KEY, nextValue ? "true" : "false");
  } catch {
    // Storage is optional; keep the in-memory preference for this session.
  }
};

if (typeof window !== "undefined") {
  window.addEventListener("storage", (event) => {
    if (event.key === LARGE_TABLE_HEADERS_STORAGE_KEY) {
      useLargeTableHeaders.value = event.newValue === "true";
      applyLargeTableHeadersClass(useLargeTableHeaders.value);
    }
  });
}

const _sfc_main$J = {
  __name: 'OrderContentTable',
  props: {
  orderId: {
    type: Number,
    required: true,
  },
  displayPrice: {
    type: Boolean,
    default: true,
  },
  displayReference: {
    type: Boolean,
    default: true,
  },
  displayNotes: {
    type: Boolean,
    default: true,
  },
  useLocalOrderItems: {
    type: Boolean,
    default: false,
  },
  localOrderItems: {
    type: Array,
    default: () => [],
  },
  summaryMode: {
    type: Boolean,
    default: false,
  },
  invoicePeriodFlags: {
    type: Array,
    default: () => [],
  },
},
  emits: ["flagStatusChanged"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const { t } = useI18n();

const props = __props;
const emit = __emit;

const order_item_default = {
  "id": null,
  "order_id": null,
  "product_id": null,
  "reference": null,
  "notes": null,
  "cashier_id": null,
  "price": null,
  "quantity": null,
  "related_item_id": null,
  "product": {
    "id": null,
    "name": null,
    "description": null,
    "price": null,
    "category": null,
    "piktogram": null,
    "economic_product_id": null,
    "apply_category_discount": null,
    "requires_note": null,
    "created_at": null,
    "updated_at": null
  }
};

const orderItems = ref([]);

const loadOrderItems = async () => {
  if (props.useLocalOrderItems) {
    orderItems.value = props.localOrderItems;
    return;
  }
  await SessionUser.request(
      '/order/items',
      'GET',
      {
        order_id: props.orderId,
      }
  ).then((response) => {
    orderItems.value = response.data.data;
  }).catch((error) => {
    console.error(error);
  });
};

const isOrderItemAddon = (item) => {
  return item.related_item_id !== 0;
};

const getItemAddons = (item) => {
  return orderItems.value.filter((order_item) => {
    return order_item.related_item_id === item.id;
  });
};

const ucFirst = (str) => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

const sortInvoicePeriodFlags = (flags = []) => [...flags].sort((left, right) => {
  const sourceOrder = { manual: 0, automatic: 1 };
  const leftSource = sourceOrder[left?.source] ?? 99;
  const rightSource = sourceOrder[right?.source] ?? 99;
  if (leftSource !== rightSource) {
    return leftSource - rightSource;
  }

  return String(left?.created_at || left?.fingerprint || "").localeCompare(
    String(right?.created_at || right?.fingerprint || "")
  );
});

const getOrderItemFlags = (orderItem) => sortInvoicePeriodFlags((props.invoicePeriodFlags || []).filter((flag) => {
  if (String(flag?.status || "active") !== "active") {
    return false;
  }

  const targetType = String(flag?.target_type || "");
  if (!["order_item", "order_item_field"].includes(targetType)) {
    return false;
  }

  const flagOrderItemId = Number(flag?.order_item_id || flag?.target_id || flag?.context?.order_item_id || 0);
  return flagOrderItemId > 0 && flagOrderItemId === Number(orderItem?.id || 0);
}));

const getOrderItemFlagIconClass = (orderItem) => (
  getOrderItemFlags(orderItem).length > 0 ? "fas fa-flag" : ""
);

const getOrderItemFlagColorClass = (orderItem) => {
  const flags = getOrderItemFlags(orderItem);
  if (flags.length === 0) {
    return "";
  }

  return flags.some((flag) => flag?.source === "manual") ? "has-text-danger" : "has-text-warning";
};

const displayColumnCount = computed(() => (
  2 + (props.displayNotes ? 1 : 0) + (props.displayReference ? 1 : 0) + (props.displayPrice ? 1 : 0)
));

const emitFlagStatusChanged = (flag) => emit("flagStatusChanged", flag);

loadOrderItems();

watch(() => props.orderId, (newValue, oldValue) => {
  if (newValue !== oldValue) {
    loadOrderItems();
  }
}, { immediate: true });

const __returned__ = { t, props, emit, order_item_default, orderItems, loadOrderItems, isOrderItemAddon, getItemAddons, ucFirst, sortInvoicePeriodFlags, getOrderItemFlags, getOrderItemFlagIconClass, getOrderItemFlagColorClass, displayColumnCount, emitFlagStatusChanged, get useI18n() { return useI18n }, computed, ref, watch, SessionUser, InvoicingPeriodFlagList };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$d = {
  key: 0,
  class: "table is-fullwidth"
};
const _hoisted_2$b = { key: 0 };
const _hoisted_3$b = { key: 1 };
const _hoisted_4$b = { key: 2 };
const _hoisted_5$a = { key: 0 };
const _hoisted_6$a = ["data-testid"];
const _hoisted_7$a = { key: 0 };
const _hoisted_8$a = { key: 1 };
const _hoisted_9$9 = { key: 2 };
const _hoisted_10$8 = { class: "has-background-warning-light" };
const _hoisted_11$8 = ["data-testid"];
const _hoisted_12$7 = { style: {"text-decoration":"line-through"} };
const _hoisted_13$6 = { key: 0 };
const _hoisted_14$6 = { key: 1 };
const _hoisted_15$6 = {
  key: 2,
  style: {"text-decoration":"line-through"}
};
const _hoisted_16$6 = ["data-testid"];
const _hoisted_17$5 = ["colspan"];
const _hoisted_18$5 = { key: 0 };
const _hoisted_19$4 = ["data-testid"];
const _hoisted_20$3 = { key: 0 };
const _hoisted_21$3 = { key: 1 };
const _hoisted_22$3 = { key: 2 };
const _hoisted_23$3 = { class: "has-background-warning" };
const _hoisted_24$3 = ["data-testid"];
const _hoisted_25$3 = { style: {"text-decoration":"line-through"} };
const _hoisted_26$3 = { key: 0 };
const _hoisted_27$3 = { key: 1 };
const _hoisted_28$3 = {
  key: 2,
  style: {"text-decoration":"line-through"}
};
const _hoisted_29$2 = ["data-testid"];
const _hoisted_30$2 = ["colspan"];
const _hoisted_31$2 = {
  key: 0,
  class: "is-flex is-justify-content-center is-align-items-center",
  style: {"height":"100px"}
};
const _hoisted_32$2 = ["data-testid"];
const _hoisted_33$2 = { key: 1 };
const _hoisted_34$2 = ["data-testid"];
const _hoisted_35$2 = { key: 1 };

function _sfc_render$d(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", null, [
    (!$setup.props.summaryMode)
      ? (openBlock(), createElementBlock("table", _hoisted_1$d, [
          createBaseVNode("thead", null, [
            createBaseVNode("tr", null, [
              createBaseVNode("th", null, toDisplayString(_ctx.$t('tables.products.name')), 1 /* TEXT */),
              ($setup.props.displayNotes)
                ? (openBlock(), createElementBlock("th", _hoisted_2$b, toDisplayString(_ctx.$t('objects.columns.notes')), 1 /* TEXT */))
                : createCommentVNode("v-if", true),
              ($setup.props.displayReference)
                ? (openBlock(), createElementBlock("th", _hoisted_3$b, toDisplayString(_ctx.$t('common.reference')), 1 /* TEXT */))
                : createCommentVNode("v-if", true),
              createBaseVNode("th", null, toDisplayString(_ctx.$t('common.quantity')), 1 /* TEXT */),
              ($setup.props.displayPrice)
                ? (openBlock(), createElementBlock("th", _hoisted_4$b, toDisplayString(_ctx.$t('tables.products.price')), 1 /* TEXT */))
                : createCommentVNode("v-if", true)
            ])
          ]),
          createBaseVNode("tbody", null, [
            (openBlock(true), createElementBlock(Fragment, null, renderList($setup.orderItems, (item) => {
              return (openBlock(), createElementBlock(Fragment, {
                key: item.id
              }, [
                createCommentVNode(" If the item is a primary item, show it "),
                (!$setup.isOrderItemAddon(item))
                  ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                      createCommentVNode(" If the item is included in the invoice, show it normally "),
                      (item.include_in_invoice)
                        ? (openBlock(), createElementBlock("tr", _hoisted_5$a, [
                            createBaseVNode("td", null, [
                              ($setup.getOrderItemFlags(item).length > 0)
                                ? (openBlock(), createElementBlock("span", {
                                    key: 0,
                                    class: normalizeClass(["icon is-small mr-1 invoice-period-item-flag-indicator", $setup.getOrderItemFlagColorClass(item)]),
                                    "data-testid": `order-content-item-flag-indicator-${item.id}`
                                  }, [
                                    createBaseVNode("i", {
                                      class: normalizeClass($setup.getOrderItemFlagIconClass(item))
                                    }, null, 2 /* CLASS */)
                                  ], 10 /* CLASS, PROPS */, _hoisted_6$a))
                                : createCommentVNode("v-if", true),
                              createTextVNode(" " + toDisplayString(item.product.name), 1 /* TEXT */)
                            ]),
                            ($setup.props.displayReference)
                              ? (openBlock(), createElementBlock("td", _hoisted_7$a, toDisplayString(item.reference), 1 /* TEXT */))
                              : createCommentVNode("v-if", true),
                            ($setup.props.displayNotes)
                              ? (openBlock(), createElementBlock("td", _hoisted_8$a, toDisplayString(item.notes), 1 /* TEXT */))
                              : createCommentVNode("v-if", true),
                            createBaseVNode("td", null, toDisplayString(item.quantity), 1 /* TEXT */),
                            ($setup.props.displayPrice)
                              ? (openBlock(), createElementBlock("td", _hoisted_9$9, toDisplayString($setup.SessionUser.functions.currency.toLocal(item.price)), 1 /* TEXT */))
                              : createCommentVNode("v-if", true)
                          ]))
                        : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
                            createCommentVNode(" If the item is not included in the invoice, show it with a strikethrough "),
                            createBaseVNode("tr", _hoisted_10$8, [
                              createBaseVNode("td", null, [
                                ($setup.getOrderItemFlags(item).length > 0)
                                  ? (openBlock(), createElementBlock("span", {
                                      key: 0,
                                      class: normalizeClass(["icon is-small mr-1 invoice-period-item-flag-indicator", $setup.getOrderItemFlagColorClass(item)]),
                                      "data-testid": `order-content-item-flag-indicator-${item.id}`
                                    }, [
                                      createBaseVNode("i", {
                                        class: normalizeClass($setup.getOrderItemFlagIconClass(item))
                                      }, null, 2 /* CLASS */)
                                    ], 10 /* CLASS, PROPS */, _hoisted_11$8))
                                  : createCommentVNode("v-if", true),
                                createBaseVNode("span", _hoisted_12$7, toDisplayString(item.product.name), 1 /* TEXT */),
                                createTextVNode(" ( " + toDisplayString($setup.SessionUser.objects.vehicles.columns.wash_subscription.label) + " ) ", 1 /* TEXT */)
                              ]),
                              ($setup.props.displayReference)
                                ? (openBlock(), createElementBlock("td", _hoisted_13$6, toDisplayString(item.reference), 1 /* TEXT */))
                                : createCommentVNode("v-if", true),
                              ($setup.props.displayNotes)
                                ? (openBlock(), createElementBlock("td", _hoisted_14$6, toDisplayString(item.notes), 1 /* TEXT */))
                                : createCommentVNode("v-if", true),
                              createBaseVNode("td", null, toDisplayString(item.quantity), 1 /* TEXT */),
                              ($setup.props.displayPrice)
                                ? (openBlock(), createElementBlock("td", _hoisted_15$6, toDisplayString($setup.SessionUser.functions.currency.toLocal(item.price)), 1 /* TEXT */))
                                : createCommentVNode("v-if", true)
                            ])
                          ], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */)),
                      ($setup.getOrderItemFlags(item).length > 0)
                        ? (openBlock(), createElementBlock("tr", {
                            key: 2,
                            "data-testid": `order-content-item-flags-${item.id}`
                          }, [
                            createBaseVNode("td", { colspan: $setup.displayColumnCount }, [
                              createVNode($setup["InvoicingPeriodFlagList"], {
                                compact: "",
                                flags: $setup.getOrderItemFlags(item),
                                onStatusChanged: $setup.emitFlagStatusChanged
                              }, null, 8 /* PROPS */, ["flags"])
                            ], 8 /* PROPS */, _hoisted_17$5)
                          ], 8 /* PROPS */, _hoisted_16$6))
                        : createCommentVNode("v-if", true)
                    ], 64 /* STABLE_FRAGMENT */))
                  : createCommentVNode("v-if", true),
                createCommentVNode(" Show the add-on items "),
                (openBlock(true), createElementBlock(Fragment, null, renderList($setup.getItemAddons(item), (addon_item) => {
                  return (openBlock(), createElementBlock(Fragment, {
                    key: addon_item.id
                  }, [
                    createCommentVNode(" If the add-on item is included in the invoice, show it normally "),
                    (addon_item.include_in_invoice)
                      ? (openBlock(), createElementBlock("tr", _hoisted_18$5, [
                          createBaseVNode("td", null, [
                            ($setup.getOrderItemFlags(addon_item).length > 0)
                              ? (openBlock(), createElementBlock("span", {
                                  key: 0,
                                  class: normalizeClass(["icon is-small mr-1 invoice-period-item-flag-indicator", $setup.getOrderItemFlagColorClass(addon_item)]),
                                  "data-testid": `order-content-item-flag-indicator-${addon_item.id}`
                                }, [
                                  createBaseVNode("i", {
                                    class: normalizeClass($setup.getOrderItemFlagIconClass(addon_item))
                                  }, null, 2 /* CLASS */)
                                ], 10 /* CLASS, PROPS */, _hoisted_19$4))
                              : createCommentVNode("v-if", true),
                            createTextVNode(" + " + toDisplayString(addon_item.product.name), 1 /* TEXT */)
                          ]),
                          ($setup.props.displayReference)
                            ? (openBlock(), createElementBlock("td", _hoisted_20$3, toDisplayString(addon_item.reference), 1 /* TEXT */))
                            : createCommentVNode("v-if", true),
                          ($setup.props.displayNotes)
                            ? (openBlock(), createElementBlock("td", _hoisted_21$3, toDisplayString(addon_item.notes), 1 /* TEXT */))
                            : createCommentVNode("v-if", true),
                          createBaseVNode("td", null, toDisplayString(addon_item.quantity), 1 /* TEXT */),
                          ($setup.props.displayPrice)
                            ? (openBlock(), createElementBlock("td", _hoisted_22$3, toDisplayString($setup.SessionUser.functions.currency.toLocal(addon_item.price)), 1 /* TEXT */))
                            : createCommentVNode("v-if", true)
                        ]))
                      : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
                          createCommentVNode(" If the add-on item is not included in the invoice, show it with a strikethrough "),
                          createBaseVNode("tr", _hoisted_23$3, [
                            createBaseVNode("td", null, [
                              ($setup.getOrderItemFlags(addon_item).length > 0)
                                ? (openBlock(), createElementBlock("span", {
                                    key: 0,
                                    class: normalizeClass(["icon is-small mr-1 invoice-period-item-flag-indicator", $setup.getOrderItemFlagColorClass(addon_item)]),
                                    "data-testid": `order-content-item-flag-indicator-${addon_item.id}`
                                  }, [
                                    createBaseVNode("i", {
                                      class: normalizeClass($setup.getOrderItemFlagIconClass(addon_item))
                                    }, null, 2 /* CLASS */)
                                  ], 10 /* CLASS, PROPS */, _hoisted_24$3))
                                : createCommentVNode("v-if", true),
                              _cache[0] || (_cache[0] = createTextVNode(" + ", -1 /* CACHED */)),
                              createBaseVNode("span", _hoisted_25$3, toDisplayString(addon_item.product.name), 1 /* TEXT */),
                              createTextVNode(" ( " + toDisplayString($setup.SessionUser.objects.vehicles.columns.wash_subscription.label) + " ) ", 1 /* TEXT */)
                            ]),
                            ($setup.props.displayReference)
                              ? (openBlock(), createElementBlock("td", _hoisted_26$3, toDisplayString(addon_item.reference), 1 /* TEXT */))
                              : createCommentVNode("v-if", true),
                            ($setup.props.displayNotes)
                              ? (openBlock(), createElementBlock("td", _hoisted_27$3, toDisplayString(addon_item.notes), 1 /* TEXT */))
                              : createCommentVNode("v-if", true),
                            createBaseVNode("td", null, toDisplayString(addon_item.quantity), 1 /* TEXT */),
                            ($setup.props.displayPrice)
                              ? (openBlock(), createElementBlock("td", _hoisted_28$3, toDisplayString($setup.SessionUser.functions.currency.toLocal(addon_item.price)), 1 /* TEXT */))
                              : createCommentVNode("v-if", true)
                          ])
                        ], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */)),
                    ($setup.getOrderItemFlags(addon_item).length > 0)
                      ? (openBlock(), createElementBlock("tr", {
                          key: 2,
                          "data-testid": `order-content-item-flags-${addon_item.id}`
                        }, [
                          createBaseVNode("td", { colspan: $setup.displayColumnCount }, [
                            createVNode($setup["InvoicingPeriodFlagList"], {
                              compact: "",
                              flags: $setup.getOrderItemFlags(addon_item),
                              onStatusChanged: $setup.emitFlagStatusChanged
                            }, null, 8 /* PROPS */, ["flags"])
                          ], 8 /* PROPS */, _hoisted_30$2)
                        ], 8 /* PROPS */, _hoisted_29$2))
                      : createCommentVNode("v-if", true)
                  ], 64 /* STABLE_FRAGMENT */))
                }), 128 /* KEYED_FRAGMENT */))
              ], 64 /* STABLE_FRAGMENT */))
            }), 128 /* KEYED_FRAGMENT */))
          ])
        ]))
      : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
          createCommentVNode(" Summary Mode "),
          createBaseVNode("div", null, [
            createCommentVNode(" Loader "),
            ($setup.orderItems.length === 0)
              ? (openBlock(), createElementBlock("span", _hoisted_31$2, [...(_cache[1] || (_cache[1] = [
                  createBaseVNode("span", { class: "loader is-loading is-align-self-center" }, null, -1 /* CACHED */)
                ]))]))
              : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
                  createCommentVNode(" Order Items "),
                  (openBlock(true), createElementBlock(Fragment, null, renderList($setup.orderItems, (item) => {
                    return (openBlock(), createElementBlock("div", {
                      key: item.id,
                      class: "mb-2"
                    }, [
                      createCommentVNode(" If the item is a primary item, show it "),
                      (!$setup.isOrderItemAddon(item))
                        ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                            createBaseVNode("div", null, [
                              ($setup.getOrderItemFlags(item).length > 0)
                                ? (openBlock(), createElementBlock("span", {
                                    key: 0,
                                    class: normalizeClass(["icon is-small mr-1 invoice-period-item-flag-indicator", $setup.getOrderItemFlagColorClass(item)]),
                                    "data-testid": `order-content-item-flag-indicator-${item.id}`
                                  }, [
                                    createBaseVNode("i", {
                                      class: normalizeClass($setup.getOrderItemFlagIconClass(item))
                                    }, null, 2 /* CLASS */)
                                  ], 10 /* CLASS, PROPS */, _hoisted_32$2))
                                : createCommentVNode("v-if", true),
                              createBaseVNode("strong", null, toDisplayString(item.product.name), 1 /* TEXT */),
                              createTextVNode(" x " + toDisplayString(item.quantity) + " ", 1 /* TEXT */),
                              ($setup.props.displayPrice)
                                ? (openBlock(), createElementBlock("span", _hoisted_33$2, " - " + toDisplayString($setup.SessionUser.functions.currency.toLocal(item.price)), 1 /* TEXT */))
                                : createCommentVNode("v-if", true)
                            ]),
                            createVNode($setup["InvoicingPeriodFlagList"], {
                              compact: "",
                              flags: $setup.getOrderItemFlags(item),
                              onStatusChanged: $setup.emitFlagStatusChanged
                            }, null, 8 /* PROPS */, ["flags"]),
                            createCommentVNode(" Show the add-on items "),
                            (openBlock(true), createElementBlock(Fragment, null, renderList($setup.getItemAddons(item), (addon_item) => {
                              return (openBlock(), createElementBlock("div", {
                                key: addon_item.id,
                                class: "ml-4"
                              }, [
                                createBaseVNode("small", null, [
                                  ($setup.getOrderItemFlags(addon_item).length > 0)
                                    ? (openBlock(), createElementBlock("span", {
                                        key: 0,
                                        class: normalizeClass(["icon is-small mr-1 invoice-period-item-flag-indicator", $setup.getOrderItemFlagColorClass(addon_item)]),
                                        "data-testid": `order-content-item-flag-indicator-${addon_item.id}`
                                      }, [
                                        createBaseVNode("i", {
                                          class: normalizeClass($setup.getOrderItemFlagIconClass(addon_item))
                                        }, null, 2 /* CLASS */)
                                      ], 10 /* CLASS, PROPS */, _hoisted_34$2))
                                    : createCommentVNode("v-if", true),
                                  createTextVNode(" + " + toDisplayString(addon_item.product.name) + " x " + toDisplayString(addon_item.quantity) + " ", 1 /* TEXT */),
                                  ($setup.props.displayPrice)
                                    ? (openBlock(), createElementBlock("span", _hoisted_35$2, " - " + toDisplayString($setup.SessionUser.functions.currency.toLocal(addon_item.price)), 1 /* TEXT */))
                                    : createCommentVNode("v-if", true)
                                ]),
                                createVNode($setup["InvoicingPeriodFlagList"], {
                                  compact: "",
                                  flags: $setup.getOrderItemFlags(addon_item),
                                  onStatusChanged: $setup.emitFlagStatusChanged
                                }, null, 8 /* PROPS */, ["flags"])
                              ]))
                            }), 128 /* KEYED_FRAGMENT */))
                          ], 64 /* STABLE_FRAGMENT */))
                        : createCommentVNode("v-if", true)
                    ]))
                  }), 128 /* KEYED_FRAGMENT */))
                ], 64 /* STABLE_FRAGMENT */))
          ])
        ], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */))
  ]))
}
const OrderContentTable = /*#__PURE__*/_export_sfc(_sfc_main$J, [['render',_sfc_render$d],['__scopeId',"data-v-37cd264d"],['__file',"OrderContentTable.vue"]]);

const _sfc_main$I = {
  __name: 'InvoiceMultipleCollectionsModal',
  props: {
  queued: {
    type: Object,
    required: true,
  },
  succeeded: {
    type: Object,
    required: true,
  },
  failed: {
    type: Object,
    required: true,
  },
  inProgress: {
    type: Object,
    required: true,
  },
  log: {
    type: Object,
    required: false,
  },
  jobs: {
    type: Object,
    required: false,
    default: () => ({}),
  },
},
  emits: ["closeModal", "saveChanges", "retry"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const props = __props;


const emit = __emit;

const closeModal = () => {
  emit("closeModal");
};

// Listen for esc key to close the modal
const handleKeydown = (event) => {
  if (event.key === "Escape") {
    closeModal();
  }
};
window.addEventListener("keydown", handleKeydown);
onBeforeUnmount(() => {
  window.removeEventListener("keydown", handleKeydown);
});

const ucFirst = (str) => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

const getLogStatus = (item) => {
  if (typeof item?.status === "string" && item.status.length > 0) {
    return item.status;
  }

  if (item?.success === true) {
    return "COMPLETED";
  }

  if (item?.success === false) {
    return "FAILED";
  }

  return "QUEUED";
};

const getLogMessage = (item) => {
  if (typeof item?.errorMessage === "string" && item.errorMessage.length > 0) {
    return item.errorMessage;
  }

  if (typeof item?.progressMessage === "string" && item.progressMessage.length > 0) {
    return item.progressMessage;
  }

  return "-";
};

const getLogProgress = (item) => {
  const value = Number(item?.progressPercent ?? 0);
  if (!Number.isFinite(value)) {
    return 0;
  }

  if (value < 0) {
    return 0;
  }

  if (value > 100) {
    return 100;
  }

  return Math.round(value);
};

const canRetry = (item) => item?.success === false;

const retry = (invoiceCollectionId) => {
  emit("retry", invoiceCollectionId);
};


const __returned__ = { props, emit, closeModal, handleKeydown, ucFirst, getLogStatus, getLogMessage, getLogProgress, canRetry, retry, onBeforeUnmount, SessionUser };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$c = {
  class: "modal is-active",
  ref: "modal"
};
const _hoisted_2$a = { class: "modal-card" };
const _hoisted_3$a = { class: "modal-card-head" };
const _hoisted_4$a = { class: "modal-card-title" };
const _hoisted_5$9 = { class: "modal-card-body" };
const _hoisted_6$9 = { class: "level" };
const _hoisted_7$9 = { class: "level-item has-text-centered" };
const _hoisted_8$9 = { class: "heading" };
const _hoisted_9$8 = { class: "title" };
const _hoisted_10$7 = { class: "level-item has-text-centered" };
const _hoisted_11$7 = { class: "heading" };
const _hoisted_12$6 = { class: "title" };
const _hoisted_13$5 = { class: "level-item has-text-centered" };
const _hoisted_14$5 = { class: "heading" };
const _hoisted_15$5 = { class: "title" };
const _hoisted_16$5 = { class: "level-item has-text-centered" };
const _hoisted_17$4 = { class: "heading" };
const _hoisted_18$4 = { class: "title" };
const _hoisted_19$3 = { class: "level-item has-text-centered" };
const _hoisted_20$2 = { class: "heading" };
const _hoisted_21$2 = { class: "title" };
const _hoisted_22$2 = { class: "table-container" };
const _hoisted_23$2 = { class: "table is-striped is-hoverable is-fullwidth" };
const _hoisted_24$2 = ["onClick"];
const _hoisted_25$2 = ["value"];
const _hoisted_26$2 = {
  key: 1,
  class: "tag is-success is-light"
};
const _hoisted_27$2 = {
  key: 2,
  class: "tag is-danger is-light"
};
const _hoisted_28$2 = ["onClick"];

function _sfc_render$c(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$c, [
    createBaseVNode("div", {
      class: "modal-background",
      onClick: $setup.closeModal
    }),
    createBaseVNode("div", _hoisted_2$a, [
      createBaseVNode("header", _hoisted_3$a, [
        createBaseVNode("p", _hoisted_4$a, toDisplayString($setup.SessionUser.objects.global.language.invoice), 1 /* TEXT */),
        createBaseVNode("button", {
          class: "delete",
          "aria-label": "close",
          onClick: $setup.closeModal
        })
      ]),
      createBaseVNode("section", _hoisted_5$9, [
        createCommentVNode(" Level "),
        createBaseVNode("nav", _hoisted_6$9, [
          createBaseVNode("div", _hoisted_7$9, [
            createBaseVNode("div", null, [
              createBaseVNode("p", _hoisted_8$9, toDisplayString($setup.SessionUser.objects.global.language.waiting), 1 /* TEXT */),
              createBaseVNode("p", _hoisted_9$8, toDisplayString($props.queued.length), 1 /* TEXT */)
            ])
          ]),
          createBaseVNode("div", _hoisted_10$7, [
            createBaseVNode("div", null, [
              createBaseVNode("p", _hoisted_11$7, toDisplayString($setup.SessionUser.objects.global.language.in_progress), 1 /* TEXT */),
              createBaseVNode("p", _hoisted_12$6, toDisplayString($props.inProgress.length), 1 /* TEXT */)
            ])
          ]),
          createBaseVNode("div", _hoisted_13$5, [
            createBaseVNode("div", null, [
              createBaseVNode("p", _hoisted_14$5, toDisplayString($setup.SessionUser.objects.global.language.succeeded), 1 /* TEXT */),
              createBaseVNode("p", _hoisted_15$5, toDisplayString($props.succeeded.length), 1 /* TEXT */)
            ])
          ]),
          createBaseVNode("div", _hoisted_16$5, [
            createBaseVNode("div", null, [
              createBaseVNode("p", _hoisted_17$4, toDisplayString($setup.SessionUser.objects.global.language.failed), 1 /* TEXT */),
              createBaseVNode("p", _hoisted_18$4, toDisplayString($props.failed.length), 1 /* TEXT */)
            ])
          ]),
          createBaseVNode("div", _hoisted_19$3, [
            createBaseVNode("div", null, [
              createBaseVNode("p", _hoisted_20$2, toDisplayString($setup.SessionUser.objects.global.language.total), 1 /* TEXT */),
              createBaseVNode("p", _hoisted_21$2, toDisplayString($props.queued.length + $props.succeeded.length + $props.failed.length + $props.inProgress.length), 1 /* TEXT */)
            ])
          ])
        ]),
        createCommentVNode(" Table logs "),
        createBaseVNode("div", _hoisted_22$2, [
          createBaseVNode("table", _hoisted_23$2, [
            createBaseVNode("thead", null, [
              createBaseVNode("tr", null, [
                createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.global.language.status), 1 /* TEXT */),
                createBaseVNode("th", null, toDisplayString($setup.ucFirst($setup.SessionUser.objects.collectedOrderInvoices.meta.labels.single)), 1 /* TEXT */),
                createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.global.language.customer), 1 /* TEXT */),
                createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.global.language.progress), 1 /* TEXT */),
                createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.global.language.actions), 1 /* TEXT */)
              ])
            ]),
            createBaseVNode("tbody", null, [
              (openBlock(true), createElementBlock(Fragment, null, renderList($props.log, (item, index) => {
                return (openBlock(), createElementBlock("tr", { key: index }, [
                  createBaseVNode("td", null, toDisplayString($setup.getLogStatus(item)), 1 /* TEXT */),
                  createBaseVNode("td", {
                    class: "is-clickable",
                    onClick: $event => ($setup.SessionUser.functions.redirectTo.superUser('/invoices/' + item.invoiceCollectionId, true))
                  }, toDisplayString(item.invoiceCollectionId), 9 /* TEXT, PROPS */, _hoisted_24$2),
                  createBaseVNode("td", null, toDisplayString($setup.getLogMessage(item)), 1 /* TEXT */),
                  createBaseVNode("td", null, [
                    ($setup.getLogStatus(item) === 'QUEUED' || $setup.getLogStatus(item) === 'PROCESSING')
                      ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                          createBaseVNode("progress", {
                            class: "progress is-link is-small",
                            max: "100",
                            value: $setup.getLogProgress(item)
                          }, null, 8 /* PROPS */, _hoisted_25$2),
                          createBaseVNode("small", null, toDisplayString($setup.getLogProgress(item)) + "%", 1 /* TEXT */)
                        ], 64 /* STABLE_FRAGMENT */))
                      : ($setup.getLogStatus(item) === 'COMPLETED')
                        ? (openBlock(), createElementBlock("span", _hoisted_26$2, "100%"))
                        : (openBlock(), createElementBlock("span", _hoisted_27$2, toDisplayString($setup.getLogProgress(item)) + "%", 1 /* TEXT */))
                  ]),
                  createBaseVNode("td", null, [
                    ($setup.canRetry(item))
                      ? (openBlock(), createElementBlock("button", {
                          key: 0,
                          class: "button is-small is-danger is-light",
                          onClick: $event => ($setup.retry(item.invoiceCollectionId))
                        }, toDisplayString($setup.SessionUser.objects.global.language.retry), 9 /* TEXT, PROPS */, _hoisted_28$2))
                      : createCommentVNode("v-if", true)
                  ])
                ]))
              }), 128 /* KEYED_FRAGMENT */))
            ])
          ])
        ])
      ]),
      _cache[0] || (_cache[0] = createBaseVNode("footer", { class: "modal-card-foot" }, null, -1 /* CACHED */))
    ])
  ], 512 /* NEED_PATCH */))
}
const InvoiceMultipleCollectionsModal = /*#__PURE__*/_export_sfc(_sfc_main$I, [['render',_sfc_render$c],['__file',"InvoiceMultipleCollectionsModal.vue"]]);

const SELF_SERVE_WASH_ATTACHMENT_TYPE = "SELF_SERVE_WASH";
const _sfc_main$H = /* @__PURE__ */ defineComponent({
  __name: "PosDepartmentStepMobileAttachment",
  props: {
    attachments: {
      type: Array,
      required: true
    },
    getPreviewLink: {
      type: Function,
      required: true
    },
    showAttachWashCertificateAction: {
      type: Boolean,
      default: false
    }
  },
  emits: ["delete", "upload", "download", "attach-wash-certificate"],
  setup(__props, { expose: __expose, emit: __emit }) {
    __expose();
    const { t } = useI18n();
    const getAttachmentContent = (attachmentEntry) => {
      if (!attachmentEntry.content) {
        return {
          image: null,
          document: null,
          relation: null,
          other: null,
          src: null
        };
      }
      return {
        image: attachmentEntry.content.image ?? null,
        document: attachmentEntry.content.document ?? null,
        relation: attachmentEntry.content.relation ?? null,
        other: attachmentEntry.content.other ?? null,
        src: attachmentEntry.content.src ?? null
      };
    };
    const getAttachmentOtherText = (attachmentEntry) => {
      const other = getAttachmentContent(attachmentEntry).other;
      if (typeof other === "string") {
        return other;
      }
      if (isSelfServeWashAttachment(attachmentEntry)) {
        const customerNumber = getSelfServeWashPayload(attachmentEntry)?.customer_number;
        return customerNumber ? `${t("admin.pos.settings_wheel.self_serve_wash_attachment")} #${customerNumber}` : t("admin.pos.settings_wheel.self_serve_wash_attachment");
      }
      return other && typeof other === "object" ? JSON.stringify(other) : "";
    };
    const props = __props;
    const emits = __emit;
    const onClickDelete = (id) => {
      emits("delete", id);
    };
    const determineAttachmentType = (attachment) => {
      const content = getAttachmentContent(attachment);
      if (content.image) return "image";
      if (content.document) return "document";
      if (content.relation) return "relation";
      if (content.other) return "other";
      return "unknown";
    };
    const getSelfServeWashPayload = (attachmentEntry) => {
      const other = getAttachmentContent(attachmentEntry).other;
      return other && typeof other === "object" && other.type === SELF_SERVE_WASH_ATTACHMENT_TYPE ? other : null;
    };
    const isSelfServeWashAttachment = (attachmentEntry) => {
      return getSelfServeWashPayload(attachmentEntry) !== null;
    };
    const formatSelfServeDriver = (payload) => {
      return payload.subuser?.name || payload.subuser?.username || (payload.subuser_id ? `#${payload.subuser_id}` : "-");
    };
    const formatElapsedMinutes = (seconds) => {
      const parsed = Number(seconds);
      return Number.isFinite(parsed) && parsed > 0 ? `${Math.ceil(parsed / 60)} min` : "-";
    };
    const getAttachmentTypeIcon = (attachment) => {
      const type = determineAttachmentType(attachment);
      switch (type) {
        case "image":
          return "fas fa-image";
        case "document":
          return "fas fa-file-alt";
        case "relation":
          return "fas fa-link";
        case "other":
          return "fas fa-ellipsis-h";
        default:
          return "fas fa-question";
      }
    };
    const isAttachmentTypeIn = (types) => {
      return props.attachments.some((att) => types.includes(determineAttachmentType(att)));
    };
    const isOfficeDocument = (attachmentEntry) => {
      const otherText = getAttachmentOtherText(attachmentEntry).toLowerCase();
      return [".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx"].some((extension) => otherText.endsWith(extension));
    };
    const previewRequestsInFlight = /* @__PURE__ */ new Set();
    const generatedObjectUrls = /* @__PURE__ */ new Set();
    const isObjectUrl = (url) => Boolean(url && url.startsWith("blob:"));
    const releaseObjectUrl = (url) => {
      if (!isObjectUrl(url)) {
        return;
      }
      URL.revokeObjectURL(url);
      generatedObjectUrls.delete(url);
    };
    const shouldLoadDocumentPreview = (attachmentEntry) => {
      const content = getAttachmentContent(attachmentEntry);
      return determineAttachmentType(attachmentEntry) === "document" && Boolean(content.document) && !isOfficeDocument(attachmentEntry) && !content.src;
    };
    const createEmbeddablePreviewUrl = async (downloadLink) => {
      if (!downloadLink) {
        return null;
      }
      try {
        const response = await fetch(downloadLink, { method: "GET" });
        if (!response.ok) {
          return null;
        }
        const fileBlob = await response.blob();
        if (!fileBlob || fileBlob.size === 0) {
          return null;
        }
        const objectUrl = URL.createObjectURL(fileBlob);
        generatedObjectUrls.add(objectUrl);
        return objectUrl;
      } catch (error) {
        console.warn("Unable to create embeddable preview blob", error);
        return null;
      }
    };
    const loadPreviewLink = async (id) => {
      if (previewRequestsInFlight.has(id)) {
        return;
      }
      previewRequestsInFlight.add(id);
      try {
        const downloadLink = await props.getPreviewLink(id);
        const src = await createEmbeddablePreviewUrl(downloadLink);
        const attachment = props.attachments.find((att) => att.id === id);
        if (!attachment) {
          return;
        }
        const content = getAttachmentContent(attachment);
        if (content.src && content.src !== src) {
          releaseObjectUrl(content.src);
        }
        content.src = src || null;
        attachment.content = content;
      } catch (error) {
        console.warn("Error loading preview link for attachment", id, error);
      } finally {
        previewRequestsInFlight.delete(id);
      }
    };
    watch(
      () => props.attachments.map((attachment) => `${attachment.id}:${getAttachmentContent(attachment).src ?? ""}:${getAttachmentOtherText(attachment)}`),
      () => {
        props.attachments.forEach((attachment) => {
          if (shouldLoadDocumentPreview(attachment)) {
            void loadPreviewLink(attachment.id);
          }
        });
      },
      { immediate: true }
    );
    onBeforeUnmount(() => {
      generatedObjectUrls.forEach((url) => URL.revokeObjectURL(url));
      generatedObjectUrls.clear();
    });
    const uploadAttachment = (file) => {
      console.warn("Uploading file:", file);
      const reader = new FileReader();
      reader.onload = (e) => {
        const base64String = e.target?.result;
        const filename = file.name;
        emits("upload", { filename, base64String });
      };
      reader.readAsDataURL(file);
    };
    const onClickUpload = () => {
      const fileInput = document.createElement("input");
      fileInput.type = "file";
      fileInput.accept = "image/*,application/pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx";
      fileInput.onchange = (event) => {
        const target = event.target;
        if (target.files && target.files[0]) {
          uploadAttachment(target.files[0]);
        }
      };
      fileInput.click();
    };
    const onClickAttachWashCertificate = () => {
      emits("attach-wash-certificate");
    };
    const __returned__ = { t, SELF_SERVE_WASH_ATTACHMENT_TYPE, getAttachmentContent, getAttachmentOtherText, props, emits, onClickDelete, determineAttachmentType, getSelfServeWashPayload, isSelfServeWashAttachment, formatSelfServeDriver, formatElapsedMinutes, getAttachmentTypeIcon, isAttachmentTypeIn, isOfficeDocument, previewRequestsInFlight, generatedObjectUrls, isObjectUrl, releaseObjectUrl, shouldLoadDocumentPreview, createEmbeddablePreviewUrl, loadPreviewLink, uploadAttachment, onClickUpload, onClickAttachWashCertificate, WhiteBoxCard };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$b = { class: "is-fullwidth" };
const _hoisted_2$9 = { class: "columns is-mobile is-multiline is-variable is-1" };
const _hoisted_3$9 = { class: "column is-12" };
const _hoisted_4$9 = { class: "card-header-title" };
const _hoisted_5$8 = { class: "card-header-icon" };
const _hoisted_6$8 = { class: "icon" };
const _hoisted_7$8 = { class: "card-header-title" };
const _hoisted_8$8 = { key: 0 };
const _hoisted_9$7 = ["onClick"];
const _hoisted_10$6 = ["src"];
const _hoisted_11$6 = { key: 2 };
const _hoisted_12$5 = {
  key: 0,
  class: "content is-size-7"
};
const _hoisted_13$4 = { class: "has-text-weight-semibold" };
const _hoisted_14$4 = ["href"];
const _hoisted_15$4 = { key: 2 };
const _hoisted_16$4 = { class: "card-footer-item" };
const _hoisted_17$3 = ["onClick"];
const _hoisted_18$3 = ["data-testid", "onClick"];
function _sfc_render$b(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock("div", _hoisted_1$b, [
    createBaseVNode("div", _hoisted_2$9, [
      createCommentVNode(" Add Attachment Button "),
      createBaseVNode("div", _hoisted_3$9, [
        createVNode($setup["WhiteBoxCard"], {
          toggleable: true,
          "data-testid": "pos-order-attachments-add-card"
        }, {
          header: withCtx(() => [
            _cache[0] || (_cache[0] = createBaseVNode(
              "div",
              { class: "card-header-icon" },
              [
                createBaseVNode("span", { class: "icon" }, [
                  createBaseVNode("i", {
                    class: "fas fa-plus",
                    "aria-hidden": "true"
                  })
                ])
              ],
              -1
              /* CACHED */
            )),
            createBaseVNode(
              "div",
              _hoisted_4$9,
              toDisplayString($setup.t("admin.pos.attachments_add")),
              1
              /* TEXT */
            ),
            _cache[1] || (_cache[1] = createBaseVNode(
              "div",
              { class: "card-header-icon" },
              [
                createBaseVNode("span", { class: "icon" }, [
                  createBaseVNode("i", {
                    class: "fas fa-chevron-down",
                    "aria-hidden": "true"
                  })
                ])
              ],
              -1
              /* CACHED */
            ))
          ]),
          content: withCtx(() => [
            createCommentVNode(" Content for adding a new attachment can go here "),
            createBaseVNode(
              "p",
              null,
              toDisplayString($setup.t("admin.pos.attachments_upload_description")),
              1
              /* TEXT */
            )
          ]),
          footer: withCtx(() => [
            createBaseVNode("a", {
              class: "card-footer-item",
              "data-testid": "pos-order-attachments-upload-action",
              onClick: $setup.onClickUpload
            }, [
              createCommentVNode(" Footer actions can go here "),
              createTextVNode(
                " " + toDisplayString($setup.t("admin.pos.attachments_upload_action")),
                1
                /* TEXT */
              )
            ]),
            $setup.props.showAttachWashCertificateAction ? (openBlock(), createElementBlock(
              "a",
              {
                key: 0,
                class: "card-footer-item",
                "data-testid": "pos-order-attachments-attach-wash-certificate",
                onClick: $setup.onClickAttachWashCertificate
              },
              toDisplayString($setup.t("admin.pos.settings_wheel.attach_wash_certificate")),
              1
              /* TEXT */
            )) : createCommentVNode("v-if", true)
          ]),
          _: 1
          /* STABLE */
        })
      ]),
      createCommentVNode(" Existing Attachments "),
      (openBlock(true), createElementBlock(
        Fragment,
        null,
        renderList($setup.props.attachments, (attachment) => {
          return openBlock(), createElementBlock("div", {
            key: attachment.id,
            class: "column is-12"
          }, [
            createVNode($setup["WhiteBoxCard"], {
              toggleable: true,
              "data-testid": `pos-order-attachment-card-${attachment.id}`
            }, {
              header: withCtx(() => [
                createBaseVNode("div", _hoisted_5$8, [
                  _cache[2] || (_cache[2] = createBaseVNode(
                    "span",
                    { class: "icon" },
                    [
                      createBaseVNode("i", {
                        class: "fas fa-paperclip",
                        "aria-hidden": "true"
                      })
                    ],
                    -1
                    /* CACHED */
                  )),
                  createBaseVNode("span", _hoisted_6$8, [
                    createBaseVNode(
                      "i",
                      {
                        class: normalizeClass($setup.getAttachmentTypeIcon(attachment)),
                        "aria-hidden": "true"
                      },
                      null,
                      2
                      /* CLASS */
                    )
                  ])
                ]),
                createBaseVNode(
                  "div",
                  _hoisted_7$8,
                  toDisplayString($setup.t("admin.pos.attachment")) + " #" + toDisplayString(attachment.id),
                  1
                  /* TEXT */
                ),
                _cache[3] || (_cache[3] = createBaseVNode(
                  "div",
                  { class: "card-header-icon" },
                  [
                    createBaseVNode("span", { class: "icon" }, [
                      createBaseVNode("i", {
                        class: "fas fa-chevron-down",
                        "aria-hidden": "true"
                      })
                    ])
                  ],
                  -1
                  /* CACHED */
                ))
              ]),
              content: withCtx(() => [
                createCommentVNode("{{ attachment }}"),
                createCommentVNode(" DOCUMENT PREVIEW "),
                $setup.determineAttachmentType(attachment) === "document" && $setup.getAttachmentContent(attachment).document ? (openBlock(), createElementBlock(
                  Fragment,
                  { key: 0 },
                  [
                    createCommentVNode(" If the file extension is office document, you can use an online viewer "),
                    $setup.isOfficeDocument(attachment) ? (openBlock(), createElementBlock("span", _hoisted_8$8, [
                      createTextVNode(
                        toDisplayString($setup.t("admin.pos.attachments_office_preview_unavailable")) + " ",
                        1
                        /* TEXT */
                      ),
                      createBaseVNode("a", {
                        onClick: ($event) => _ctx.$emit("download", attachment.id)
                      }, toDisplayString($setup.t("admin.pos.attachments_download_action")), 9, _hoisted_9$7)
                    ])) : $setup.getAttachmentContent(attachment).src ? (openBlock(), createElementBlock("iframe", {
                      key: 1,
                      src: $setup.getAttachmentContent(attachment).src || "",
                      style: { "width": "100%", "height": "400px", "border": "none" }
                    }, null, 8, _hoisted_10$6)) : (openBlock(), createElementBlock(
                      "span",
                      _hoisted_11$6,
                      toDisplayString($setup.t("admin.pos.attachments_no_preview")),
                      1
                      /* TEXT */
                    ))
                  ],
                  64
                  /* STABLE_FRAGMENT */
                )) : $setup.determineAttachmentType(attachment) === "other" && $setup.getAttachmentContent(attachment).other ? (openBlock(), createElementBlock(
                  Fragment,
                  { key: 1 },
                  [
                    createCommentVNode(" OTHER PREVIEW "),
                    $setup.isSelfServeWashAttachment(attachment) ? (openBlock(), createElementBlock("div", _hoisted_12$5, [
                      createBaseVNode(
                        "p",
                        _hoisted_13$4,
                        toDisplayString($setup.t("admin.pos.settings_wheel.self_serve_wash_attachment")),
                        1
                        /* TEXT */
                      ),
                      createBaseVNode("p", null, [
                        createBaseVNode(
                          "strong",
                          null,
                          toDisplayString($setup.t("admin.pos.settings_wheel.self_serve_customer")) + ":",
                          1
                          /* TEXT */
                        ),
                        createTextVNode(
                          " #" + toDisplayString($setup.getSelfServeWashPayload(attachment)?.customer_number || "-"),
                          1
                          /* TEXT */
                        )
                      ]),
                      createBaseVNode("p", null, [
                        createBaseVNode(
                          "strong",
                          null,
                          toDisplayString($setup.t("admin.pos.settings_wheel.self_serve_driver")) + ":",
                          1
                          /* TEXT */
                        ),
                        createTextVNode(
                          " " + toDisplayString($setup.formatSelfServeDriver($setup.getSelfServeWashPayload(attachment) || {})),
                          1
                          /* TEXT */
                        )
                      ]),
                      createBaseVNode("p", null, [
                        createBaseVNode(
                          "strong",
                          null,
                          toDisplayString($setup.t("pos.license_plate")) + ":",
                          1
                          /* TEXT */
                        ),
                        createTextVNode(
                          " " + toDisplayString($setup.getSelfServeWashPayload(attachment)?.license_plate || "-"),
                          1
                          /* TEXT */
                        )
                      ]),
                      createBaseVNode("p", null, [
                        createBaseVNode(
                          "strong",
                          null,
                          toDisplayString($setup.t("admin.pos.settings_wheel.self_serve_elapsed")) + ":",
                          1
                          /* TEXT */
                        ),
                        createTextVNode(
                          " " + toDisplayString($setup.formatElapsedMinutes($setup.getSelfServeWashPayload(attachment)?.elapsed_wash_time_seconds)),
                          1
                          /* TEXT */
                        )
                      ])
                    ])) : typeof $setup.getAttachmentContent(attachment).other === "string" && $setup.getAttachmentContent(attachment).other.startsWith("http") ? (openBlock(), createElementBlock(
                      Fragment,
                      { key: 1 },
                      [
                        createCommentVNode(" If the other type is a URL, you can create a link "),
                        createBaseVNode("a", {
                          href: String($setup.getAttachmentContent(attachment).other),
                          target: "_blank",
                          rel: "noopener noreferrer"
                        }, toDisplayString($setup.getAttachmentContent(attachment).other), 9, _hoisted_14$4)
                      ],
                      64
                      /* STABLE_FRAGMENT */
                    )) : (openBlock(), createElementBlock(
                      "span",
                      _hoisted_15$4,
                      toDisplayString($setup.getAttachmentOtherText(attachment)),
                      1
                      /* TEXT */
                    ))
                  ],
                  64
                  /* STABLE_FRAGMENT */
                )) : (openBlock(), createElementBlock(
                  Fragment,
                  { key: 2 },
                  [
                    createCommentVNode(" NO PREVIEW "),
                    createBaseVNode(
                      "span",
                      null,
                      toDisplayString($setup.t("admin.pos.attachments_no_preview")),
                      1
                      /* TEXT */
                    )
                  ],
                  64
                  /* STABLE_FRAGMENT */
                ))
              ]),
              footer: withCtx(() => [
                createBaseVNode(
                  "div",
                  _hoisted_16$4,
                  toDisplayString($setup.t("common.created")) + ": " + toDisplayString(new Date(attachment.created_at).toLocaleString()),
                  1
                  /* TEXT */
                ),
                !attachment.deleted_at ? (openBlock(), createElementBlock("a", {
                  key: 0,
                  class: "card-footer-item",
                  onClick: ($event) => $setup.onClickDelete(attachment.id)
                }, [
                  createCommentVNode(" Delete button or action can be placed here "),
                  createTextVNode(
                    " " + toDisplayString($setup.t("admin.pos.delete")),
                    1
                    /* TEXT */
                  )
                ], 8, _hoisted_17$3)) : createCommentVNode("v-if", true),
                createCommentVNode(" Download, if applicable "),
                $setup.isAttachmentTypeIn(["image", "document"]) && ($setup.getAttachmentContent(attachment).image || $setup.getAttachmentContent(attachment).document) ? (openBlock(), createElementBlock("a", {
                  key: 1,
                  class: "card-footer-item",
                  "data-testid": `pos-order-attachment-download-${attachment.id}`,
                  onClick: ($event) => _ctx.$emit("download", attachment.id)
                }, toDisplayString($setup.t("admin.pos.attachments_download_action")), 9, _hoisted_18$3)) : createCommentVNode("v-if", true)
              ]),
              _: 2
              /* DYNAMIC */
            }, 1032, ["data-testid"])
          ]);
        }),
        128
        /* KEYED_FRAGMENT */
      ))
    ])
  ]);
}
const PosDepartmentStepMobileAttachment = /* @__PURE__ */ _export_sfc(_sfc_main$H, [["render", _sfc_render$b], ["__file", "PosDepartmentStepMobileAttachment.vue"]]);

const getMatch = (query) => {
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false
  return window.matchMedia(query).matches
};

const _sfc_main$G = defineComponent({
  name: 'ViewportResponsiveWrapper',
  setup(_, { slots }) {
    const isMobile = useMediaQuery('(max-width: 768px)', getMatch('(max-width: 768px)'));
    const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)', getMatch('(min-width: 769px) and (max-width: 1024px)'));
    const isDesktop = useMediaQuery('(min-width: 1025px)', getMatch('(min-width: 1025px)'));

    return () => {
      if (isMobile.value && slots.mobile) return slots.mobile()
      if (isTablet.value && slots.tablet) return slots.tablet()
      if (isDesktop.value && slots.desktop) return slots.desktop()
      return slots.default ? slots.default() : []
    }
  },
});
const ViewportResponsiveWrapper = /*#__PURE__*/_export_sfc(_sfc_main$G, [['__file',"ViewportResponsiveWrapper.vue"]]);

const NAVIGATION_COUNT_REFRESH_EVENT = "navigation-count-refresh";

const dispatchNavigationCountRefresh = () => {
  if (typeof window === "undefined") {
    return;
  }

  window.dispatchEvent(new Event(NAVIGATION_COUNT_REFRESH_EVENT));
};

const _sfc_main$F = {
  __name: 'ordersTable',
  props: {
  orders: {
    type: Object,
    required: true,
  },
  invoiceView: {
    type: Boolean,
    default: false,
  },
  allowSelectMultiple: {
    type: Boolean,
    default: false,
  },
  isCustomerView: {
    type: Boolean,
    default: false,
  },
  groupInvoiceCollection: {
    type: Boolean,
    default: false,
  },
  showOnlyWithIds: {
    type: Array,
    default: () => [],
  },
  autoExpandAll: {
    type: Boolean,
    default: false,
  },
  excludedOrderIds: {
    type: Array, // Any order ids that should be excluded from the list, will also be excluded from calculations (e.g. hidden orders).
    default: () => [],
  },
  showDraftAssignmentActions: {
    type: Boolean,
    default: false,
  },
  invoicePeriodFlags: {
    type: Array,
    default: () => [],
  },
},
  emits: ["flagStatusChanged", "flagCreated"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const { t, locale } = useI18n();

const props = __props;
const emit = __emit;
const { orderBy, orderDirection, setOrder, loadList } = usePaginatedListInstance();
const route = useRoute();

const redirectDepartmentOrderPage = (orderId, departmentId, newTab = true) => {
  // Check if the user has access to the department
  if (!SessionUser.canAccessDepartment(departmentId)) {
    window.open("/user/orders/" + orderId, newTab ? "_blank" : "_self");
  } else {
    // Send the user to the order page (In a new tab)
    // `/admin/${departmentId}/modules/pos/orders/${orderId}`
    window.open(`/admin/${departmentId}/modules/pos/orders/${orderId}`, newTab ? "_blank" : "_self");
  }
};

const redirectSuperUserInvoiceCollectionPage = (invoiceCollectionId) => {
  // Send the user to the invoice collection page (In a new tab)
  window.open(`/superuser/invoices/${invoiceCollectionId}`, "_blank");
};

// Get the departments (If the departments are not already loaded)
if (departments.value.length === 0) {
  getDepartments();
}

const getEconomicInvoiceModule = (order) => order?.economic_invoice_module ?? null;
const getStripeInvoiceModule = (order) => order?.stripe_invoice_module ?? null;
const getInvoiceCollection = (order) => order?.invoice_collection ?? null;

const isOrderInvoicedWithEconomic = (order) => {
  const economicInvoiceModule = getEconomicInvoiceModule(order);
  if (!economicInvoiceModule) {
    return false;
  }

  return economicInvoiceModule.invoice_id !== null || economicInvoiceModule.invoice_draft_id !== null;
};

const isOrderEconomicInvoiceBooked = (order) => {
  const economicInvoiceModule = getEconomicInvoiceModule(order);
  if (!economicInvoiceModule) {
    return false;
  }

  return economicInvoiceModule.invoice_id !== null;
};

const isOrderInvoicedWithStripe = (order) => {
  return getStripeInvoiceModule(order) !== null;
};

const isOrderInvoiced = (order) => {
  return isOrderInvoicedWithEconomic(order) || isOrderInvoicedWithStripe(order);
};

const doesOrderHaveInvoiceCollection = (order) => {
  return getInvoiceCollection(order) !== null;
};

const isOrderInvoiceCollectionClosed = (order) => {
  const invoiceCollection = getInvoiceCollection(order);
  if (!invoiceCollection) {
    return false;
  }

  return invoiceCollection.closed_at !== null;
};

const isOrderInvoiceCollectionBooked = (order) => {
  const invoiceCollection = getInvoiceCollection(order);
  if (!invoiceCollection) {
    return false;
  }

  return invoiceCollection.booked_invoice_id !== null;
};

const isOrderStripeInvoicePaid = (order) => {
  const stripeInvoiceModule = getStripeInvoiceModule(order);
  if (stripeInvoiceModule) {
    return stripeInvoiceModule.paid;
  }
  return false;
};

const doesOrderHaveErrorMessage = (order) => {
  return order.error_message !== null && order.error_message !== undefined;
};

const getOrderInvoiceStatusBarColor = (order) => {
  // Check the invoice status
  let color_class = "has-text-danger";
  if (isOrderInvoicedWithStripe(order)) {
    isOrderStripeInvoicePaid(order) ? (color_class = "has-text-success") : (color_class = "has-text-warning");
  }
  if (isOrderInvoicedWithEconomic(order)) {
    isOrderEconomicInvoiceBooked(order) ? (color_class = "has-text-success") : (color_class = "has-text-warning");
  }
  if (doesOrderHaveInvoiceCollection(order)) {
    if (isPendingHandheld(order) && !order?.completed_at) {
      return "has-text-warning"; // If the order is pending handheld, show a warning color
    }
    color_class = "has-text-grey";
    // Check if the invoice collection is closed
    if (isOrderInvoiceCollectionClosed(order)) {
      color_class = "has-text-warning";
      // Check if the invoice collection is booked
      if (isOrderInvoiceCollectionBooked(order)) {
        color_class = "has-text-success";
      }
    }
  }
  if (doesOrderHaveErrorMessage(order)) {
    color_class = "has-text-danger";
  }
  // Return the color class
  return color_class;
};

const getOrderInvoiceStatusContent = (order) => {
  const content = [];
  const economicInvoiceModule = getEconomicInvoiceModule(order);
  const stripeInvoiceModule = getStripeInvoiceModule(order);
  const invoiceCollection = getInvoiceCollection(order);
  if (isOrderInvoiced(order)) {
    // If the order is invoiced with e-conomic, show the invoice id
    if (isOrderInvoicedWithEconomic(order)) {
      isOrderEconomicInvoiceBooked(order)
        ? content.push("Bogført i e-conomic")
        : content.push("Gemt som kladde i e-conomic");
      isOrderEconomicInvoiceBooked(order)
        ? content.push("Faktura ID: <strong>" + (economicInvoiceModule?.invoice_id ?? "-") + "</strong>")
        : content.push("Faktura Kladde ID: <strong>" + (economicInvoiceModule?.invoice_draft_id ?? "-") + "</strong>");
    }
    // If the order is invoiced with stripe, show the invoice id
    if (isOrderInvoicedWithStripe(order)) {
      isOrderStripeInvoicePaid(order)
        ? content.push("Fakturaen er <strong>betalt</strong>")
        : content.push("Fakturaen er <strong>ikke betalt</strong>");
      content.push("Faktura ID: <strong>" + (stripeInvoiceModule?.id ?? "-") + "</strong>");
    }
    content.push(""); // Add a line break
    isOrderInvoicedWithEconomic(order)
      ? content.push('<span class="has-text-grey">Faktureret med e-conomic</span>')
      : content.push('<span class="has-text-grey">Faktureret med stripe</span>');
  } else {
    // Check if the order has an invoice collection
    if (doesOrderHaveInvoiceCollection(order)) {
      // Check if the invoice collection is closed
      if (isOrderInvoiceCollectionClosed(order)) {
        content.push("Faktura samlingen er <strong>lukket</strong>");
        // Check if the invoice collection is booked
        if (isOrderInvoiceCollectionBooked(order)) {
          content.push("Faktura samlingen er <strong>bogført</strong>");
        }
      }
      content.push(""); // Add a line break
      content.push("Faktura samling ID: <strong>" + (invoiceCollection?.id ?? "-") + "</strong>");
      // Add the Error message if it exists
      if (doesOrderHaveErrorMessage(order)) {
        content.push('Fejl: <strong class="has-text-danger">' + order.error_message + "</strong>");
      }
    } else {
      content.push(""); // Add a line break
      content.push('<strong class="has-text-grey">Transaktionen er ikke faktureret</strong>');
    }
  }
  // Return the list of content as a string, with line breaks between each item
  return content.join("<br>");
};

const getOrderInvoiceStatusTitle = (order) => {
  return isOrderInvoiced(order) ? "Faktura status" : "Transaktion status";
};

const clickUser = (customer_id) => {
  if (!SessionUser.canAccessSuperUser()) {
    return;
  }
  // Send the user to the user page
  SessionUser.adminUser.customers.fromCustomerNumber
    .getUserId(customer_id)
    .then((response) => window.open("/superuser/users/" + response.data.data.user_id, "_blank"));
};

const truncateOrderField = (value, length = 25) => {
  return SessionUser.functions.text.truncate(value ?? "", length);
};

const normalizeInvoiceCollectionId = (invoiceCollectionId) => {
  const parsedInvoiceCollectionId = Number.parseInt(invoiceCollectionId, 10);
  return Number.isInteger(parsedInvoiceCollectionId) && parsedInvoiceCollectionId > 0
    ? parsedInvoiceCollectionId
    : null;
};

const getApiPayload = (response) => response?.data?.data ?? response?.data ?? response ?? {};

const escapeHtml = (value) =>
  String(value ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");

const getInvoiceCollectionResponseOrders = (response) => {
  if (Array.isArray(response?.orders)) {
    return response.orders;
  }

  if (Array.isArray(response?.data?.orders)) {
    return response.data.orders;
  }

  if (Array.isArray(response?.data?.data?.orders)) {
    return response.data.data.orders;
  }

  if (Array.isArray(response?.includes?.orders)) {
    return response.includes.orders;
  }

  return [];
};

const isColumnCurrentlyBeingSortedBy = (column) => {
  // Check if the column is currently being sorted by
  return orderBy.value === column;
};

const isCurrentSortDirectionAscending = () => {
  // Check if the current sort direction is ascending
  return orderDirection.value === "asc";
};

const isCurrentSortDirectionDescending = () => {
  // Check if the current sort direction is descending
  return orderDirection.value === "desc";
};

const onTableHeaderClick = (column) => {
  // Check if the column is already sorted
  if (orderBy.value === column) {
    // If the column is already sorted, toggle the direction
    const direction = orderDirection.value === "asc" ? "desc" : "asc";
    setOrder(column, direction);
  } else {
    // If the column is not sorted, set the order to the new column and default to ascending
    const direction = "asc";
    setOrder(column, direction);
  }
  // Load the list
  loadList();
};

const tableHeaders = ref([
  {
    name: "id",
    title: SessionUser.objects.orders.columns.id.label,
    sortable: true,
  },
  ...(props.isCustomerView
    ? []
    : [
        {
          name: "customer_id",
          title: SessionUser.objects.orders.columns.customer_id.label,
          sortable: true,
        },
      ]),
  ...(props.isCustomerView
    ? []
    : [
        {
          name: "cashier_id",
          title: SessionUser.objects.orders.columns.cashier_id.label,
          sortable: true,
        },
      ]),
  {
    name: "department_id",
    title: SessionUser.objects.orders.columns.department_id.label,
    sortable: true,
  },
  {
    name: "reg_1",
    title: SessionUser.functions.ucFirst(SessionUser.objects.vehicles.meta.labels.multiple),
    sortable: true,
  },
  /**
   * {
   *     name: 'reg_1',
   *     title: 'Reg. 1',
   *     sortable: true,
   *   },
   *   {
   *     name: 'reg_2',
   *     title: 'Reg. 2',
   *     sortable: true,
   *   },
   *   {
   *     name: 'reg_3',
   *     title: 'Reg. 3',
   *     sortable: true,
   *   },
   */
  {
    name: "reference",
    title: SessionUser.objects.orders.columns.reference.label,
    sortable: true,
  },
  {
    name: "notes",
    title: SessionUser.objects.orders.columns.notes.label,
    sortable: true,
  },
  {
    name: "po",
    title: SessionUser.objects.orders.columns.po.label,
    visible: (order) => {
      return canSeePoField() || SessionUser.canAccessAdmin();
    },
  },
  {
    name: "created_at",
    title: SessionUser.objects.orders.columns.created_at.label,
    sortable: true,
  },
  {
    name: "total_net_amount",
    title: t("tables.orders.amount"),
    sortable: false,
  },
  /**
   * {
   *     name: 'completed_at',
   *     title: 'Gennemført',
   *     sortable: true,
   *   },
   */
  {
    name: "actions",
    title: "",
    sortable: false,
  },
]);

const isTableHeaderVisible = (header) => {
  return header.visible === undefined || header.visible(null) === true;
};

const invoiceCollectionSummaryColumnSpan = computed(() => {
  const invoiceControlColumns = (props.invoiceView && props.allowSelectMultiple ? 1 : 0) + (props.invoiceView ? 1 : 0);
  const leadingOrderColumns = tableHeaders.value.filter(
    (header) => isTableHeaderVisible(header) && !["total_net_amount", "actions"].includes(header.name)
  ).length;

  return invoiceControlColumns + leadingOrderColumns;
});

const active_dropdown_object_ids = ref([]);
const toggleDropdown = (object) => {
  // Check if the object is already in the active dropdown list
  if (active_dropdown_object_ids.value.includes(object.id)) {
    // If it is, remove it from the list
    active_dropdown_object_ids.value = active_dropdown_object_ids.value.filter((id) => id !== object.id);
  } else {
    // If it is not, add it to the list
    active_dropdown_object_ids.value.push(object.id);
  }
};
const isDropdownActive = (object) => {
  // If the expanded all prop is true, the active dropdown list should be exclusive instead of inclusive
  // Check if the object is in the active dropdown list
  const isObjectInList = active_dropdown_object_ids.value.includes(object.id);
  return isAutoExpandAll() ? !isObjectInList : isObjectInList;
};

/**
 * Invoice collection selection
 */
const selectedInvoiceCollections = ref([]);
const toggleInvoiceCollectionSelection = (invoiceCollectionId) => {
  const normalizedInvoiceCollectionId = normalizeInvoiceCollectionId(invoiceCollectionId);
  if (normalizedInvoiceCollectionId === null) {
    return;
  }
  // Check if the invoice collection is already selected
  if (selectedInvoiceCollections.value.includes(normalizedInvoiceCollectionId)) {
    // If it is, remove it from the list
    selectedInvoiceCollections.value = selectedInvoiceCollections.value.filter(
      (id) => id !== normalizedInvoiceCollectionId
    );
  } else {
    // If it is not, add it to the list
    selectedInvoiceCollections.value.push(normalizedInvoiceCollectionId);
  }
};

const setInvoiceCollectionSelection = (invoiceCollectionId, checked) => {
  const normalizedInvoiceCollectionId = normalizeInvoiceCollectionId(invoiceCollectionId);
  if (normalizedInvoiceCollectionId === null) {
    return;
  }

  const isSelected = selectedInvoiceCollections.value.includes(normalizedInvoiceCollectionId);
  if ((checked && !isSelected) || (!checked && isSelected)) {
    toggleInvoiceCollectionSelection(normalizedInvoiceCollectionId);
  }
};

const isInvoiceCollectionSelected = (invoiceCollectionId) => {
  const normalizedInvoiceCollectionId = normalizeInvoiceCollectionId(invoiceCollectionId);
  if (normalizedInvoiceCollectionId === null) {
    return false;
  }
  // Check if the invoice collection is in the selected list
  return selectedInvoiceCollections.value.includes(normalizedInvoiceCollectionId);
};
const isInvoiceCollectionSelectedAll = () => {
  // Check if all invoice collections are selected
  return selectedInvoiceCollections.value.length === getUniqueInvoiceCollections().length;
};
const selectAllInvoiceCollections = () => {
  // Check if all invoice collections are selected
  if (isInvoiceCollectionSelectedAll()) {
    // If they are, deselect all
    selectedInvoiceCollections.value = [];
  } else {
    // If they are not, select all
    selectedInvoiceCollections.value = getUniqueInvoiceCollections();
  }
};

const getUniqueInvoiceCollections = () => {
  // Check if there are no orders
  if (props.orders ? props.orders.length === 0 : true) {
    // If there are no orders, return an empty array
    return [];
  }
  // Get a list of unique invoice collections from the orders
  return [
    ...new Set(
      props.orders
        .map((order) => normalizeInvoiceCollectionId(order?.invoice_collection_id))
        .filter((invoiceCollectionId) => invoiceCollectionId !== null)
    ),
  ];
};

const invoiceCollectionQueueInProgress = invoiceQueue.invoiceCollectionQueueInProgress;
const invoiceCollectionQueueFailed = invoiceQueue.invoiceCollectionQueueFailed;
const invoiceCollectionQueueSuccess = invoiceQueue.invoiceCollectionQueueSuccess;
const invoiceCollectionQueue = invoiceQueue.invoiceCollectionQueue;
const collectionQueueLog = invoiceQueue.collectionQueueLog;
const isInvoiceMultipleCollectionsModalOpen = ref(false);
const isSuperuserInvoicesRoute = computed(
  () => route.path === "/superuser/invoices" || route.path.startsWith("/superuser/invoices/")
);
const legacyInvoiceProgressCount = computed(
  () =>
    invoiceCollectionQueueSuccess.value.length +
    invoiceCollectionQueueFailed.value.length +
    invoiceCollectionQueueInProgress.value.length +
    invoiceCollectionQueue.value.length
);
const shouldShowLegacyInvoiceProgressBar = computed(() => {
  return !isSuperuserInvoicesRoute.value && legacyInvoiceProgressCount.value > 0;
});
const isInvoiceQueueBusy = computed(() => {
  return invoiceCollectionQueue.value.length > 0 || invoiceCollectionQueueInProgress.value.length > 0;
});

const getSelectedInvoiceCollectionIds = () =>
  selectedInvoiceCollections.value
    .map((invoiceCollectionId) => normalizeInvoiceCollectionId(invoiceCollectionId))
    .filter((invoiceCollectionId) => invoiceCollectionId !== null);
const selectableInvoiceCollectionCount = computed(() => getUniqueInvoiceCollections().length);

const getBulkActionLabel = (action) => t(`invoicing_period.invoice_collection_actions.actions.${action}`);

const renderBulkActionPreviewHtml = (preview) => {
  const summary = preview?.summary || {};
  const collections = Number(summary.collections ?? preview?.invoice_collection_ids?.length ?? 0);
  const changedCount = Number(summary.changed_count ?? summary.order_items ?? summary.orders_to_move ?? 0);
  const skippedCount = Number(summary.skipped_count ?? 0);
  const blockers = Array.isArray(preview?.blockers) ? preview.blockers : [];
  const orderItems = Array.isArray(preview?.order_items) ? preview.order_items : [];
  const orders = Array.isArray(preview?.orders) ? preview.orders : [];
  const splitItems = Array.isArray(preview?.items) ? preview.items : [];
  const detailItems = [
    ...orderItems.map((item) =>
      t("invoicing_period.invoice_collection_actions.preview.order_item_line", {
        collection: item.invoice_collection_id,
        order: item.order_id,
        product: item.product_name || item.product_id,
      })
    ),
    ...orders.map((item) =>
      t("invoicing_period.invoice_collection_actions.preview.order_move_line", {
        order: item.order_id,
        source: item.source_invoice_collection_id,
        target: item.target_invoice_collection_id,
      })
    ),
    ...splitItems.map((item) =>
      t("invoicing_period.invoice_collection_actions.preview.collection_status_line", {
        collection: item.invoice_collection_id,
        status: item.status,
      })
    ),
  ].slice(0, 10);

  const summaryLines = [
    t("invoicing_period.invoice_collection_actions.preview.collections", { count: collections }),
    t("invoicing_period.invoice_collection_actions.preview.changed", { count: changedCount }),
    ...(skippedCount > 0
      ? [t("invoicing_period.invoice_collection_actions.preview.skipped", { count: skippedCount })]
      : []),
    ...(preview?.target_invoice_collection_id
      ? [
          t("invoicing_period.invoice_collection_actions.preview.merge_target", {
            id: preview.target_invoice_collection_id,
          }),
        ]
      : []),
  ];

  const html = [
    `<p>${escapeHtml(
      t("invoicing_period.invoice_collection_actions.preview.requires_confirmation", {
        phrase: preview?.confirmation_phrase || "",
      })
    )}</p>`,
    `<ul class="has-text-left">${summaryLines.map((line) => `<li>${escapeHtml(line)}</li>`).join("")}</ul>`,
  ];

  if (detailItems.length > 0) {
    html.push(
      `<hr><p class="has-text-left has-text-weight-bold">${escapeHtml(
        t("invoicing_period.invoice_collection_actions.preview.affected_examples")
      )}</p>`
    );
    html.push(`<ul class="has-text-left">${detailItems.map((line) => `<li>${escapeHtml(line)}</li>`).join("")}</ul>`);
  }

  if (blockers.length > 0) {
    html.push(
      `<hr><p class="has-text-left has-text-weight-bold has-text-danger">${escapeHtml(
        t("invoicing_period.invoice_collection_actions.preview.blockers")
      )}</p>`
    );
    html.push(
      `<ul class="has-text-left">${blockers
        .map((blocker) => `<li>${escapeHtml(blocker.message || blocker.code)}</li>`)
        .join("")}</ul>`
    );
  }

  return html.join("");
};

const chooseMergeTargetInvoiceCollection = async (invoiceCollectionIds) => {
  const result = await Swal.fire({
    title: t("invoicing_period.invoice_collection_actions.merge_target_title"),
    input: "select",
    inputOptions: invoiceCollectionIds.reduce(
      (options, invoiceCollectionId) => ({
        ...options,
        [invoiceCollectionId]: `#${invoiceCollectionId}`,
      }),
      {}
    ),
    inputValue: String(invoiceCollectionIds[0] ?? ""),
    showCancelButton: true,
    confirmButtonText: t("common.continue"),
    cancelButtonText: t("common.cancel"),
  });

  if (!result.isConfirmed) {
    return null;
  }

  return normalizeInvoiceCollectionId(result.value);
};

const runInvoiceCollectionBulkAction = async (action) => {
  const invoiceCollectionIds = getSelectedInvoiceCollectionIds();
  if (invoiceCollectionIds.length === 0) {
    return;
  }

  const options = {};
  if (action === INVOICE_COLLECTION_BULK_ACTIONS.MERGE) {
    if (invoiceCollectionIds.length < 2) {
      await Swal.fire({
        icon: "warning",
        title: t("invoicing_period.invoice_collection_actions.merge_requires_multiple_title"),
        text: t("invoicing_period.invoice_collection_actions.merge_requires_multiple_text"),
      });
      return;
    }

    const targetInvoiceCollectionId = await chooseMergeTargetInvoiceCollection(invoiceCollectionIds);
    if (targetInvoiceCollectionId === null) {
      return;
    }
    options.target_invoice_collection_id = targetInvoiceCollectionId;
  }

  try {
    const previewResponse = await SessionUser.objects.collectedOrderInvoices.functions.bulk_action_preview(
      action,
      invoiceCollectionIds,
      options,
      locale.value
    );
    const preview = getApiPayload(previewResponse);
    const blockers = Array.isArray(preview.blockers) ? preview.blockers : [];
    const changedCount = Number(preview?.summary?.changed_count ?? 0);

    if (blockers.length > 0 || changedCount === 0) {
      await Swal.fire({
        icon: blockers.length > 0 ? "error" : "info",
        title:
          blockers.length > 0
            ? t("invoicing_period.invoice_collection_actions.preview.blocked_title")
            : t("invoicing_period.invoice_collection_actions.preview.no_changes_title"),
        html: renderBulkActionPreviewHtml(preview),
      });
      return;
    }

    const confirmation = await Swal.fire({
      icon: "warning",
      title: t("invoicing_period.invoice_collection_actions.preview.title", {
        action: getBulkActionLabel(action),
      }),
      html: renderBulkActionPreviewHtml(preview),
      input: "text",
      inputLabel: t("invoicing_period.invoice_collection_actions.preview.confirmation_label", {
        phrase: preview.confirmation_phrase,
      }),
      inputPlaceholder: preview.confirmation_phrase,
      showCancelButton: true,
      confirmButtonText: t("invoicing_period.invoice_collection_actions.preview.confirm_button"),
      cancelButtonText: t("common.cancel"),
      inputValidator: (value) => {
        if (String(value ?? "").trim() !== String(preview.confirmation_phrase ?? "")) {
          return t("invoicing_period.invoice_collection_actions.preview.confirmation_mismatch", {
            phrase: preview.confirmation_phrase,
          });
        }
        return undefined;
      },
    });

    if (!confirmation.isConfirmed) {
      return;
    }

    const applyResponse = await SessionUser.objects.collectedOrderInvoices.functions.bulk_action_apply({
      preview_id: preview.preview_id,
      action,
      invoice_collection_ids: invoiceCollectionIds,
      options,
      confirmation_text: confirmation.value,
      locale: locale.value,
    });
    const applied = getApiPayload(applyResponse);

    if (action === INVOICE_COLLECTION_BULK_ACTIONS.QUEUE_ECONOMIC) {
      const queuedInvoiceCollectionIds = applied?.result?.queued_invoice_collection_ids || invoiceCollectionIds;
      isInvoiceMultipleCollectionsModalOpen.value = true;
      invoiceQueue.addInvoiceCollectionsToQueue(queuedInvoiceCollectionIds);
      invoiceQueue.processInvoiceCollectionQueue();
    } else {
      selectedInvoiceCollections.value = [];
      await loadList();
    }

    await Swal.fire({
      icon: "success",
      title: t("invoicing_period.invoice_collection_actions.success_title"),
      text: t("invoicing_period.invoice_collection_actions.success_text", {
        count: applied?.result?.changed_count ?? applied?.summary?.changed_count ?? changedCount,
      }),
      timer: 2000,
      showConfirmButton: false,
    });
  } catch (error) {
    await Swal.fire({
      icon: "error",
      title: t("invoicing_period.invoice_collection_actions.error_title"),
      text: SessionUser.functions.parseErrorMessage(error),
    });
  }
};

const invoiceSelectedCollections = () => {
  runInvoiceCollectionBulkAction(INVOICE_COLLECTION_BULK_ACTIONS.QUEUE_ECONOMIC);
};

const retryInvoiceCollection = (invoiceCollectionId) => {
  invoiceQueue.retryInvoiceCollection(parseInt(invoiceCollectionId));
};

const confirmCloseModal = () => {
  Swal.fire({
    title: "Er du sikker på at du vil lukke vinduet?",
    text: "Du vil ikke kunne få den visualiseret igen!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "#3085d6",
    cancelButtonColor: "#d33",
    confirmButtonText: "Ja, luk vinduet!",
  }).then((result) => {
    if (result.isConfirmed) {
      isInvoiceMultipleCollectionsModalOpen.value = false;
    }
  });
};

const ordersSortedByInvoiceCollection = computed(() => {
  // Sort the orders by invoice collection id
  return [...props.orders].sort((a, b) => {
    const leftInvoiceCollectionId = normalizeInvoiceCollectionId(a?.invoice_collection_id) ?? Number.MAX_SAFE_INTEGER;
    const rightInvoiceCollectionId = normalizeInvoiceCollectionId(b?.invoice_collection_id) ?? Number.MAX_SAFE_INTEGER;
    return leftInvoiceCollectionId - rightInvoiceCollectionId;
  });
});

const redirectDepartmentBookingPage = (bookingId, departmentId, newTab = true) => {
  // Send the user to the booking page (In a new tab)
  window.open(`/admin/${departmentId}/modules/pos/bookings/${bookingId}`, newTab ? "_blank" : "_self");
};

const getVisibleOrdersSortedByInvoiceCollection = computed(() => {
  // Get the orders that are visible and sorted by invoice collection id
  return ordersSortedByInvoiceCollection.value.filter((order) => isObjectVisible(order));
});

const getVisibleOrders = computed(() => {
  // Get the orders that are visible
  return props.orders.filter((order) => isObjectVisible(order));
});

const getOrdersByInvoiceCollection = (invoiceCollectionId) => {
  const normalizedInvoiceCollectionId = normalizeInvoiceCollectionId(invoiceCollectionId);
  if (normalizedInvoiceCollectionId === null) {
    return [];
  }
  // If the showOnlyWithIds prop is set, filter the orders by the ids in the array
  if (props.showOnlyWithIds.length > 0) {
    return props.orders.filter(
      (order) =>
        normalizeInvoiceCollectionId(order?.invoice_collection_id) === normalizedInvoiceCollectionId &&
        props.showOnlyWithIds.includes(order.id)
    );
  }
  // Get the orders by invoice collection id
  return props.orders.filter(
    (order) => normalizeInvoiceCollectionId(order?.invoice_collection_id) === normalizedInvoiceCollectionId
  );
};

const isFirstOrderInCollection = (invoiceCollectionId, order) => {
  // Check if the order is the first in the collection
  const ordersInCollection = getOrdersByInvoiceCollection(invoiceCollectionId);
  // Get the first order in the collection
  const firstOrderInCollection = ordersInCollection[0];
  // Check if the current order is the first in the collection
  return firstOrderInCollection?.id === order.id;
};
const invoiceCollectionDetails = ref({}); // Used to provide the invoice collection booked id in the list
const invoiceCollectionOrderCounts = ref({});
const shouldLoadInvoiceCollectionOrderCounts = computed(() => {
  return (
    props.groupInvoiceCollection &&
    SessionUser.canAccessSuperUser() &&
    typeof SessionUser.objects?.collectedOrderInvoices?.get?.single === "function"
  );
});
const resetInvoiceCollectionLookups = () => {
  invoiceCollectionDetails.value = {};
  invoiceCollectionOrderCounts.value = {};
};
const loadInvoiceCollectionOrderCounts = async () => {
  resetInvoiceCollectionLookups();
  if (!shouldLoadInvoiceCollectionOrderCounts.value) {
    return;
  }
  // Get all unique invoice collection ids
  const uniqueInvoiceCollections = getUniqueInvoiceCollections();
  if (uniqueInvoiceCollections.length === 0) {
    return;
  }
  // Loop through each unique invoice collection id
  await Promise.all(
    uniqueInvoiceCollections.map(async (invoiceCollectionId) => {
      try {
        // Get the orders for the invoice collection
        const response = await SessionUser.objects.collectedOrderInvoices.get.single(invoiceCollectionId);
        // Get the orders from the response
        const orders = getInvoiceCollectionResponseOrders(response).filter(
          (order) => props.excludedOrderIds.includes(order.id) === false
        );
        // Set the count for the invoice collection id
        invoiceCollectionOrderCounts.value[invoiceCollectionId] = orders.length;
        invoiceCollectionDetails.value[invoiceCollectionId] = response ?? null;
      } catch (error) {
        console.error("Error loading invoice collection order counts for: " + invoiceCollectionId, error);
        // Set the count for the invoice collection id to 0 if there was an error
        invoiceCollectionOrderCounts.value[invoiceCollectionId] = 0;
        invoiceCollectionDetails.value[invoiceCollectionId] = null;
      }
    })
  );
};
const getInvoiceCollectionOrderCount = (invoiceCollectionId) => {
  const normalizedInvoiceCollectionId = normalizeInvoiceCollectionId(invoiceCollectionId);
  if (normalizedInvoiceCollectionId === null) {
    return 0;
  }
  // Get the count for the invoice collection id
  return invoiceCollectionOrderCounts.value[normalizedInvoiceCollectionId] || 0;
};
const getInvoiceCollectionDetails = (invoiceCollectionId) => {
  const normalizedInvoiceCollectionId = normalizeInvoiceCollectionId(invoiceCollectionId);
  if (normalizedInvoiceCollectionId !== null && invoiceCollectionDetails.value[normalizedInvoiceCollectionId]) {
    return invoiceCollectionDetails.value[normalizedInvoiceCollectionId];
  }
  return null;
};
const getInvoiceCollectionDetailOrders = (invoiceCollectionId) => {
  const details = getInvoiceCollectionDetails(invoiceCollectionId);
  return details ? getInvoiceCollectionResponseOrders(details) : [];
};
const getHiddenOrdersByInvoiceCollection = (invoiceCollectionId) => {
  const visibleOrderIds = new Set(getOrdersByInvoiceCollection(invoiceCollectionId).map((order) => Number(order?.id)));
  return getInvoiceCollectionDetailOrders(invoiceCollectionId).filter(
    (order) => !visibleOrderIds.has(Number(order?.id))
  );
};
const getHiddenOrderIdsByInvoiceCollection = (invoiceCollectionId) =>
  getHiddenOrdersByInvoiceCollection(invoiceCollectionId).map((order) => Number(order?.id));
const getHiddenInvoiceCollectionFlags = (invoiceCollectionId) => {
  const hiddenOrderIds = new Set(getHiddenOrderIdsByInvoiceCollection(invoiceCollectionId));
  if (hiddenOrderIds.size === 0) {
    return [];
  }

  return sortInvoicePeriodFlags(
    (props.invoicePeriodFlags || []).filter((flag) => {
      if (!isActiveInvoicePeriodFlag(flag)) {
        return false;
      }

      const targetType = String(flag?.target_type || "");
      if (!["order", "order_field", "order_item", "order_item_field"].includes(targetType)) {
        return false;
      }

      const flagOrderId = Number(
        flag?.order_id ||
          flag?.context?.order_id ||
          (["order", "order_field"].includes(targetType) ? flag?.target_id : 0)
      );
      return flagOrderId > 0 && hiddenOrderIds.has(flagOrderId);
    })
  );
};
watch(
  [() => props.orders, () => props.excludedOrderIds, () => props.groupInvoiceCollection],
  () => {
    // Load the invoice collection order counts when the orders change
    loadInvoiceCollectionOrderCounts();
  },
  { immediate: true }
);

const isObjectVisible = (object) => {
  if (!SessionUser.canAccessSuperUser() && isSystemOrder(object)) {
    return false; // Hide system orders for non-superusers
  }
  // Check if the object is visible based on the showOnlyWithIds prop
  if (props.showOnlyWithIds.length === 0 && !props.excludedOrderIds.includes(object.id)) {
    return true; // If no filter is applied, show all objects
  } else if (props.excludedOrderIds.includes(object.id)) {
    return false; // If the object is in the excluded list, hide it
  }
  // Check if the object id is in the showOnlyWithIds array
  return props.showOnlyWithIds.includes(object.id);
};
const autoExpandAllToggled = ref(false); // When true, the prop.autoExpandAll value will be reversed. (This is used to toggle the auto expand all button in the UI)

const isAutoExpandAll = () => {
  // Return the opposite of the autoExpandAll prop if the autoExpandAllToggled is true
  return (props.autoExpandAll && !autoExpandAllToggled.value) || (!props.autoExpandAll && autoExpandAllToggled.value);
};

const toggleAutoExpandAll = () => {
  // Toggle the auto expand all state
  autoExpandAllToggled.value = !autoExpandAllToggled.value;
  // Clear the active dropdown list
  // This is to avoid confusion when toggling the auto expand all button
  active_dropdown_object_ids.value = [];
};

const isSystemOrder = (order) => {
  return isSystemUserId(order?.cashier_id);
};

const isPendingHandheld = (order) => {
  return order.pending_handheld === true && order.completed_at === null;
};

const canSeePoField = () => {
  return true;
  //return (SessionUser.hasAttribute('usePONumbers') || SessionUser.hasPermission('department'))
};

const sortInvoicePeriodFlags = (flags = []) =>
  [...flags].sort((left, right) => {
    const sourceOrder = { manual: 0, automatic: 1 };
    const leftSource = sourceOrder[left?.source] ?? 99;
    const rightSource = sourceOrder[right?.source] ?? 99;
    if (leftSource !== rightSource) {
      return leftSource - rightSource;
    }

    return String(left?.created_at || left?.fingerprint || "").localeCompare(
      String(right?.created_at || right?.fingerprint || "")
    );
  });
const isActiveInvoicePeriodFlag = (flag) => String(flag?.status || "active") === "active";
const getOrderLineFlags = (order) =>
  sortInvoicePeriodFlags(
    (props.invoicePeriodFlags || []).filter((flag) => {
      if (!isActiveInvoicePeriodFlag(flag)) {
        return false;
      }

      const targetType = String(flag?.target_type || "");
      if (!["order", "order_field"].includes(targetType)) {
        return false;
      }

      const flagOrderId = Number(flag?.order_id || flag?.target_id || 0);
      return flagOrderId > 0 && flagOrderId === Number(order?.id || 0);
    })
  );
const getOrderItemLineFlags = (order) =>
  sortInvoicePeriodFlags(
    (props.invoicePeriodFlags || []).filter((flag) => {
      if (!isActiveInvoicePeriodFlag(flag)) {
        return false;
      }

      const targetType = String(flag?.target_type || "");
      if (!["order_item", "order_item_field"].includes(targetType)) {
        return false;
      }

      return Number(flag?.order_id || flag?.context?.order_id || 0) === Number(order?.id || 0);
    })
  );
const getOrderContainedFlags = (order) =>
  sortInvoicePeriodFlags([...getOrderLineFlags(order), ...getOrderItemLineFlags(order)]);
const getOrderIndicatorIconClass = (order) => {
  if (getOrderContainedFlags(order).length > 0) {
    return "fas fa-flag";
  }

  return isPendingHandheld(order) ? "fas fa-mobile-alt" : "fas fa-circle";
};
const getOrderIndicatorColorClass = (order) => {
  const flags = getOrderContainedFlags(order);
  if (flags.length === 0) {
    return getOrderInvoiceStatusBarColor(order);
  }

  return flags.some((flag) => flag?.source === "manual") ? "has-text-danger" : "has-text-warning";
};
const emitFlagStatusChanged = (flag) => emit("flagStatusChanged", flag);
const emitFlagCreated = (flag) => emit("flagCreated", flag);

/**
 * Order actions modal
 */
const selectedOrderForActionsMenu = ref(null);
const isOrderActionsModalOpen = computed(() => {
  return selectedOrderForActionsMenu.value !== null;
});
const closeOrderActionsModal = () => {
  selectedOrderForActionsMenu.value = null;
};
const openOrderActionsModal = (order) => {
  selectedOrderForActionsMenu.value = order;
};
const selectedOrderForDraftAssignment = ref(null);
const isDraftAssignmentModalOpen = computed(() => {
  return selectedOrderForDraftAssignment.value !== null;
});

const canEditTransaction = (order) => {
  if (props.isCustomerView) {
    return SessionUser.canAccessCustomerFeature("orders", "edit");
  }

  return SessionUser.canAccessAdmin() || SessionUser.canAccessDepartment(order.department_id);
};

const currentRoutePath = computed(() => {
  const resolvedRoutePath = route && typeof route === "object" ? route.path || route.fullPath || route.name || "" : "";

  if (resolvedRoutePath) {
    return String(resolvedRoutePath);
  }

  if (typeof window !== "undefined") {
    return String(window.location.pathname || "");
  }

  return "";
});

const shouldShowDraftAssignmentActions = computed(() => {
  return Boolean(props.showDraftAssignmentActions) || currentRoutePath.value.includes("/modules/pos/drafts");
});

const canShowDraftAssignmentAction = () => {
  return shouldShowDraftAssignmentActions.value;
};

const closeDraftAssignmentModal = () => {
  selectedOrderForDraftAssignment.value = null;
};

const openDraftAssignmentModal = (order) => {
  if (!canShowDraftAssignmentAction()) {
    return;
  }

  closeOrderActionsModal();
  selectedOrderForDraftAssignment.value = order;
};

const handleDraftAssignmentSuccess = async () => {
  closeDraftAssignmentModal();
  await loadList();
  dispatchNavigationCountRefresh();
  await Swal.fire({
    icon: "success",
    title: t("admin.pos.drafts_assignment.success"),
    timer: 1800,
    showConfirmButton: false,
  });
};

/**
 * Cashier name formatting
 * This:
 * - Writes "afdeling" if the cashiers name is the same as the department name.
 * - Returns the first name, and first letter of the lastname of the cashier.
 */
const formatCashierName = (order) => {
  if (getDepartmentName(order.department_id) === order.cashier_name) {
    return SessionUser.functions.ucFirst(SessionUser.objects.departments.meta.labels.single);
  }
  return order.cashier_name;
};

const __returned__ = { t, locale, props, emit, orderBy, orderDirection, setOrder, loadList, route, redirectDepartmentOrderPage, redirectSuperUserInvoiceCollectionPage, getEconomicInvoiceModule, getStripeInvoiceModule, getInvoiceCollection, isOrderInvoicedWithEconomic, isOrderEconomicInvoiceBooked, isOrderInvoicedWithStripe, isOrderInvoiced, doesOrderHaveInvoiceCollection, isOrderInvoiceCollectionClosed, isOrderInvoiceCollectionBooked, isOrderStripeInvoicePaid, doesOrderHaveErrorMessage, getOrderInvoiceStatusBarColor, getOrderInvoiceStatusContent, getOrderInvoiceStatusTitle, clickUser, truncateOrderField, normalizeInvoiceCollectionId, getApiPayload, escapeHtml, getInvoiceCollectionResponseOrders, isColumnCurrentlyBeingSortedBy, isCurrentSortDirectionAscending, isCurrentSortDirectionDescending, onTableHeaderClick, tableHeaders, isTableHeaderVisible, invoiceCollectionSummaryColumnSpan, active_dropdown_object_ids, toggleDropdown, isDropdownActive, selectedInvoiceCollections, toggleInvoiceCollectionSelection, setInvoiceCollectionSelection, isInvoiceCollectionSelected, isInvoiceCollectionSelectedAll, selectAllInvoiceCollections, getUniqueInvoiceCollections, invoiceCollectionQueueInProgress, invoiceCollectionQueueFailed, invoiceCollectionQueueSuccess, invoiceCollectionQueue, collectionQueueLog, isInvoiceMultipleCollectionsModalOpen, isSuperuserInvoicesRoute, legacyInvoiceProgressCount, shouldShowLegacyInvoiceProgressBar, isInvoiceQueueBusy, getSelectedInvoiceCollectionIds, selectableInvoiceCollectionCount, getBulkActionLabel, renderBulkActionPreviewHtml, chooseMergeTargetInvoiceCollection, runInvoiceCollectionBulkAction, invoiceSelectedCollections, retryInvoiceCollection, confirmCloseModal, ordersSortedByInvoiceCollection, redirectDepartmentBookingPage, getVisibleOrdersSortedByInvoiceCollection, getVisibleOrders, getOrdersByInvoiceCollection, isFirstOrderInCollection, invoiceCollectionDetails, invoiceCollectionOrderCounts, shouldLoadInvoiceCollectionOrderCounts, resetInvoiceCollectionLookups, loadInvoiceCollectionOrderCounts, getInvoiceCollectionOrderCount, getInvoiceCollectionDetails, getInvoiceCollectionDetailOrders, getHiddenOrdersByInvoiceCollection, getHiddenOrderIdsByInvoiceCollection, getHiddenInvoiceCollectionFlags, isObjectVisible, autoExpandAllToggled, isAutoExpandAll, toggleAutoExpandAll, isSystemOrder, isPendingHandheld, canSeePoField, sortInvoicePeriodFlags, isActiveInvoicePeriodFlag, getOrderLineFlags, getOrderItemLineFlags, getOrderContainedFlags, getOrderIndicatorIconClass, getOrderIndicatorColorClass, emitFlagStatusChanged, emitFlagCreated, selectedOrderForActionsMenu, isOrderActionsModalOpen, closeOrderActionsModal, openOrderActionsModal, selectedOrderForDraftAssignment, isDraftAssignmentModalOpen, canEditTransaction, currentRoutePath, shouldShowDraftAssignmentActions, canShowDraftAssignmentAction, closeDraftAssignmentModal, openDraftAssignmentModal, handleDraftAssignmentSuccess, formatCashierName, get useI18n() { return useI18n }, get BCheckbox() { return BCheckbox }, ActionSettingsWheelButton, InvoiceCollectionSelectionActionWheel, OrderAttachmentsActionButton, AssignDraftOrderCustomerModal, InvoicingPeriodFlagList, get INVOICE_COLLECTION_BULK_ACTIONS() { return INVOICE_COLLECTION_BULK_ACTIONS }, SuperuserInvoiceRowActions, get useLargeTableHeaders() { return useLargeTableHeaders }, computed, onMounted, ref, watch, get useRoute() { return useRoute }, departments, getDepartments, isLoading, getDepartmentName, showPopper, removePopperIfOpen, popperBox, SessionUser, usePaginatedListInstance, OrderContentTable, InvoiceMultipleCollectionsModal, get Swal() { return Swal }, ColorIndicator, InvoicingBillingPeriodInvoiceProgressBar, invoiceQueue, PosDepartmentStepMobileAttachment, EditableTableColumn, ViewportResponsiveWrapper, WhiteBoxCard, get dispatchNavigationCountRefresh() { return dispatchNavigationCountRefresh }, get isSystemUserId() { return isSystemUserId } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$a = { class: "table is-fullwidth" };
const _hoisted_2$8 = { key: 0 };
const _hoisted_3$8 = { colspan: "100%" };
const _hoisted_4$8 = {
  key: 0,
  class: "is-narrow pos-orders-table-leading-control-header pos-orders-table-selector-header"
};
const _hoisted_5$7 = {
  key: 1,
  class: "is-narrow pos-orders-table-leading-control-header pos-orders-table-collapse-header"
};
const _hoisted_6$7 = ["onClick"];
const _hoisted_7$7 = { class: "is-flex-wrap-nowrap pleno-table-header-content" };
const _hoisted_8$7 = { class: "has-text-weight-bold pos-orders-table-header__label" };
const _hoisted_9$6 = { class: "is-flex-wrap-nowrap pleno-table-header-content" };
const _hoisted_10$5 = { class: "has-text-weight-bold pos-orders-table-header__label" };
const _hoisted_11$5 = ["data-testid"];
const _hoisted_12$4 = ["colspan", "data-testid"];
const _hoisted_13$3 = { class: "has-text-weight-bold" };
const _hoisted_14$3 = { class: "has-text-grey" };
const _hoisted_15$3 = ["data-testid"];
const _hoisted_16$3 = { class: "has-text-weight-bold" };
const _hoisted_17$2 = { class: "is-narrow" };
const _hoisted_18$2 = { key: 0 };
const _hoisted_19$2 = { colspan: "100%" };
const _hoisted_20$1 = { class: "message is-warning" };
const _hoisted_21$1 = { class: "message-body" };
const _hoisted_22$1 = { class: "has-text-weight-bold" };
const _hoisted_23$1 = {
  key: 0,
  class: "is-narrow pos-orders-table-leading-control-cell pos-order-invoice-collection-selector-cell"
};
const _hoisted_24$1 = {
  key: 1,
  class: "is-narrow pos-orders-table-leading-control-cell pos-orders-table-collapse-cell"
};
const _hoisted_25$1 = ["data-testid", "onClick"];
const _hoisted_26$1 = { class: "is-narrow pos-orders-table-id-cell pos-orders-table-compact-text-cell" };
const _hoisted_27$1 = { class: "pos-orders-table-id-cell-content" };
const _hoisted_28$1 = {
  key: 2,
  class: "pos-orders-table-customer-cell pos-orders-table-compact-text-cell"
};
const _hoisted_29$1 = {
  key: 3,
  class: "pos-orders-table-compact-text-cell"
};
const _hoisted_30$1 = {
  key: 1,
  class: "has-text-grey-light"
};
const _hoisted_31$1 = { class: "pos-orders-table-compact-text-cell" };
const _hoisted_32$1 = { class: "pos-order-vehicle-cell" };
const _hoisted_33$1 = { class: "pos-order-vehicle-registration-line" };
const _hoisted_34$1 = {
  key: 0,
  class: "pos-order-vehicle-registration-line"
};
const _hoisted_35$1 = {
  key: 1,
  class: "pos-order-vehicle-registration-separator"
};
const _hoisted_36$1 = { class: "pos-orders-table-date-cell" };
const _hoisted_37$1 = { class: "pos-orders-table-amount-cell" };
const _hoisted_38$1 = { class: "is-narrow pos-orders-table-actions-cell" };
const _hoisted_39$1 = ["data-testid", "onClick"];
const _hoisted_40$1 = ["data-testid"];
const _hoisted_41$1 = { colspan: "100%" };
const _hoisted_42$1 = { key: 3 };
const _hoisted_43$1 = { colspan: "100%" };
const _hoisted_44$1 = { class: "content" };
const _hoisted_45$1 = { colspan: "100%" };
const _hoisted_46$1 = { class: "columns is-multiline is-mobile" };
const _hoisted_47$1 = {
  key: 0,
  class: "column is-full"
};
const _hoisted_48$1 = {
  class: "card-header-title is-flex is-justify-content-space-between is-align-items-center",
  style: {"width":"100%"}
};
const _hoisted_49$1 = { key: 0 };
const _hoisted_50$1 = {
  class: "is-pulled-right",
  style: {"width":"fit-content"}
};
const _hoisted_51$1 = { class: "columns is-multiline is-mobile is-gapless is-justify-content-flex-end is-align-items-center" };
const _hoisted_52$1 = { class: "column is-narrow has-text-right mb-2" };
const _hoisted_53$1 = { class: "tag is-light is-small mr-1" };
const _hoisted_54$1 = { class: "column is-12 has-text-right mb-2" };
const _hoisted_55$1 = { class: "pos-order-invoice-collection-selector-wrapper mr-1" };
const _hoisted_56$1 = { class: "card-content" };
const _hoisted_57$1 = { class: "columns is-mobile is-multiline" };
const _hoisted_58$1 = { class: "column is-12" };
const _hoisted_59$1 = { key: 0 };
const _hoisted_60$1 = { key: 1 };
const _hoisted_61$1 = { class: "column is-12" };
const _hoisted_62$1 = { class: "column is-12" };
const _hoisted_63$1 = {
  key: 0,
  class: "column is-12"
};
const _hoisted_64 = {
  key: 1,
  class: "column is-12"
};
const _hoisted_65 = { class: "has-text-warning" };
const _hoisted_66 = { class: "buttons is-right" };
const _hoisted_67 = ["data-testid", "onClick"];
const _hoisted_68 = {
  key: 0,
  class: "content"
};
const _hoisted_69 = { class: "column is-full" };
const _hoisted_70 = { class: "has-text-centered" };
const _hoisted_71 = { class: "columns is-multiline is-mobile" };
const _hoisted_72 = {
  key: 0,
  class: "column is-full"
};
const _hoisted_73 = ["data-testid"];
const _hoisted_74 = { class: "message is-light mb-0" };
const _hoisted_75 = ["data-testid"];
const _hoisted_76 = { class: "has-text-weight-bold" };
const _hoisted_77 = { class: "has-text-weight-bold" };
const _hoisted_78 = ["data-testid"];
const _hoisted_79 = { class: "column is-full" };
const _hoisted_80 = {
  class: "card-header-title is-flex is-justify-content-space-between is-align-items-center",
  style: {"width":"100%"}
};
const _hoisted_81 = { key: 0 };
const _hoisted_82 = { key: 1 };
const _hoisted_83 = { class: "has-text-grey-light" };
const _hoisted_84 = { key: 0 };
const _hoisted_85 = {
  class: "is-pulled-right",
  style: {"width":"fit-content"}
};
const _hoisted_86 = { class: "columns is-multiline is-mobile is-gapless is-justify-content-flex-end is-align-items-center" };
const _hoisted_87 = { class: "column is-narrow has-text-right mb-2" };
const _hoisted_88 = { class: "tag is-light is-small mr-1" };
const _hoisted_89 = { class: "column is-12 has-text-right mb-2" };
const _hoisted_90 = { class: "pos-order-invoice-collection-selector-wrapper mr-1" };
const _hoisted_91 = { class: "card-content" };
const _hoisted_92 = { class: "columns is-mobile is-multiline" };
const _hoisted_93 = { class: "column is-12" };
const _hoisted_94 = {
  key: 0,
  class: "columns is-mobile is-gapless is-align-items-center mb-1"
};
const _hoisted_95 = { class: "column is-narrow mr-1" };
const _hoisted_96 = { class: "label is-small" };
const _hoisted_97 = { class: "column is-flex-grow-1" };
const _hoisted_98 = {
  key: 1,
  class: "columns is-mobile is-gapless is-align-items-center mb-1"
};
const _hoisted_99 = { class: "column is-narrow mr-1" };
const _hoisted_100 = { class: "column is-flex-grow-1" };
const _hoisted_101 = {
  key: 2,
  class: "columns is-mobile is-gapless is-align-items-center mb-1"
};
const _hoisted_102 = { class: "column is-narrow mr-1" };
const _hoisted_103 = { class: "column is-flex-grow-1" };
const _hoisted_104 = { key: 3 };
const _hoisted_105 = { class: "column is-12 has-text-centered" };
const _hoisted_106 = { class: "has-text-grey" };
const _hoisted_107 = { class: "has-text-grey" };
const _hoisted_108 = { class: "columns is-mobile is-gapless is-justify-content-center is-align-items-center" };
const _hoisted_109 = { class: "column is-narrow" };
const _hoisted_110 = {
  key: 0,
  class: "columns is-mobile is-gapless is-align-items-center"
};
const _hoisted_111 = { class: "column is-flex-grow-1" };
const _hoisted_112 = {
  key: 0,
  class: "column"
};
const _hoisted_113 = {
  key: 1,
  class: "column is-narrow"
};
const _hoisted_114 = {
  key: 0,
  class: "columns is-mobile is-gapless is-align-items-center"
};
const _hoisted_115 = { class: "column is-flex-grow-1" };
const _hoisted_116 = {
  key: 2,
  class: "column"
};
const _hoisted_117 = {
  key: 3,
  class: "column is-narrow"
};
const _hoisted_118 = {
  key: 0,
  class: "columns is-mobile is-gapless is-align-items-center"
};
const _hoisted_119 = { class: "column is-flex-grow-1" };
const _hoisted_120 = ["onClick", "data-testid"];
const _hoisted_121 = ["onClick"];
const _hoisted_122 = ["onClick"];
const _hoisted_123 = { class: "column is-full" };
const _hoisted_124 = { class: "has-text-centered" };
const _hoisted_125 = { class: "modal-card" };
const _hoisted_126 = { class: "modal-card-head" };
const _hoisted_127 = { class: "modal-card-title" };
const _hoisted_128 = { class: "modal-card-body" };
const _hoisted_129 = ["data-testid"];
const _hoisted_130 = { class: "modal-card-foot" };

function _sfc_render$a(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock(Fragment, null, [
    createVNode($setup["ViewportResponsiveWrapper"], null, {
      desktop: withCtx(() => [
        createBaseVNode("table", _hoisted_1$a, [
          createBaseVNode("thead", null, [
            ($setup.props.invoiceView && $setup.props.allowSelectMultiple)
              ? (openBlock(), createElementBlock("tr", _hoisted_2$8, [
                  createBaseVNode("td", _hoisted_3$8, [
                    createVNode($setup["InvoiceCollectionSelectionActionWheel"], {
                      "selected-invoice-collection-ids": $setup.selectedInvoiceCollections,
                      "total-invoice-collection-count": $setup.selectableInvoiceCollectionCount,
                      "all-selected": $setup.isInvoiceCollectionSelectedAll(),
                      "all-expanded": $setup.isAutoExpandAll(),
                      "invoice-queue-busy": $setup.isInvoiceQueueBusy,
                      onInvoiceSelected: $setup.invoiceSelectedCollections,
                      onBulkAction: $setup.runInvoiceCollectionBulkAction,
                      onToggleSelectAll: $setup.selectAllInvoiceCollections,
                      onToggleExpandAll: $setup.toggleAutoExpandAll
                    }, null, 8 /* PROPS */, ["selected-invoice-collection-ids", "total-invoice-collection-count", "all-selected", "all-expanded", "invoice-queue-busy"])
                  ])
                ]))
              : createCommentVNode("v-if", true),
            createBaseVNode("tr", null, [
              ($setup.props.invoiceView && $setup.props.allowSelectMultiple)
                ? (openBlock(), createElementBlock("th", _hoisted_4$8))
                : createCommentVNode("v-if", true),
              ($setup.props.invoiceView)
                ? (openBlock(), createElementBlock("th", _hoisted_5$7))
                : createCommentVNode("v-if", true),
              (openBlock(true), createElementBlock(Fragment, null, renderList($setup.tableHeaders, (tableHeaders) => {
                return (openBlock(), createElementBlock(Fragment, { key: tableHeaders }, [
                  (tableHeaders.visible === undefined || tableHeaders.visible(null) === true)
                    ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                        (tableHeaders.sortable)
                          ? (openBlock(), createElementBlock("th", {
                              key: 0,
                              class: normalizeClass({
                    'is-clickable': tableHeaders.sortable,
                    'is-narrow': ['id', 'reg_1', 'actions'].includes(tableHeaders.name),
                    'pos-orders-table-header--compact': !$setup.useLargeTableHeaders,
                    'pos-orders-table-id-header': tableHeaders.name === 'id',
                    'pos-orders-table-header--vehicles': tableHeaders.name === 'reg_1',
                  }),
                              onClick: $event => ($setup.onTableHeaderClick(tableHeaders.name))
                            }, [
                              createBaseVNode("span", _hoisted_7$7, [
                                createBaseVNode("span", _hoisted_8$7, toDisplayString(tableHeaders.title), 1 /* TEXT */),
                                ($setup.isColumnCurrentlyBeingSortedBy(tableHeaders.name))
                                  ? (openBlock(), createElementBlock("span", {
                                      key: 0,
                                      class: normalizeClass([{
                        'fas fa-sort-up': $setup.isCurrentSortDirectionAscending(),
                        'fas fa-sort-down': $setup.isCurrentSortDirectionDescending(),
                      }, "icon is-small"])
                                    }, null, 2 /* CLASS */))
                                  : createCommentVNode("v-if", true)
                              ])
                            ], 10 /* CLASS, PROPS */, _hoisted_6$7))
                          : (openBlock(), createElementBlock("th", {
                              key: 1,
                              class: normalizeClass({
                    'is-narrow': ['id', 'reg_1', 'actions'].includes(tableHeaders.name),
                    'pos-orders-table-header--compact': !$setup.useLargeTableHeaders,
                    'pos-orders-table-id-header': tableHeaders.name === 'id',
                    'pos-orders-table-header--vehicles': tableHeaders.name === 'reg_1',
                  })
                            }, [
                              createBaseVNode("span", _hoisted_9$6, [
                                createBaseVNode("span", _hoisted_10$5, toDisplayString(tableHeaders.title), 1 /* TEXT */)
                              ])
                            ], 2 /* CLASS */))
                      ], 64 /* STABLE_FRAGMENT */))
                    : createCommentVNode("v-if", true)
                ], 64 /* STABLE_FRAGMENT */))
              }), 128 /* KEYED_FRAGMENT */))
            ])
          ]),
          createBaseVNode("tbody", null, [
            (openBlock(true), createElementBlock(Fragment, null, renderList($setup.props.groupInvoiceCollection ? $setup.getVisibleOrdersSortedByInvoiceCollection : $setup.getVisibleOrders, (order) => {
              return (openBlock(), createElementBlock(Fragment, {
                key: order.id
              }, [
                createCommentVNode(" If grouping by invoice collection is enabled, show the invoice collection id "),
                (
                $setup.props.groupInvoiceCollection &&
                $setup.doesOrderHaveInvoiceCollection(order) &&
                $setup.isFirstOrderInCollection(order.invoice_collection_id, order)
              )
                  ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                      createBaseVNode("tr", {
                        "data-testid": `pos-order-invoice-collection-row-${order.invoice_collection_id}`
                      }, [
                        createBaseVNode("td", {
                          colspan: $setup.invoiceCollectionSummaryColumnSpan,
                          "data-testid": `pos-order-invoice-collection-summary-${order.invoice_collection_id}`
                        }, [
                          createBaseVNode("div", _hoisted_13$3, [
                            createTextVNode(" Faktura samling ID: " + toDisplayString(order.invoice_collection_id) + " ", 1 /* TEXT */),
                            createBaseVNode("span", _hoisted_14$3, "( " + toDisplayString($setup.SessionUser.objects.global.language.showing) + " " + toDisplayString($setup.getOrdersByInvoiceCollection(order.invoice_collection_id).length) + " " + toDisplayString($setup.SessionUser.objects.global.language.showing_of_separator) + " " + toDisplayString($setup.getInvoiceCollectionOrderCount(order.invoice_collection_id)) + " " + toDisplayString($setup.SessionUser.objects.orders.meta.labels.multiple.toLowerCase()) + " )", 1 /* TEXT */)
                          ])
                        ], 8 /* PROPS */, _hoisted_12$4),
                        createBaseVNode("td", {
                          class: "has-text-right",
                          "data-testid": `pos-order-invoice-collection-total-${order.invoice_collection_id}`
                        }, [
                          createCommentVNode(" Total net amount for the invoice collection "),
                          createBaseVNode("span", _hoisted_16$3, toDisplayString($setup.SessionUser.functions.currency.toLocal(
                        $setup.getOrdersByInvoiceCollection(order.invoice_collection_id)
                          .reduce((sum, order) => sum + order.total_net_amount, 0)
                          .toFixed(2)
                      )), 1 /* TEXT */)
                        ], 8 /* PROPS */, _hoisted_15$3),
                        createCommentVNode(" Actions for the invoice collection "),
                        createBaseVNode("td", _hoisted_17$2, [
                          createVNode($setup["SuperuserInvoiceRowActions"], { "include-buffer": true }, {
                            default: withCtx(() => [
                              createVNode($setup["ActionSettingsWheelButton"], {
                                invoice_collection_id: order.invoice_collection_id
                              }, {
                                actions: withCtx(() => [...(_cache[6] || (_cache[6] = []))]),
                                _: 1 /* STABLE */
                              }, 8 /* PROPS */, ["invoice_collection_id"])
                            ]),
                            _: 2 /* DYNAMIC */
                          }, 1024 /* DYNAMIC_SLOTS */)
                        ])
                      ], 8 /* PROPS */, _hoisted_11$5),
                      createCommentVNode(" Warning, if there's orders in the collection that are filtered out "),
                      (
                  $setup.getInvoiceCollectionOrderCount(order.invoice_collection_id) >
                  $setup.getOrdersByInvoiceCollection(order.invoice_collection_id).length
                )
                        ? (openBlock(), createElementBlock("tr", _hoisted_18$2, [
                            createBaseVNode("td", _hoisted_19$2, [
                              createBaseVNode("div", _hoisted_20$1, [
                                createBaseVNode("div", _hoisted_21$1, [
                                  _cache[7] || (_cache[7] = createBaseVNode("span", { class: "has-text-weight-bold" }, "Bemærk:", -1 /* CACHED */)),
                                  _cache[8] || (_cache[8] = createTextVNode(" Der er ordrer i denne faktura samling, som ikke er synlige pga. filtre. ", -1 /* CACHED */)),
                                  _cache[9] || (_cache[9] = createBaseVNode("br", null, null, -1 /* CACHED */)),
                                  createBaseVNode("span", _hoisted_22$1, "Disse " + toDisplayString($setup.getInvoiceCollectionOrderCount(order.invoice_collection_id) -
                          $setup.getOrdersByInvoiceCollection(order.invoice_collection_id).length) + " er ikke vist, men vil muligvis blive faktureret alligevel.", 1 /* TEXT */),
                                  ($setup.getHiddenInvoiceCollectionFlags(order.invoice_collection_id).length > 0)
                                    ? (openBlock(), createBlock($setup["InvoicingPeriodFlagList"], {
                                        key: 0,
                                        class: "mt-3",
                                        compact: "",
                                        flags: $setup.getHiddenInvoiceCollectionFlags(order.invoice_collection_id),
                                        onStatusChanged: $setup.emitFlagStatusChanged
                                      }, null, 8 /* PROPS */, ["flags"]))
                                    : createCommentVNode("v-if", true)
                                ])
                              ])
                            ])
                          ]))
                        : createCommentVNode("v-if", true)
                    ], 64 /* STABLE_FRAGMENT */))
                  : createCommentVNode("v-if", true),
                ($setup.isObjectVisible(order))
                  ? (openBlock(), createElementBlock("tr", {
                      key: 1,
                      class: normalizeClass(["pos-orders-table-row", { 'has-background-info-light': $setup.isSystemOrder(order) }])
                    }, [
                      ($setup.props.invoiceView && $setup.props.allowSelectMultiple)
                        ? (openBlock(), createElementBlock("td", _hoisted_23$1, [
                            createVNode($setup["BCheckbox"], {
                              class: "pos-order-invoice-collection-selector",
                              "model-value": $setup.isInvoiceCollectionSelected(order.invoice_collection_id),
                              disabled: $setup.normalizeInvoiceCollectionId(order.invoice_collection_id) === null,
                              "aria-label": `${
                      $setup.SessionUser.objects.global.language.select
                    } ${$setup.SessionUser.objects.global.language.invoice.toLowerCase()} #${
                      order.invoice_collection_id || order.id
                    }`,
                              "data-testid": `pos-order-invoice-collection-selector-${order.id}`,
                              "onUpdate:modelValue": 
                      (checked) => $setup.setInvoiceCollectionSelection(order.invoice_collection_id, checked)
                    
                            }, null, 8 /* PROPS */, ["model-value", "disabled", "aria-label", "data-testid", "onUpdate:modelValue"])
                          ]))
                        : createCommentVNode("v-if", true),
                      ($setup.props.invoiceView)
                        ? (openBlock(), createElementBlock("td", _hoisted_24$1, [
                            createBaseVNode("button", {
                              class: "button is-small",
                              "data-testid": `pos-order-expand-${order.id}`,
                              onClick: $event => ($setup.toggleDropdown(order))
                            }, [
                              createBaseVNode("span", {
                                class: normalizeClass(["icon", $setup.isDropdownActive(order) ? 'has-text-link' : '']),
                                style: normalizeStyle($setup.isDropdownActive(order) ? 'transform: rotate(90deg);' : '')
                              }, [
                                createCommentVNode(" Dropdown icon "),
                                _cache[10] || (_cache[10] = createBaseVNode("i", { class: "fas fa-angle-right" }, null, -1 /* CACHED */))
                              ], 6 /* CLASS, STYLE */)
                            ], 8 /* PROPS */, _hoisted_25$1)
                          ]))
                        : createCommentVNode("v-if", true),
                      createBaseVNode("td", _hoisted_26$1, [
                        createBaseVNode("div", _hoisted_27$1, [
                          createVNode($setup["ColorIndicator"], {
                            color_class: $setup.getOrderIndicatorColorClass(order),
                            icon_class: $setup.getOrderIndicatorIconClass(order),
                            is_narrow: true,
                            label: {
                      text: order.id,
                      classes: [],
                      max_length: 7,
                    },
                            visibility: {
                      icon: true,
                      dropdown: true,
                    },
                            dropdown_content: {
                      title: null,
                      buttons_title: null,
                      content: [
                        // Transaction
                        {
                          text: $setup.SessionUser.functions.ucFirst($setup.SessionUser.objects.orders.meta.labels.single),
                          action: () => {
                            $setup.redirectDepartmentOrderPage(order.id, order.department_id);
                          },
                          ...($setup.SessionUser.canAccessSuperUser() ? {} : { disabled: true }),
                          button_classes: ['no-underline-text', 'is-text'],
                          button: true,
                          button_text: order.id,
                          v_centered: true,
                        },
                        // Invoice collection
                        {
                          text:
                            $setup.SessionUser.objects.global.language.invoice +
                            ' ' +
                            $setup.SessionUser.objects.global.language.collection.toLowerCase(),
                          action: () => {
                            $setup.redirectSuperUserInvoiceCollectionPage(order.invoice_collection_id);
                          },
                          ...($setup.SessionUser.canAccessSuperUser() ? {} : { disabled: true }),
                          button_classes: ['no-underline-text', 'is-text'],
                          button: true,
                          button_text: order.invoice_collection_id,
                          v_centered: true,
                        },
                        /**
                         * // Completed status
                         *                     {
                         *                       text: SessionUser.objects.orders.columns.completed_at.label,
                         *                       action: () => {
                         *                         redirectDepartmentOrderPage(order.id, order.department_id);
                         *                       },
                         *                       ...(SessionUser.canAccessSuperUser() ? {} : { disabled: true }),
                         *                       button_classes: ['no-underline-text', 'is-text', ...(order.completed_at !== null ? [] : ['has-text-warning'])],
                         *                       button: true,
                         *                       button_text: (order.completed_at !== null ? SessionUser.objects.global.language.yes : SessionUser.objects.global.language.no),
                         *                       v_centered: true,
                         *                     },
                         */

                        // Handheld status
                        ...($setup.isPendingHandheld(order)
                          ? [
                              {
                                text: $setup.SessionUser.objects.global.language.handheld_pending_order,
                                action: () => {},
                                button_classes: ['no-underline-text', 'is-text', 'has-text-warning'],
                                button: true,
                                button_text: $setup.SessionUser.objects.global.language.confirmation_needed,
                                v_centered: true,
                              },
                            ]
                          : []),
                      ],
                      buttons: [],
                    }
                          }, null, 8 /* PROPS */, ["color_class", "icon_class", "label", "dropdown_content"])
                        ])
                      ]),
                      (!$setup.props.isCustomerView)
                        ? (openBlock(), createElementBlock("td", _hoisted_28$1, [
                            createVNode($setup["ColorIndicator"], {
                              label: {
                    text: order.customer_name,
                    classes: ['pos-orders-table-customer-name'],
                    max_length: 48,
                  },
                              visibility: {
                    icon: false,
                    dropdown: true,
                  },
                              dropdown_content: {
                    title: null,
                    buttons_title: null,
                    content: [
                      {
                        text: order.customer_name,
                        action: () => {
                          $setup.clickUser(order.customer_id);
                        },
                        ...($setup.SessionUser.canAccessSuperUser() ? {} : { disabled: true }),
                        button: true,
                        button_text: 'Vis kunde',
                      },
                    ],
                    buttons: [],
                  }
                            }, null, 8 /* PROPS */, ["label", "dropdown_content"])
                          ]))
                        : createCommentVNode("v-if", true),
                      createCommentVNode("\n        <td>\n          <span\n              @mouseover=\"showPopper(\n                              popperBox(\n                                  'Customer ID',\n                                  order.customer_id,\n                                  ),\n                                  $event.target\n                              )\"\n              @mouseleave=\"removePopperIfOpen()\"\n              @click=\"clickUser(order.customer_id)\"\n              :class=\"{ 'is-clickable': SessionUser.canAccessSuperUser() }\"\n              >\n        {{ order.customer_name }}\n      </span>\n        </td> "),
                      (!$setup.props.isCustomerView)
                        ? (openBlock(), createElementBlock("td", _hoisted_29$1, [
                            (!$setup.isSystemOrder(order))
                              ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                                  createTextVNode(toDisplayString($setup.formatCashierName(order)), 1 /* TEXT */)
                                ], 64 /* STABLE_FRAGMENT */))
                              : (openBlock(), createElementBlock("span", _hoisted_30$1, "System"))
                          ]))
                        : createCommentVNode("v-if", true),
                      createBaseVNode("td", _hoisted_31$1, toDisplayString($setup.getDepartmentName(order.department_id)), 1 /* TEXT */),
                      createCommentVNode(" Vehicles "),
                      createBaseVNode("td", _hoisted_32$1, [
                        createBaseVNode("p", _hoisted_33$1, [
                          (order.reg_1)
                            ? (openBlock(), createBlock($setup["EditableTableColumn"], {
                                key: 0,
                                componentWrapper: 'div',
                                object: order,
                                loadList: $setup.loadList,
                                column: "reg_1",
                                "parse-function": (value) => value || $setup.t('global.no_data'),
                                "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                                permissionCheckFunction: (orderobj) => $setup.canEditTransaction(order)
                              }, null, 8 /* PROPS */, ["object", "loadList", "parse-function", "edit-function", "permissionCheckFunction"]))
                            : createCommentVNode("v-if", true)
                        ]),
                        (order.reg_2 || order.reg_3)
                          ? (openBlock(), createElementBlock("p", _hoisted_34$1, [
                              (order.reg_3)
                                ? (openBlock(), createBlock($setup["EditableTableColumn"], {
                                    key: 0,
                                    componentWrapper: 'div',
                                    object: order,
                                    loadList: $setup.loadList,
                                    column: "reg_2",
                                    "parse-function": (value) => value || '-',
                                    "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                                    permissionCheckFunction: (bookingobj) => $setup.canEditTransaction(order)
                                  }, null, 8 /* PROPS */, ["object", "loadList", "parse-function", "edit-function", "permissionCheckFunction"]))
                                : createCommentVNode("v-if", true),
                              (order.reg_2 && order.reg_3)
                                ? (openBlock(), createElementBlock("span", _hoisted_35$1, "/"))
                                : createCommentVNode("v-if", true),
                              createVNode($setup["EditableTableColumn"], {
                                componentWrapper: 'div',
                                object: order,
                                loadList: $setup.loadList,
                                column: "reg_3",
                                "parse-function": (value) => value || '-',
                                "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                                permissionCheckFunction: (bookingobj) => $setup.canEditTransaction(order)
                              }, null, 8 /* PROPS */, ["object", "loadList", "parse-function", "edit-function", "permissionCheckFunction"])
                            ]))
                          : createCommentVNode("v-if", true)
                      ]),
                      createVNode($setup["EditableTableColumn"], {
                        class: "pos-orders-table-compact-text-cell",
                        object: order,
                        loadList: $setup.loadList,
                        column: "reference",
                        "cell-test-id": `pos-order-reference-${order.id}`,
                        "hover-text": order.reference,
                        "parse-function": (value) => $setup.truncateOrderField(value, 10),
                        "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                        "permission-check-function": () => $setup.canEditTransaction(order)
                      }, null, 8 /* PROPS */, ["object", "loadList", "cell-test-id", "hover-text", "parse-function", "edit-function", "permission-check-function"]),
                      createVNode($setup["EditableTableColumn"], {
                        class: "pos-orders-table-compact-text-cell",
                        object: order,
                        loadList: $setup.loadList,
                        column: "notes",
                        "cell-test-id": `pos-order-notes-${order.id}`,
                        "parse-function": (value) => $setup.truncateOrderField(value, 10),
                        "hover-text": order.notes,
                        "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                        "permission-check-function": () => $setup.SessionUser.canAccessAdmin()
                      }, null, 8 /* PROPS */, ["object", "loadList", "cell-test-id", "parse-function", "hover-text", "edit-function", "permission-check-function"]),
                      ($setup.canSeePoField() || $setup.SessionUser.canAccessAdmin())
                        ? (openBlock(), createBlock($setup["EditableTableColumn"], {
                            key: 4,
                            class: "pos-orders-table-compact-text-cell",
                            object: order,
                            loadList: $setup.loadList,
                            column: "po",
                            "cell-test-id": `pos-order-po-${order.id}`,
                            "hover-text": order.po,
                            "parse-function": (value) => $setup.truncateOrderField(value, 10),
                            "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                            "permission-check-function": () => $setup.canEditTransaction(order)
                          }, null, 8 /* PROPS */, ["object", "loadList", "cell-test-id", "hover-text", "parse-function", "edit-function", "permission-check-function"]))
                        : createCommentVNode("v-if", true),
                      createBaseVNode("td", _hoisted_36$1, toDisplayString(order.created_at), 1 /* TEXT */),
                      createBaseVNode("td", _hoisted_37$1, toDisplayString($setup.SessionUser.functions.currency.toLocal(order.total_net_amount)), 1 /* TEXT */),
                      createCommentVNode("<td>{{ order.completed_at }}</td>"),
                      createBaseVNode("td", _hoisted_38$1, [
                        createVNode($setup["SuperuserInvoiceRowActions"], { class: "pos-order-list-actions" }, {
                          default: withCtx(() => [
                            ($setup.shouldShowDraftAssignmentActions)
                              ? (openBlock(), createElementBlock("button", {
                                  key: 0,
                                  class: "button is-small is-link is-light pos-order-list-assign-customer-button",
                                  "data-testid": `draft-order-assign-customer-button-${order.id}`,
                                  onClick: $event => ($setup.openDraftAssignmentModal(order))
                                }, [
                                  _cache[11] || (_cache[11] = createBaseVNode("span", { class: "icon" }, [
                                    createBaseVNode("i", { class: "fas fa-user-check" })
                                  ], -1 /* CACHED */)),
                                  createBaseVNode("span", null, toDisplayString($setup.t("admin.pos.drafts_assignment.button")), 1 /* TEXT */)
                                ], 8 /* PROPS */, _hoisted_39$1))
                              : createCommentVNode("v-if", true),
                            createCommentVNode(" Attachments "),
                            createVNode($setup["OrderAttachmentsActionButton"], {
                              order: order,
                              "refresh-function": $setup.loadList,
                              "data-testid": `pos-order-list-attachments-${order.id}`
                            }, null, 8 /* PROPS */, ["order", "refresh-function", "data-testid"]),
                            createVNode($setup["ActionSettingsWheelButton"], {
                              user_id: order.user_id,
                              order_id: order.id,
                              invoice_collection_id: order.invoice_collection_id,
                              customer_number: order.customer_id,
                              department_id: order.department_id,
                              reg_1: order.reg_1,
                              reg_2: order.reg_2,
                              reg_3: order.reg_3,
                              order_booking_id: order.booking_id,
                              refreshFunction: $setup.loadList,
                              onDeleted: _cache[0] || (_cache[0] = $event => ($setup.loadList())),
                              onFlagCreated: $setup.emitFlagCreated,
                              "data-testid": `pos-order-list-settings-${order.id}`
                            }, {
                              actions: withCtx(() => [
                                createCommentVNode("\n                Go to the order page, in a new tab\n                <action-settings-wheel-item\n                  label=\"Se transaktion i ny fane\"\n                  icon=\"fas fa-external-link-alt\"\n                  :click-action=\"() => redirectDepartmentOrderPage(order.id, order.department_id)\"\n                  :disabled=\"false\"\n                  />\n                Show the invoice collection, in a new tab\n                <action-settings-wheel-item\n                  label=\"Vis faktura samling i ny fane\"\n                  icon=\"fas fa-file-invoice-dollar\"\n                  :click-action=\"() => redirectSuperUserInvoiceCollectionPage(order.invoice_collection.id)\"\n                  :disabled=\"!doesOrderHaveInvoiceCollection(order)\"\n                  />\n                ")
                              ]),
                              _: 1 /* STABLE */
                            }, 8 /* PROPS */, ["user_id", "order_id", "invoice_collection_id", "customer_number", "department_id", "reg_1", "reg_2", "reg_3", "order_booking_id", "refreshFunction", "data-testid"])
                          ]),
                          _: 2 /* DYNAMIC */
                        }, 1024 /* DYNAMIC_SLOTS */)
                      ])
                    ], 2 /* CLASS */))
                  : createCommentVNode("v-if", true),
                ($setup.getOrderLineFlags(order).length > 0)
                  ? (openBlock(), createElementBlock("tr", {
                      key: 2,
                      "data-testid": `pos-order-flags-row-${order.id}`
                    }, [
                      createBaseVNode("td", _hoisted_41$1, [
                        createVNode($setup["InvoicingPeriodFlagList"], {
                          compact: "",
                          flags: $setup.getOrderLineFlags(order),
                          onStatusChanged: $setup.emitFlagStatusChanged
                        }, null, 8 /* PROPS */, ["flags"])
                      ])
                    ], 8 /* PROPS */, _hoisted_40$1))
                  : createCommentVNode("v-if", true),
                createCommentVNode(" Dropdown content (if the invoice view is enabled,and the dropdown is active) "),
                ($setup.props.invoiceView && $setup.isDropdownActive(order))
                  ? (openBlock(), createElementBlock("tr", _hoisted_42$1, [
                      createCommentVNode(" Order line items "),
                      createBaseVNode("td", _hoisted_43$1, [
                        createCommentVNode(" Content "),
                        createBaseVNode("div", _hoisted_44$1, [
                          createVNode($setup["OrderContentTable"], {
                            "order-id": order.id,
                            "invoice-period-flags": $setup.getOrderItemLineFlags(order),
                            onFlagStatusChanged: $setup.emitFlagStatusChanged
                          }, null, 8 /* PROPS */, ["order-id", "invoice-period-flags"])
                        ])
                      ])
                    ]))
                  : createCommentVNode("v-if", true)
              ], 64 /* STABLE_FRAGMENT */))
            }), 128 /* KEYED_FRAGMENT */))
          ]),
          createBaseVNode("tfoot", null, [
            createBaseVNode("tr", null, [
              createBaseVNode("td", _hoisted_45$1, toDisplayString($setup.t("tables.showing")) + " " + toDisplayString($setup.getVisibleOrders.length) + " " + toDisplayString($setup.SessionUser.objects.orders.meta.labels.entries.toLowerCase()), 1 /* TEXT */)
            ])
          ])
        ])
      ]),
      tablet: withCtx(() => [
        createBaseVNode("div", _hoisted_46$1, [
          createCommentVNode(" Bulk actions when invoice view allows selection "),
          ($setup.props.invoiceView && $setup.props.allowSelectMultiple)
            ? (openBlock(), createElementBlock("div", _hoisted_47$1, [
                createVNode($setup["InvoiceCollectionSelectionActionWheel"], {
                  "selected-invoice-collection-ids": $setup.selectedInvoiceCollections,
                  "total-invoice-collection-count": $setup.selectableInvoiceCollectionCount,
                  "all-selected": $setup.isInvoiceCollectionSelectedAll(),
                  "all-expanded": $setup.isAutoExpandAll(),
                  "invoice-queue-busy": $setup.isInvoiceQueueBusy,
                  onInvoiceSelected: $setup.invoiceSelectedCollections,
                  onBulkAction: $setup.runInvoiceCollectionBulkAction,
                  onToggleSelectAll: $setup.selectAllInvoiceCollections,
                  onToggleExpandAll: $setup.toggleAutoExpandAll
                }, null, 8 /* PROPS */, ["selected-invoice-collection-ids", "total-invoice-collection-count", "all-selected", "all-expanded", "invoice-queue-busy"])
              ]))
            : createCommentVNode("v-if", true),
          createCommentVNode(" Orders as cards "),
          (openBlock(true), createElementBlock(Fragment, null, renderList($setup.getVisibleOrders, (order) => {
            return (openBlock(), createElementBlock("div", {
              key: order.id,
              class: "column is-full"
            }, [
              createVNode($setup["WhiteBoxCard"], {
                forceStateFooter: false,
                forceState: false,
                defaultOpen: false,
                toggleable: true,
                class: "is-clickable",
                "has-hover-effect": true,
                hasSelectionStyle: false
              }, {
                header: withCtx(() => [
                  createBaseVNode("div", _hoisted_48$1, [
                    createBaseVNode("div", null, [
                      createBaseVNode("div", null, [
                        createBaseVNode("small", null, [
                          createCommentVNode(" ID and status icon "),
                          createBaseVNode("span", {
                            class: normalizeClass(["icon mr-1", $setup.getOrderInvoiceStatusBarColor(order)])
                          }, [
                            createBaseVNode("i", {
                              class: normalizeClass($setup.isPendingHandheld(order) ? 'fas fa-mobile-alt' : 'fas fa-circle')
                            }, null, 2 /* CLASS */)
                          ], 2 /* CLASS */),
                          createTextVNode(" #" + toDisplayString(order.id), 1 /* TEXT */)
                        ])
                      ]),
                      (!$setup.props.isCustomerView)
                        ? (openBlock(), createElementBlock("div", _hoisted_49$1, [
                            createBaseVNode("small", null, toDisplayString(order.customer_name), 1 /* TEXT */)
                          ]))
                        : createCommentVNode("v-if", true)
                    ]),
                    createBaseVNode("div", _hoisted_50$1, [
                      createBaseVNode("div", _hoisted_51$1, [
                        createBaseVNode("div", _hoisted_52$1, [
                          createBaseVNode("span", _hoisted_53$1, [
                            createBaseVNode("small", null, toDisplayString($setup.getDepartmentName(order.department_id)), 1 /* TEXT */)
                          ])
                        ]),
                        createBaseVNode("div", _hoisted_54$1, [
                          createBaseVNode("span", _hoisted_55$1, [
                            ($setup.props.invoiceView && $setup.props.allowSelectMultiple)
                              ? (openBlock(), createBlock($setup["BCheckbox"], {
                                  key: 0,
                                  class: "pos-order-invoice-collection-selector",
                                  "model-value": $setup.isInvoiceCollectionSelected(order.invoice_collection_id),
                                  disabled: $setup.normalizeInvoiceCollectionId(order.invoice_collection_id) === null,
                                  "aria-label": `${
                              $setup.SessionUser.objects.global.language.select
                            } ${$setup.SessionUser.objects.global.language.invoice.toLowerCase()} #${
                              order.invoice_collection_id || order.id
                            }`,
                                  "data-testid": `pos-order-invoice-collection-selector-${order.id}`,
                                  "onUpdate:modelValue": 
                              (checked) => $setup.setInvoiceCollectionSelection(order.invoice_collection_id, checked)
                            
                                }, null, 8 /* PROPS */, ["model-value", "disabled", "aria-label", "data-testid", "onUpdate:modelValue"]))
                              : createCommentVNode("v-if", true)
                          ])
                        ])
                      ])
                    ])
                  ])
                ]),
                default: withCtx(() => [
                  createBaseVNode("div", _hoisted_56$1, [
                    createBaseVNode("div", _hoisted_57$1, [
                      createBaseVNode("div", _hoisted_58$1, [
                        createBaseVNode("small", null, [
                          createTextVNode(toDisplayString(order.reg_1), 1 /* TEXT */),
                          (order.reg_2)
                            ? (openBlock(), createElementBlock("span", _hoisted_59$1, ", " + toDisplayString(order.reg_2), 1 /* TEXT */))
                            : createCommentVNode("v-if", true),
                          (order.reg_3)
                            ? (openBlock(), createElementBlock("span", _hoisted_60$1, ", " + toDisplayString(order.reg_3), 1 /* TEXT */))
                            : createCommentVNode("v-if", true)
                        ])
                      ]),
                      createBaseVNode("div", _hoisted_61$1, [
                        createBaseVNode("strong", null, [
                          createBaseVNode("small", null, toDisplayString(order.created_at), 1 /* TEXT */)
                        ])
                      ]),
                      createBaseVNode("div", _hoisted_62$1, [
                        createBaseVNode("small", null, toDisplayString($setup.SessionUser.objects.orders.columns.total_net_amount.label || "Total") + ": " + toDisplayString($setup.SessionUser.functions.currency.toLocal(order.total_net_amount)), 1 /* TEXT */)
                      ]),
                      (order.completed_at)
                        ? (openBlock(), createElementBlock("div", _hoisted_63$1, [
                            createBaseVNode("small", null, toDisplayString($setup.SessionUser.objects.orders.columns.completed_at.label) + ": " + toDisplayString(order.completed_at), 1 /* TEXT */)
                          ]))
                        : createCommentVNode("v-if", true),
                      ($setup.isPendingHandheld(order))
                        ? (openBlock(), createElementBlock("div", _hoisted_64, [
                            createBaseVNode("small", _hoisted_65, toDisplayString($setup.SessionUser.objects.global.language.handheld_pending_order) + " • " + toDisplayString($setup.SessionUser.objects.global.language.confirmation_needed), 1 /* TEXT */)
                          ]))
                        : createCommentVNode("v-if", true)
                    ])
                  ]),
                  createVNode($setup["InvoicingPeriodFlagList"], {
                    compact: "",
                    flags: $setup.getOrderLineFlags(order),
                    onStatusChanged: $setup.emitFlagStatusChanged
                  }, null, 8 /* PROPS */, ["flags"])
                ]),
                content: withCtx(() => [
                  createBaseVNode("div", null, [
                    withDirectives(createBaseVNode("p", null, [
                      _cache[12] || (_cache[12] = createBaseVNode("strong", null, "PO:", -1 /* CACHED */)),
                      createTextVNode(" " + toDisplayString(order.po || "-"), 1 /* TEXT */)
                    ], 512 /* NEED_PATCH */), [
                      [vShow, !!order.po]
                    ]),
                    withDirectives(createBaseVNode("p", null, [
                      createBaseVNode("strong", null, toDisplayString($setup.SessionUser.objects.orders.columns.reference?.label || "Reference") + ":", 1 /* TEXT */),
                      createTextVNode(" " + toDisplayString(order.reference || "-"), 1 /* TEXT */)
                    ], 512 /* NEED_PATCH */), [
                      [vShow, !!order.reference]
                    ]),
                    withDirectives(createBaseVNode("p", null, [
                      createBaseVNode("strong", null, toDisplayString($setup.SessionUser.objects.orders.columns.notes?.label || "Noter") + ":", 1 /* TEXT */),
                      createTextVNode(" " + toDisplayString(order.notes || "-"), 1 /* TEXT */)
                    ], 512 /* NEED_PATCH */), [
                      [vShow, !!order.notes]
                    ]),
                    _cache[15] || (_cache[15] = createBaseVNode("hr", null, null, -1 /* CACHED */)),
                    createCommentVNode(" Actions and attachments "),
                    createBaseVNode("div", _hoisted_66, [
                      ($setup.shouldShowDraftAssignmentActions)
                        ? (openBlock(), createElementBlock("button", {
                            key: 0,
                            class: "button is-small is-link is-light pos-order-list-assign-customer-button",
                            "data-testid": `draft-order-assign-customer-button-${order.id}`,
                            onClick: $event => ($setup.openDraftAssignmentModal(order))
                          }, [
                            _cache[13] || (_cache[13] = createBaseVNode("span", { class: "icon" }, [
                              createBaseVNode("i", { class: "fas fa-user-check" })
                            ], -1 /* CACHED */)),
                            createBaseVNode("span", null, toDisplayString($setup.t("admin.pos.drafts_assignment.button")), 1 /* TEXT */)
                          ], 8 /* PROPS */, _hoisted_67))
                        : createCommentVNode("v-if", true),
                      createVNode($setup["ActionSettingsWheelButton"], {
                        user_id: order.user_id,
                        order_id: order.id,
                        invoice_collection_id: order.invoice_collection_id,
                        customer_number: order.customer_id,
                        department_id: order.department_id,
                        reg_1: order.reg_1,
                        reg_2: order.reg_2,
                        reg_3: order.reg_3,
                        order_booking_id: order.booking_id,
                        refreshFunction: $setup.loadList,
                        onDeleted: _cache[1] || (_cache[1] = $event => ($setup.loadList())),
                        onFlagCreated: $setup.emitFlagCreated,
                        displayActionsDirectly: true
                      }, {
                        actions: withCtx(() => [...(_cache[14] || (_cache[14] = []))]),
                        _: 1 /* STABLE */
                      }, 8 /* PROPS */, ["user_id", "order_id", "invoice_collection_id", "customer_number", "department_id", "reg_1", "reg_2", "reg_3", "order_booking_id", "refreshFunction"]),
                      createVNode($setup["OrderAttachmentsActionButton"], {
                        order: order,
                        "refresh-function": $setup.loadList,
                        "data-testid": `pos-order-list-attachments-${order.id}`
                      }, null, 8 /* PROPS */, ["order", "refresh-function", "data-testid"])
                    ]),
                    createCommentVNode(" Order line items "),
                    ($setup.props.invoiceView && $setup.isAutoExpandAll())
                      ? (openBlock(), createElementBlock("div", _hoisted_68, [
                          createVNode($setup["OrderContentTable"], {
                            "order-id": order.id,
                            "invoice-period-flags": $setup.getOrderItemLineFlags(order),
                            onFlagStatusChanged: $setup.emitFlagStatusChanged
                          }, null, 8 /* PROPS */, ["order-id", "invoice-period-flags"])
                        ]))
                      : createCommentVNode("v-if", true)
                  ])
                ]),
                _: 2 /* DYNAMIC */
              }, 1024 /* DYNAMIC_SLOTS */)
            ]))
          }), 128 /* KEYED_FRAGMENT */)),
          createCommentVNode(" Footer count "),
          createBaseVNode("div", _hoisted_69, [
            createBaseVNode("div", _hoisted_70, [
              createBaseVNode("small", null, toDisplayString($setup.t("tables.showing")) + " " + toDisplayString($setup.getVisibleOrders.length) + " " + toDisplayString($setup.SessionUser.objects.orders.meta.labels.entries.toLowerCase()), 1 /* TEXT */)
            ])
          ])
        ])
      ]),
      mobile: withCtx(() => [
        createBaseVNode("div", _hoisted_71, [
          createCommentVNode(" Bulk actions when invoice view allows selection "),
          ($setup.props.invoiceView && $setup.props.allowSelectMultiple)
            ? (openBlock(), createElementBlock("div", _hoisted_72, [
                createVNode($setup["InvoiceCollectionSelectionActionWheel"], {
                  "selected-invoice-collection-ids": $setup.selectedInvoiceCollections,
                  "total-invoice-collection-count": $setup.selectableInvoiceCollectionCount,
                  "all-selected": $setup.isInvoiceCollectionSelectedAll(),
                  "all-expanded": $setup.isAutoExpandAll(),
                  "invoice-queue-busy": $setup.isInvoiceQueueBusy,
                  onInvoiceSelected: $setup.invoiceSelectedCollections,
                  onBulkAction: $setup.runInvoiceCollectionBulkAction,
                  onToggleSelectAll: $setup.selectAllInvoiceCollections,
                  onToggleExpandAll: $setup.toggleAutoExpandAll
                }, null, 8 /* PROPS */, ["selected-invoice-collection-ids", "total-invoice-collection-count", "all-selected", "all-expanded", "invoice-queue-busy"])
              ]))
            : createCommentVNode("v-if", true),
          createCommentVNode(" Orders as cards "),
          (openBlock(true), createElementBlock(Fragment, null, renderList($setup.props.groupInvoiceCollection ? $setup.getVisibleOrdersSortedByInvoiceCollection : $setup.getVisibleOrders, (order) => {
            return (openBlock(), createElementBlock(Fragment, {
              key: order.id
            }, [
              createCommentVNode(" If grouping by invoice collection is enabled, show the invoice collection id "),
              (
              $setup.props.groupInvoiceCollection &&
              $setup.doesOrderHaveInvoiceCollection(order) &&
              $setup.isFirstOrderInCollection(order.invoice_collection_id, order)
            )
                ? (openBlock(), createElementBlock("div", {
                    key: 0,
                    class: "column is-full",
                    "data-testid": `pos-order-invoice-collection-row-${order.invoice_collection_id}`
                  }, [
                    createBaseVNode("div", _hoisted_74, [
                      createBaseVNode("div", {
                        class: "message-body is-flex is-justify-content-space-between is-align-items-center p-2",
                        "data-testid": `pos-order-invoice-collection-summary-${order.invoice_collection_id}`
                      }, [
                        createBaseVNode("div", _hoisted_76, "Faktura samling ID: " + toDisplayString(order.invoice_collection_id), 1 /* TEXT */),
                        createBaseVNode("div", _hoisted_77, [
                          createBaseVNode("span", {
                            "data-testid": `pos-order-invoice-collection-total-${order.invoice_collection_id}`
                          }, toDisplayString($setup.SessionUser.functions.currency.toLocal(
                          $setup.getOrdersByInvoiceCollection(order.invoice_collection_id)
                            .reduce((sum, order) => sum + order.total_net_amount, 0)
                            .toFixed(2)
                        )) + " kr.", 9 /* TEXT, PROPS */, _hoisted_78)
                        ])
                      ], 8 /* PROPS */, _hoisted_75)
                    ])
                  ], 8 /* PROPS */, _hoisted_73))
                : createCommentVNode("v-if", true),
              createBaseVNode("div", _hoisted_79, [
                createVNode($setup["WhiteBoxCard"], {
                  forceStateFooter: true,
                  forceState: false,
                  defaultOpen: false,
                  toggleable: true,
                  class: "is-clickable pos-orders-mobile-card",
                  "has-hover-effect": true,
                  hasSelectionStyle: false,
                  "data-testid": `pos-order-list-card-${order.id}`,
                  headerTestId: `pos-order-expand-${order.id}`
                }, {
                  header: withCtx(() => [
                    createBaseVNode("div", _hoisted_80, [
                      createBaseVNode("div", null, [
                        createBaseVNode("div", null, [
                          createBaseVNode("small", null, [
                            createCommentVNode(" ID and status icon "),
                            createVNode($setup["ColorIndicator"], {
                              class: "mr-1",
                              style: {"display":"inline-flex"},
                              color_class: $setup.getOrderIndicatorColorClass(order),
                              icon_class: $setup.getOrderIndicatorIconClass(order),
                              is_narrow: true,
                              visibility: {
                            icon: true,
                            dropdown: false,
                          }
                            }, null, 8 /* PROPS */, ["color_class", "icon_class"]),
                            createTextVNode(" " + toDisplayString(order.reg_1), 1 /* TEXT */),
                            (order.reg_2)
                              ? (openBlock(), createElementBlock("span", _hoisted_81, ", " + toDisplayString(order.reg_2), 1 /* TEXT */))
                              : createCommentVNode("v-if", true),
                            (order.reg_3)
                              ? (openBlock(), createElementBlock("span", _hoisted_82, ", " + toDisplayString(order.reg_3), 1 /* TEXT */))
                              : createCommentVNode("v-if", true),
                            createBaseVNode("span", _hoisted_83, "#" + toDisplayString(order.id), 1 /* TEXT */)
                          ])
                        ]),
                        (!$setup.props.isCustomerView)
                          ? (openBlock(), createElementBlock("div", _hoisted_84, [
                              createBaseVNode("small", null, toDisplayString(order.customer_name), 1 /* TEXT */)
                            ]))
                          : createCommentVNode("v-if", true)
                      ]),
                      createBaseVNode("div", _hoisted_85, [
                        createBaseVNode("div", _hoisted_86, [
                          createBaseVNode("div", _hoisted_87, [
                            createBaseVNode("span", _hoisted_88, [
                              createBaseVNode("small", null, toDisplayString($setup.getDepartmentName(order.department_id)), 1 /* TEXT */)
                            ])
                          ]),
                          createBaseVNode("div", _hoisted_89, [
                            createBaseVNode("span", _hoisted_90, [
                              ($setup.props.invoiceView && $setup.props.allowSelectMultiple)
                                ? (openBlock(), createBlock($setup["BCheckbox"], {
                                    key: 0,
                                    class: "pos-order-invoice-collection-selector",
                                    "model-value": $setup.isInvoiceCollectionSelected(order.invoice_collection_id),
                                    disabled: $setup.normalizeInvoiceCollectionId(order.invoice_collection_id) === null,
                                    "aria-label": `${
                              $setup.SessionUser.objects.global.language.select
                            } ${$setup.SessionUser.objects.global.language.invoice.toLowerCase()} #${
                              order.invoice_collection_id || order.id
                            }`,
                                    "data-testid": `pos-order-invoice-collection-selector-${order.id}`,
                                    "onUpdate:modelValue": 
                              (checked) => $setup.setInvoiceCollectionSelection(order.invoice_collection_id, checked)
                            
                                  }, null, 8 /* PROPS */, ["model-value", "disabled", "aria-label", "data-testid", "onUpdate:modelValue"]))
                                : createCommentVNode("v-if", true)
                            ])
                          ])
                        ])
                      ])
                    ])
                  ]),
                  default: withCtx(() => [
                    createBaseVNode("div", _hoisted_91, [
                      createBaseVNode("div", _hoisted_92, [
                        createBaseVNode("div", _hoisted_93, [
                          (!!order.reference)
                            ? (openBlock(), createElementBlock("div", _hoisted_94, [
                                createBaseVNode("div", _hoisted_95, [
                                  createBaseVNode("label", _hoisted_96, toDisplayString($setup.SessionUser.objects.orders.columns.reference?.label || "Reference") + ":", 1 /* TEXT */)
                                ]),
                                createBaseVNode("div", _hoisted_97, [
                                  createBaseVNode("small", null, [
                                    createVNode($setup["EditableTableColumn"], {
                                      componentWrapper: 'div',
                                      object: order,
                                      loadList: $setup.loadList,
                                      column: "reference",
                                      "hover-text": order.reference,
                                      "parse-function": (value) => $setup.truncateOrderField(value, 20),
                                      "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                                      "permission-check-function": () => $setup.canEditTransaction(order)
                                    }, null, 8 /* PROPS */, ["object", "loadList", "hover-text", "parse-function", "edit-function", "permission-check-function"])
                                  ])
                                ])
                              ]))
                            : createCommentVNode("v-if", true),
                          (!!order.notes)
                            ? (openBlock(), createElementBlock("div", _hoisted_98, [
                                createBaseVNode("div", _hoisted_99, [
                                  createBaseVNode("label", {
                                    class: normalizeClass(["label is-small", { 'has-text-grey': !order.notes }])
                                  }, toDisplayString($setup.SessionUser.objects.orders.columns.notes?.label || "Noter") + ":", 3 /* TEXT, CLASS */)
                                ]),
                                createBaseVNode("div", _hoisted_100, [
                                  createBaseVNode("small", null, [
                                    createVNode($setup["EditableTableColumn"], {
                                      componentWrapper: 'div',
                                      object: order,
                                      loadList: $setup.loadList,
                                      column: "notes",
                                      "hover-text": order.notes,
                                      "parse-function": (value) => $setup.truncateOrderField(value, 20),
                                      "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                                      "permission-check-function": () => $setup.SessionUser.canAccessAdmin()
                                    }, null, 8 /* PROPS */, ["object", "loadList", "hover-text", "parse-function", "edit-function", "permission-check-function"])
                                  ])
                                ])
                              ]))
                            : createCommentVNode("v-if", true),
                          (!!order.po)
                            ? (openBlock(), createElementBlock("div", _hoisted_101, [
                                createBaseVNode("div", _hoisted_102, [
                                  createBaseVNode("label", {
                                    class: normalizeClass(["label is-small", { 'has-text-grey': !order.po }])
                                  }, "PO:", 2 /* CLASS */)
                                ]),
                                createBaseVNode("div", _hoisted_103, [
                                  createBaseVNode("small", null, [
                                    createVNode($setup["EditableTableColumn"], {
                                      componentWrapper: 'div',
                                      object: order,
                                      loadList: $setup.loadList,
                                      column: "po",
                                      "hover-text": order.po,
                                      "parse-function": (value) => $setup.truncateOrderField(value, 20),
                                      "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                                      "permission-check-function": () => $setup.canEditTransaction(order)
                                    }, null, 8 /* PROPS */, ["object", "loadList", "hover-text", "parse-function", "edit-function", "permission-check-function"])
                                  ])
                                ])
                              ]))
                            : createCommentVNode("v-if", true),
                          createCommentVNode(" Order summary "),
                          (!!order.reference || !!order.notes || !!order.po)
                            ? (openBlock(), createElementBlock("hr", _hoisted_104))
                            : createCommentVNode("v-if", true),
                          createVNode($setup["OrderContentTable"], {
                            "order-id": order.id,
                            summaryMode: true,
                            "display-price": $setup.SessionUser.canAccessAdmin(),
                            "invoice-period-flags": $setup.getOrderItemLineFlags(order),
                            onFlagStatusChanged: $setup.emitFlagStatusChanged
                          }, null, 8 /* PROPS */, ["order-id", "display-price", "invoice-period-flags"])
                        ]),
                        createBaseVNode("div", _hoisted_105, [
                          _cache[21] || (_cache[21] = createBaseVNode("hr", null, null, -1 /* CACHED */)),
                          createCommentVNode(" Total net amount "),
                          createBaseVNode("strong", null, toDisplayString($setup.SessionUser.functions.currency.toLocal(order.total_net_amount)), 1 /* TEXT */),
                          _cache[22] || (_cache[22] = createBaseVNode("br", null, null, -1 /* CACHED */)),
                          createCommentVNode(" Cashier • Time ago "),
                          createBaseVNode("small", _hoisted_106, toDisplayString(order.cashier_name) + " • " + toDisplayString($setup.SessionUser.functions.date.toLocalTimeHours(order.created_at)), 1 /* TEXT */),
                          createCommentVNode(" Reg 1 • Reg 2 • Reg 3 "),
                          _cache[23] || (_cache[23] = createBaseVNode("br", null, null, -1 /* CACHED */)),
                          createBaseVNode("div", _hoisted_107, [
                            createBaseVNode("div", _hoisted_108, [
                              createBaseVNode("div", _hoisted_109, [
                                (!!order.reg_1)
                                  ? (openBlock(), createElementBlock("div", _hoisted_110, [
                                      _cache[16] || (_cache[16] = createBaseVNode("div", { class: "column is-narrow mr-1" }, [
                                        createBaseVNode("label", { class: "label is-small" }, "Reg 1:")
                                      ], -1 /* CACHED */)),
                                      createBaseVNode("div", _hoisted_111, [
                                        createBaseVNode("small", null, [
                                          createVNode($setup["EditableTableColumn"], {
                                            componentWrapper: 'div',
                                            object: order,
                                            loadList: $setup.loadList,
                                            column: "reg_1",
                                            "hover-text": order.reg_1,
                                            "parse-function": (value) => $setup.truncateOrderField(value, 20),
                                            "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                                            "permission-check-function": () => $setup.canEditTransaction(order)
                                          }, null, 8 /* PROPS */, ["object", "loadList", "hover-text", "parse-function", "edit-function", "permission-check-function"])
                                        ])
                                      ])
                                    ]))
                                  : createCommentVNode("v-if", true)
                              ]),
                              (order.reg_2 || order.reg_3)
                                ? (openBlock(), createElementBlock("div", _hoisted_112, [...(_cache[17] || (_cache[17] = [
                                    createBaseVNode("div", { class: "columns is-mobile is-gapless is-align-items-center" }, [
                                      createBaseVNode("div", { class: "column" }, [
                                        createBaseVNode("label", { class: "label is-small has-text-grey" }, "•")
                                      ])
                                    ], -1 /* CACHED */)
                                  ]))]))
                                : createCommentVNode("v-if", true),
                              (order.reg_2)
                                ? (openBlock(), createElementBlock("div", _hoisted_113, [
                                    (!!order.reg_2)
                                      ? (openBlock(), createElementBlock("div", _hoisted_114, [
                                          _cache[18] || (_cache[18] = createBaseVNode("div", { class: "column is-narrow mr-1" }, [
                                            createBaseVNode("label", { class: "label is-small" }, "Reg 2:")
                                          ], -1 /* CACHED */)),
                                          createBaseVNode("div", _hoisted_115, [
                                            createBaseVNode("small", null, [
                                              createVNode($setup["EditableTableColumn"], {
                                                componentWrapper: 'div',
                                                object: order,
                                                loadList: $setup.loadList,
                                                column: "reg_2",
                                                "hover-text": order.reg_2,
                                                "parse-function": (value) => $setup.truncateOrderField(value, 20),
                                                "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                                                "permission-check-function": () => $setup.canEditTransaction(order)
                                              }, null, 8 /* PROPS */, ["object", "loadList", "hover-text", "parse-function", "edit-function", "permission-check-function"])
                                            ])
                                          ])
                                        ]))
                                      : createCommentVNode("v-if", true)
                                  ]))
                                : createCommentVNode("v-if", true),
                              (order.reg_2 && order.reg_3)
                                ? (openBlock(), createElementBlock("div", _hoisted_116, [...(_cache[19] || (_cache[19] = [
                                    createBaseVNode("div", { class: "columns is-mobile is-gapless is-align-items-center" }, [
                                      createBaseVNode("div", { class: "column" }, [
                                        createBaseVNode("label", { class: "label is-small has-text-grey" }, "•")
                                      ])
                                    ], -1 /* CACHED */)
                                  ]))]))
                                : createCommentVNode("v-if", true),
                              (order.reg_3)
                                ? (openBlock(), createElementBlock("div", _hoisted_117, [
                                    (!!order.reg_3)
                                      ? (openBlock(), createElementBlock("div", _hoisted_118, [
                                          _cache[20] || (_cache[20] = createBaseVNode("div", { class: "column is-narrow mr-1" }, [
                                            createBaseVNode("label", { class: "label is-small" }, "Reg 3:")
                                          ], -1 /* CACHED */)),
                                          createBaseVNode("div", _hoisted_119, [
                                            createBaseVNode("small", null, [
                                              createVNode($setup["EditableTableColumn"], {
                                                componentWrapper: 'div',
                                                object: order,
                                                loadList: $setup.loadList,
                                                column: "reg_3",
                                                "hover-text": order.reg_3,
                                                "parse-function": (value) => $setup.truncateOrderField(value, 20),
                                                "edit-function": $setup.SessionUser.objects.orders.showEditObjectFieldForm,
                                                "permission-check-function": () => $setup.canEditTransaction(order)
                                              }, null, 8 /* PROPS */, ["object", "loadList", "hover-text", "parse-function", "edit-function", "permission-check-function"])
                                            ])
                                          ])
                                        ]))
                                      : createCommentVNode("v-if", true)
                                  ]))
                                : createCommentVNode("v-if", true)
                            ])
                          ])
                        ])
                      ])
                    ]),
                    createVNode($setup["InvoicingPeriodFlagList"], {
                      compact: "",
                      flags: $setup.getOrderLineFlags(order),
                      onStatusChanged: $setup.emitFlagStatusChanged
                    }, null, 8 /* PROPS */, ["flags"])
                  ]),
                  content: withCtx(() => [...(_cache[24] || (_cache[24] = []))]),
                  footer: withCtx(() => [
                    createCommentVNode(" Delete\n                <a class=\"card-footer-item\" @click=\"SessionUser.objects.orders.functions.showDeleteConfirmationModal(order, loadList)\">\n                  {{ SessionUser.objects.global.language.delete }}\n                </a>"),
                    createBaseVNode("a", {
                      class: "card-footer-item",
                      onClick: $event => ($setup.openOrderActionsModal(order)),
                      "data-testid": `pos-order-list-actions-${order.id}`
                    }, [...(_cache[25] || (_cache[25] = [
                      createBaseVNode("span", { class: "icon mr-1" }, [
                        createBaseVNode("i", { class: "fas fa-cog" })
                      ], -1 /* CACHED */)
                    ]))], 8 /* PROPS */, _hoisted_120),
                    createCommentVNode(" Go to booking (if any) "),
                    (order.booking_id)
                      ? (openBlock(), createElementBlock("a", {
                          key: 0,
                          class: "card-footer-item",
                          onClick: $event => ($setup.redirectDepartmentBookingPage(order.booking_id, order.department_id, false))
                        }, [
                          _cache[26] || (_cache[26] = createBaseVNode("span", { class: "icon mr-1" }, [
                            createBaseVNode("i", { class: "fas fa-calendar-alt" })
                          ], -1 /* CACHED */)),
                          createBaseVNode("span", null, toDisplayString($setup.SessionUser.objects.order_bookings.meta.labels.single), 1 /* TEXT */)
                        ], 8 /* PROPS */, _hoisted_121))
                      : createCommentVNode("v-if", true),
                    createCommentVNode(" Go to order page "),
                    createBaseVNode("a", {
                      class: "card-footer-item",
                      onClick: $event => ($setup.redirectDepartmentOrderPage(order.id, order.department_id, false))
                    }, [...(_cache[27] || (_cache[27] = [
                      createBaseVNode("span", { class: "icon mr-1" }, [
                        createBaseVNode("i", { class: "fas fa-arrow-right" })
                      ], -1 /* CACHED */)
                    ]))], 8 /* PROPS */, _hoisted_122)
                  ]),
                  _: 2 /* DYNAMIC */
                }, 1032 /* PROPS, DYNAMIC_SLOTS */, ["data-testid", "headerTestId"])
              ])
            ], 64 /* STABLE_FRAGMENT */))
          }), 128 /* KEYED_FRAGMENT */)),
          createCommentVNode(" Footer count "),
          createBaseVNode("div", _hoisted_123, [
            createBaseVNode("div", _hoisted_124, [
              createBaseVNode("small", null, toDisplayString($setup.t("tables.showing")) + " " + toDisplayString($setup.getVisibleOrders.length) + " " + toDisplayString($setup.SessionUser.objects.orders.meta.labels.entries.toLowerCase()), 1 /* TEXT */)
            ])
          ])
        ])
      ]),
      _: 1 /* STABLE */
    }),
    ($setup.isInvoiceMultipleCollectionsModalOpen)
      ? (openBlock(), createBlock($setup["InvoiceMultipleCollectionsModal"], {
          key: 0,
          "in-progress": $setup.invoiceCollectionQueueInProgress,
          failed: $setup.invoiceCollectionQueueFailed,
          succeeded: $setup.invoiceCollectionQueueSuccess,
          queued: $setup.invoiceCollectionQueue,
          jobs: $setup.invoiceQueue.invoiceCollectionQueueJobs,
          log: $setup.collectionQueueLog,
          onCloseModal: _cache[2] || (_cache[2] = $event => ($setup.confirmCloseModal())),
          onRetry: $setup.retryInvoiceCollection
        }, null, 8 /* PROPS */, ["in-progress", "failed", "succeeded", "queued", "jobs", "log"]))
      : createCommentVNode("v-if", true),
    createCommentVNode(" bottom progress bar "),
    ($setup.shouldShowLegacyInvoiceProgressBar)
      ? (openBlock(), createBlock($setup["InvoicingBillingPeriodInvoiceProgressBar"], {
          key: 1,
          "max-progress": 
      $setup.invoiceCollectionQueueSuccess.length +
      $setup.invoiceCollectionQueueFailed.length +
      $setup.invoiceCollectionQueueInProgress.length +
      $setup.invoiceCollectionQueue.length
    ,
          progress: $setup.invoiceCollectionQueueSuccess.length,
          failed: $setup.invoiceCollectionQueueFailed.length,
          "in-progress": $setup.invoiceCollectionQueueInProgress.length,
          queued: $setup.invoiceCollectionQueue.length,
          onDismissed: _cache[3] || (_cache[3] = $event => ($setup.isInvoiceMultipleCollectionsModalOpen = true))
        }, null, 8 /* PROPS */, ["max-progress", "progress", "failed", "in-progress", "queued"]))
      : createCommentVNode("v-if", true),
    createCommentVNode(" Order actions menu modal "),
    ($setup.selectedOrderForActionsMenu)
      ? (openBlock(), createElementBlock("div", {
          key: 2,
          class: normalizeClass(["modal", { 'is-active': $setup.isOrderActionsModalOpen }]),
          "data-testid": "pos-order-actions-modal"
        }, [
          createBaseVNode("div", {
            class: "modal-background",
            onClick: $setup.closeOrderActionsModal
          }),
          createBaseVNode("div", _hoisted_125, [
            createBaseVNode("header", _hoisted_126, [
              createBaseVNode("p", _hoisted_127, toDisplayString($setup.SessionUser.objects.global.language.actions), 1 /* TEXT */),
              createBaseVNode("button", {
                class: "delete",
                "aria-label": "close",
                onClick: $setup.closeOrderActionsModal
              })
            ]),
            createBaseVNode("section", _hoisted_128, [
              ($setup.shouldShowDraftAssignmentActions && $setup.selectedOrderForActionsMenu)
                ? (openBlock(), createElementBlock("button", {
                    key: 0,
                    class: "button is-link is-light is-fullwidth mb-4",
                    "data-testid": `draft-order-assign-customer-modal-button-${$setup.selectedOrderForActionsMenu.id}`,
                    onClick: _cache[4] || (_cache[4] = $event => ($setup.openDraftAssignmentModal($setup.selectedOrderForActionsMenu)))
                  }, [
                    _cache[28] || (_cache[28] = createBaseVNode("span", { class: "icon" }, [
                      createBaseVNode("i", { class: "fas fa-user-check" })
                    ], -1 /* CACHED */)),
                    createBaseVNode("span", null, toDisplayString($setup.t("admin.pos.drafts_assignment.button")), 1 /* TEXT */)
                  ], 8 /* PROPS */, _hoisted_129))
                : createCommentVNode("v-if", true),
              createVNode($setup["ActionSettingsWheelButton"], {
                user_id: $setup.selectedOrderForActionsMenu.user_id,
                order_id: $setup.selectedOrderForActionsMenu.id,
                invoice_collection_id: $setup.selectedOrderForActionsMenu.invoice_collection_id,
                customer_number: $setup.selectedOrderForActionsMenu.customer_id,
                reg_1: $setup.selectedOrderForActionsMenu.reg_1,
                reg_2: $setup.selectedOrderForActionsMenu.reg_2,
                reg_3: $setup.selectedOrderForActionsMenu.reg_3,
                order_booking_id: $setup.selectedOrderForActionsMenu.booking_id,
                department_id: $setup.selectedOrderForActionsMenu.department_id,
                refreshFunction: $setup.loadList,
                onDeleted: _cache[5] || (_cache[5] = $event => ($setup.loadList())),
                onFlagCreated: $setup.emitFlagCreated,
                displayActionsDirectly: true
              }, {
                actions: withCtx(() => [...(_cache[29] || (_cache[29] = []))]),
                _: 1 /* STABLE */
              }, 8 /* PROPS */, ["user_id", "order_id", "invoice_collection_id", "customer_number", "reg_1", "reg_2", "reg_3", "order_booking_id", "department_id", "refreshFunction"])
            ]),
            createBaseVNode("footer", _hoisted_130, [
              createBaseVNode("button", {
                class: "button is-light is-link is-fullwidth",
                onClick: $setup.closeOrderActionsModal
              }, toDisplayString($setup.SessionUser.objects.global.language.close), 1 /* TEXT */)
            ])
          ])
        ], 2 /* CLASS */))
      : createCommentVNode("v-if", true),
    ($setup.isDraftAssignmentModalOpen && $setup.selectedOrderForDraftAssignment)
      ? (openBlock(), createBlock($setup["AssignDraftOrderCustomerModal"], {
          key: 3,
          order: $setup.selectedOrderForDraftAssignment,
          onClose: $setup.closeDraftAssignmentModal,
          onAssigned: $setup.handleDraftAssignmentSuccess
        }, null, 8 /* PROPS */, ["order"]))
      : createCommentVNode("v-if", true)
  ], 64 /* STABLE_FRAGMENT */))
}
const OrdersTable = /*#__PURE__*/_export_sfc(_sfc_main$F, [['render',_sfc_render$a],['__scopeId',"data-v-9ff1f013"],['__file',"ordersTable.vue"]]);

const _sfc_main$E = {
  __name: 'PaginationOtherFiltersDropdown',
  props: {
  label: {
    type: String,
    required: true,
  },
  activeCount: {
    type: Number,
    default: 0,
  },
  testId: {
    type: String,
    default: "pagination-other-filters",
  },
},
  setup(__props, { expose: __expose }) {
  __expose();

const props = __props;

const isOpen = ref(false);
const root = ref(null);

const normalizedActiveCount = computed(() => {
  const parsedCount = Number.parseInt(props.activeCount, 10);
  return Number.isFinite(parsedCount) && parsedCount > 0 ? parsedCount : 0;
});

const close = () => {
  isOpen.value = false;
};

const toggle = () => {
  isOpen.value = !isOpen.value;
};

const handleDocumentClick = (event) => {
  if (!root.value || root.value.contains(event.target)) {
    return;
  }
  close();
};

const handleDocumentKeydown = (event) => {
  if (event.key === "Escape") {
    close();
  }
};

onMounted(() => {
  document.addEventListener("click", handleDocumentClick);
  document.addEventListener("keydown", handleDocumentKeydown);
});

onBeforeUnmount(() => {
  document.removeEventListener("click", handleDocumentClick);
  document.removeEventListener("keydown", handleDocumentKeydown);
});

const __returned__ = { props, isOpen, root, normalizedActiveCount, close, toggle, handleDocumentClick, handleDocumentKeydown, computed, onBeforeUnmount, onMounted, ref };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$9 = ["data-testid"];
const _hoisted_2$7 = { class: "dropdown-trigger pagination-other-filters__trigger" };
const _hoisted_3$7 = ["aria-expanded", "aria-label", "data-testid"];
const _hoisted_4$7 = ["data-testid"];
const _hoisted_5$6 = ["data-testid"];
const _hoisted_6$6 = { class: "dropdown-content pagination-other-filters__content" };
const _hoisted_7$6 = { class: "pagination-other-filters__body" };
const _hoisted_8$6 = {
  key: 0,
  class: "pagination-other-filters__footer"
};

function _sfc_render$9(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", {
    ref: "root",
    class: normalizeClass(["dropdown is-right pagination-other-filters", { 'is-active': $setup.isOpen }]),
    "data-testid": $props.testId
  }, [
    createBaseVNode("div", _hoisted_2$7, [
      createBaseVNode("button", {
        type: "button",
        class: "button is-light pagination-other-filters__button",
        "aria-expanded": $setup.isOpen ? 'true' : 'false',
        "aria-haspopup": "true",
        "aria-label": $props.label,
        "data-testid": `${$props.testId}-button`,
        onClick: withModifiers($setup.toggle, ["stop"])
      }, [
        _cache[0] || (_cache[0] = createBaseVNode("span", { class: "icon is-small" }, [
          createBaseVNode("i", {
            class: "fas fa-filter",
            "aria-hidden": "true"
          })
        ], -1 /* CACHED */)),
        createBaseVNode("span", null, toDisplayString($props.label), 1 /* TEXT */)
      ], 8 /* PROPS */, _hoisted_3$7),
      ($setup.normalizedActiveCount > 0)
        ? (openBlock(), createElementBlock("span", {
            key: 0,
            class: "tag is-info is-rounded is-small pagination-other-filters__count",
            "data-testid": `${$props.testId}-count`
          }, toDisplayString($setup.normalizedActiveCount), 9 /* TEXT, PROPS */, _hoisted_4$7))
        : createCommentVNode("v-if", true)
    ]),
    createBaseVNode("div", {
      class: "dropdown-menu pagination-other-filters__menu",
      role: "menu",
      "data-testid": `${$props.testId}-menu`
    }, [
      createBaseVNode("div", _hoisted_6$6, [
        createBaseVNode("div", _hoisted_7$6, [
          renderSlot(_ctx.$slots, "default", {}, undefined, true)
        ]),
        (_ctx.$slots.footer)
          ? (openBlock(), createElementBlock("div", _hoisted_8$6, [
              renderSlot(_ctx.$slots, "footer", {}, undefined, true)
            ]))
          : createCommentVNode("v-if", true)
      ])
    ], 8 /* PROPS */, _hoisted_5$6)
  ], 10 /* CLASS, PROPS */, _hoisted_1$9))
}
const PaginationOtherFiltersDropdown = /*#__PURE__*/_export_sfc(_sfc_main$E, [['render',_sfc_render$9],['__scopeId',"data-v-972912d0"],['__file',"PaginationOtherFiltersDropdown.vue"]]);

const ORDER_DATE_FILTER_KEYS = new Set(["created_at-date_from", "created_at-date_to"]);
const DATE_ONLY_PATTERN$1 = /^\d{4}-\d{2}-\d{2}$/;

const ORDER_DATE_EVENT_TYPE = "is-info";

const stripOrderDateFilters = (filters = "") => {
  const filterParts = String(filters || "")
    .split(",")
    .map((filter) => filter.trim())
    .filter(Boolean);

  const retainedFilters = filterParts.filter((filter) => {
    const [key] = filter.split(":");
    return !ORDER_DATE_FILTER_KEYS.has(key);
  });

  return retainedFilters.length > 0 ? retainedFilters.join(",") : null;
};

const buildOrderDateEvents = (orders = []) => {
  const dates = new Set();

  orders.forEach((order) => {
    const datePart = String(order?.created_at || "").slice(0, 10);
    if (DATE_ONLY_PATTERN$1.test(datePart)) {
      dates.add(datePart);
    }
  });

  return [...dates].sort().map((datePart) => ({
    date: parseLocalDateOnly(datePart),
    type: ORDER_DATE_EVENT_TYPE,
  }));
};

const buildOrderDateEventRequestParams = ({
  filters = null,
  search = null,
  additionalQueryParameters = {},
  orderBy = "created_at",
  orderDirection = "desc",
  page = 1,
  limit = 1000,
} = {}) => ({
  page,
  limit,
  search,
  filters: stripOrderDateFilters(filters),
  order: `${orderBy || "created_at"}:${orderDirection || "desc"}`,
  ...additionalQueryParameters,
});

const _sfc_main$D = {
  __name: 'InvoiceOrdersPagination',
  props: {
  onlyFromInvoiceCollection: {
    type: Number,
    default: 0
  },
  autoLoad: {
    type: Boolean,
    default: true
  },
  setCustomerFilter: {
    type: Number,
    default: 0
  },
  hideSearch: {
    type: Boolean,
    default: false
  },
  invoiceView: {
    type: Boolean,
    default: false
  },
  applyDefaultFilters: {
    type: Boolean,
    default: true
  },
  hidePagination: {
    type: Boolean,
    default: false
  },
  hideFilter: {
    type: Boolean,
    default: false
  },
  dates: {
    type: Object,
    default: () => ({
      dateFrom: null,
      dateTo: null
    })
  },
  groupInvoiceCollection: {
    type: Boolean,
    default: false
  },
  limitResults: {
    type: Boolean,
    default: true
  },
  showOnlyWithIds: {
    type: Array,
    default: () => []
  },
  autoExpandAll: {
    type: Boolean,
    default: false
  },
  // Additional query parameters to add to the endpoint
  queryParameters : {
    type: Object,
    default: () => ({})
  },
  excludedOrderIds: {
    type: Array, // Used to exclude specific order ids from the list, this will also ignore warnings about hidden orders
    default: () => []
  },
  includeSystemOrders: {
    type: Boolean,
    default: false
  },
  showDraftAssignmentActions: {
    type: Boolean,
    default: false
  },
  invoicePeriodFlags: {
    type: Array,
    default: () => []
  }
},
  emits: ["flagStatusChanged", "flagCreated"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();


const props = __props;
const emit = __emit;
const paginatedList = usePaginatedList();
provide(PaginatedListKey, paginatedList);

const {
  isLoading,
  list,
  loadList,
  setEndpoint,
  setMetaItemsPerPage,
  setPage,
  search,
  endpoint,
  filter,
  metaSearch,
  additionalQueryParameters,
  orderBy,
  orderDirection,
  setFilter,
  getFilter,
  setAdditionalQueryParameters,
  setOrder,
  setHideSearchField,
} = paginatedList;
const { t } = useI18n();
const router = useRouter();
const areFiltersVisible = ref(!props.hideFilter);
const filterToggleLabel = computed(() => (
  areFiltersVisible.value ? t("pagination.hide_filters") : t("pagination.show_filters")
));
const filterToggleIcon = computed(() => (areFiltersVisible.value ? "fa-chevron-up" : "fa-filter"));
setHideSearchField(props.hideSearch);
setEndpoint("/orders", false);
// If the customer filter is set, filter the orders by the customer number
if (props.setCustomerFilter > 0) {
  setFilter("customer_id", props.setCustomerFilter, false);
}
// If there are additional query parameters, set them
if (Object.keys(props.queryParameters).length > 0) {
  setAdditionalQueryParameters(props.queryParameters);
}
// If the departmentId is set, in the route, filter the orders by the departmentId
if (router.currentRoute.value.params.departmentId) {
  setOrder("created_at", "desc");
  setFilter("department_id", router.currentRoute.value.params.departmentId, false);
} else {
  setOrder("created_at", "desc");
}

// If the onlyFromInvoiceCollection prop is set, filter the orders by the invoice collection id
if (props.onlyFromInvoiceCollection > 0) {
  setFilter("invoice_collection_id", props.onlyFromInvoiceCollection, false);
}

// If the dates prop is set, filter the orders by the dateFrom and dateTo
if (props.dates) {
  if (props.dates.dateFrom !== undefined && props.dates.dateFrom !== null) {
    setFilter("created_at-date_from", props.dates.dateFrom, false);
  }
  if (props.dates.dateTo !== undefined && props.dates.dateTo !== null) {
    setFilter("created_at-date_to", props.dates.dateTo, false);
  }
}

// If the limitResults prop is set to false, do not limit the results
if (props.limitResults === false) {
  setMetaItemsPerPage(1000, false);
}

// If the includeSystemOrders prop is set to true, include system orders
if (props.includeSystemOrders) {
  setAdditionalQueryParameters({ show_wash_subscription: true });
}


// Load the list automatically if the autoLoad prop is set
if (props.autoLoad) {
  if (props.applyDefaultFilters) {
    setFilter('customer_id-has_key-OtherVaskeabonnement', '!OtherVaskeabonnement', false);
    setFilter('customer_id-has_key-OtherSpecialArrangement', '!OtherSpecialArrangement', false);
    setFilter('booked_invoice_id', 'is_null', false);
  }
  loadList();
}

const date_from = ref(props.dates?.dateFrom ?? null);
const date_to = ref(props.dates?.dateTo ?? null);
const orderDateEvents = ref([]);
const orderDateEventRequestId = ref(0);
const orderDateEventSignature = computed(() => JSON.stringify({
  endpoint: endpoint.value,
  filters: stripOrderDateFilters(filter.value),
  search: metaSearch.value,
  additionalQueryParameters: additionalQueryParameters.value,
}));

const setDateFilter = (filterKey, value, autoLoad = true) => {
  setFilter(filterKey, value || "*", autoLoad);
};

const onDateFilterChange = (filterKey, value) => {
  setDateFilter(filterKey, value, true);
};

const onDateRangeSelected = (newSelectionStartDate, newSelectionToDate) => {
  const formattedStartDate = newSelectionStartDate ? formatLocalDateOnly(newSelectionStartDate) : "";
  const formattedEndDate = newSelectionToDate ? formatLocalDateOnly(newSelectionToDate) : "";
  date_from.value = formattedStartDate;
  date_to.value = formattedEndDate;
  setDateFilter("created_at-date_from", formattedStartDate, false);
  setDateFilter("created_at-date_to", formattedEndDate, false);
  loadList();
};

const hiddenOrderFilterDefinitions = computed(() => [
  {
    key: "order-direction",
    type: "order",
    label: t("pagination.order_direction"),
    defaultValue: "desc",
    options: [
      { value: "asc", label: t("pagination.ascending") },
      { value: "desc", label: t("pagination.descending") },
    ],
  },
  {
    key: "booked-invoice-id",
    filterKey: "booked_invoice_id",
    label: t("pagination.booking_status"),
    options: [
      { value: "*", label: t("common.all") },
      { value: "not null", label: t("pagination.booked") },
      { value: "is_null", label: t("pagination.not_booked") },
    ],
  },
  {
    key: "processor",
    filterKey: "processor",
    label: t("pagination.payment_processor"),
    options: [
      { value: "*", label: t("common.all") },
      { value: "1", label: "E-conomic" },
      { value: "2", label: "Stripe" },
      { value: "3", label: t("pagination.other_no_tracking") },
      { value: "is_null", label: t("pagination.not_specified") },
    ],
  },
  {
    key: "completed-at",
    filterKey: "completed_at",
    label: t("pagination.completed"),
    options: [
      { value: "*", label: t("common.all") },
      { value: "not null", label: t("pagination.completed") },
      { value: "is_null", label: t("pagination.not_completed") },
    ],
  },
  {
    key: "invoice-selection",
    filterKey: "customer_id-has_attribute",
    label: t("pagination.invoice_selection"),
    options: [
      { value: "*", label: t("common.all") },
      { value: "invoiceAllOrdersIndividually", label: t("pagination.invoice_per_order") },
      { value: "!invoiceAllOrdersIndividually", label: t("pagination.invoice_per_month") },
    ],
  },
  {
    key: "special-agreement",
    filterKey: "customer_id-has_key-OtherSpecialArrangement",
    label: t("pagination.special_agreement"),
    options: [
      { value: "*", label: t("common.all") },
      { value: "OtherSpecialArrangement", label: t("pagination.has_special_agreement") },
      { value: "!OtherSpecialArrangement", label: t("pagination.no_special_agreement") },
    ],
  },
  {
    key: "wash-subscription",
    filterKey: "customer_id-has_key-OtherVaskeabonnement",
    label: t("pagination.wash_subscription"),
    options: [
      { value: "*", label: t("common.all") },
      { value: "OtherVaskeabonnement", label: t("pagination.has_wash_subscription") },
      { value: "!OtherVaskeabonnement", label: t("pagination.no_wash_subscription") },
    ],
  },
]);

const isActiveHiddenOrderFilterValue = (value) => (
  value !== undefined && value !== null && value !== "" && value !== "*"
);

const getHiddenOrderFilterValue = (filterDefinition) => {
  if (filterDefinition.type === "order") {
    return orderDirection.value || filterDefinition.defaultValue;
  }

  return getFilter(filterDefinition.filterKey) || "*";
};

const applyHiddenOrderFilter = (filterDefinition, value) => {
  if (filterDefinition.type === "order") {
    setOrder("created_at", value);
    loadList();
    return;
  }

  setFilter(filterDefinition.filterKey, value, true);
};

const activeHiddenOrderFiltersCount = computed(() => hiddenOrderFilterDefinitions.value.filter((filterDefinition) => {
  const value = getHiddenOrderFilterValue(filterDefinition);

  if (filterDefinition.type === "order") {
    return value !== filterDefinition.defaultValue;
  }

  return isActiveHiddenOrderFilterValue(value);
}).length);

const hasActiveHiddenOrderFilters = computed(() => activeHiddenOrderFiltersCount.value > 0);

const clearHiddenOrderFilters = () => {
  if (!hasActiveHiddenOrderFilters.value) {
    return;
  }

  hiddenOrderFilterDefinitions.value.forEach((filterDefinition) => {
    if (filterDefinition.type === "order") {
      setOrder("created_at", filterDefinition.defaultValue);
      return;
    }

    setFilter(filterDefinition.filterKey, "*", false);
  });

  loadList();
};

const doesEndpointMatch = (matcher) => {
  // Check if the endpoint matches the current endpoint
  return endpoint.value === matcher;
};

const loadOrderDateEvents = async () => {
  if (!doesEndpointMatch("/orders")) {
    orderDateEvents.value = [];
    return;
  }

  const requestId = orderDateEventRequestId.value + 1;
  orderDateEventRequestId.value = requestId;

  try {
    const rows = [];
    let page = 1;
    let totalPages = 1;
    const limit = 1000;

    while (page <= totalPages) {
      const response = await authenticatedRequest(
        "/orders",
        "GET",
        buildOrderDateEventRequestParams({
          filters: filter.value,
          search: metaSearch.value,
          additionalQueryParameters: additionalQueryParameters.value,
          orderBy: orderBy.value,
          orderDirection: orderDirection.value,
          page,
          limit,
        })
      );

      if (requestId !== orderDateEventRequestId.value) {
        return;
      }

      const pageRows = Array.isArray(response?.data?.data) ? response.data.data : [];
      rows.push(...pageRows);

      const pagination = response?.data?.meta?.pagination || {};
      const perPage = Number.parseInt(pagination.per_page, 10) || limit;
      const total = Number.parseInt(pagination.total, 10);
      totalPages = Number.isFinite(total) && total > 0
        ? Math.max(1, Math.ceil(total / Math.max(1, perPage)))
        : 1;
      page += 1;
    }

    if (requestId === orderDateEventRequestId.value) {
      orderDateEvents.value = buildOrderDateEvents(rows);
    }
  } catch (error) {
    if (requestId === orderDateEventRequestId.value) {
      console.warn("Unable to load order date events", error);
      orderDateEvents.value = [];
    }
  }
};

watch(orderDateEventSignature, () => {
  loadOrderDateEvents();
}, { immediate: true });


const __returned__ = { props, emit, paginatedList, isLoading, list, loadList, setEndpoint, setMetaItemsPerPage, setPage, search, endpoint, filter, metaSearch, additionalQueryParameters, orderBy, orderDirection, setFilter, getFilter, setAdditionalQueryParameters, setOrder, setHideSearchField, t, router, areFiltersVisible, filterToggleLabel, filterToggleIcon, date_from, date_to, orderDateEvents, orderDateEventRequestId, orderDateEventSignature, setDateFilter, onDateFilterChange, onDateRangeSelected, hiddenOrderFilterDefinitions, isActiveHiddenOrderFilterValue, getHiddenOrderFilterValue, applyHiddenOrderFilter, activeHiddenOrderFiltersCount, hasActiveHiddenOrderFilters, clearHiddenOrderFilters, doesEndpointMatch, loadOrderDateEvents, TableLabeledPagination, computed, ref, provide, watch, get useRouter() { return useRouter }, usePaginatedList, PaginatedListKey, OrdersTable, SessionUser, PaginationDisplayFilters, PaginationOtherFiltersDropdown, DatePeriodSelector, BuefyDateField, get useI18n() { return useI18n }, get formatLocalDateOnly() { return formatLocalDateOnly }, get parseLocalDateOnly() { return parseLocalDateOnly }, authenticatedRequest, get buildOrderDateEventRequestParams() { return buildOrderDateEventRequestParams }, get buildOrderDateEvents() { return buildOrderDateEvents }, get stripOrderDateFilters() { return stripOrderDateFilters } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$8 = { class: "invoice-orders-filter-toggle" };
const _hoisted_2$6 = ["aria-expanded"];
const _hoisted_3$6 = { class: "icon is-small" };
const _hoisted_4$6 = { class: "column is-narrow" };
const _hoisted_5$5 = { class: "label is-small" };
const _hoisted_6$5 = { class: "control" };
const _hoisted_7$5 = { class: "column is-narrow" };
const _hoisted_8$5 = { class: "label is-small" };
const _hoisted_9$5 = { class: "control" };
const _hoisted_10$4 = { class: "column is-12 invoice-orders-shortcuts-column" };
const _hoisted_11$4 = { class: "invoice-orders-shortcut-actions" };
const _hoisted_12$3 = { class: "invoice-orders-other-filters-trigger" };
const _hoisted_13$2 = { class: "invoice-orders-other-filters__fields" };
const _hoisted_14$2 = ["for"];
const _hoisted_15$2 = { class: "control" };
const _hoisted_16$2 = { class: "select is-fullwidth" };
const _hoisted_17$1 = ["id", "value", "data-testid", "onChange"];
const _hoisted_18$1 = ["value"];
const _hoisted_19$1 = ["disabled"];

function _sfc_render$8(_ctx, _cache, $props, $setup, $data, $options) {
  return ($setup.doesEndpointMatch('/orders'))
    ? (openBlock(), createBlock($setup["TableLabeledPagination"], {
        key: 0,
        label: $setup.SessionUser.objects.orders.meta.labels.multiple,
        "show-filters": $setup.areFiltersVisible,
        "hide-search": $setup.props.hideSearch,
        "hide-pagination": $setup.props.hidePagination
      }, createSlots({
        paginationDisplayFiltersElement: withCtx(() => [
          createVNode($setup["PaginationDisplayFilters"], { departmentColumn: 'department_id' })
        ]),
        leftPaginationColumns: withCtx(() => [
          createCommentVNode(" Date from "),
          createBaseVNode("div", _hoisted_4$6, [
            createBaseVNode("label", _hoisted_5$5, toDisplayString($setup.t('pagination.from_date')), 1 /* TEXT */),
            createBaseVNode("div", _hoisted_6$5, [
              createVNode($setup["BuefyDateField"], {
                modelValue: $setup.date_from,
                "onUpdate:modelValue": _cache[1] || (_cache[1] = $event => (($setup.date_from) = $event)),
                "value-type": "string",
                "data-testid": "invoice-orders-date-from",
                placeholder: "--.--.----",
                clearable: "",
                events: $setup.orderDateEvents,
                indicators: "dots",
                onChange: _cache[2] || (_cache[2] = (value) => $setup.onDateFilterChange('created_at-date_from', value))
              }, null, 8 /* PROPS */, ["modelValue", "events"])
            ])
          ]),
          createCommentVNode(" Date to "),
          createBaseVNode("div", _hoisted_7$5, [
            createBaseVNode("label", _hoisted_8$5, toDisplayString($setup.t('pagination.to_date')), 1 /* TEXT */),
            createBaseVNode("div", _hoisted_9$5, [
              createVNode($setup["BuefyDateField"], {
                modelValue: $setup.date_to,
                "onUpdate:modelValue": _cache[3] || (_cache[3] = $event => (($setup.date_to) = $event)),
                "value-type": "string",
                "data-testid": "invoice-orders-date-to",
                placeholder: "--.--.----",
                clearable: "",
                events: $setup.orderDateEvents,
                indicators: "dots",
                onChange: _cache[4] || (_cache[4] = (value) => $setup.onDateFilterChange('created_at-date_to', value))
              }, null, 8 /* PROPS */, ["modelValue", "events"])
            ])
          ])
        ]),
        rightPaginationColumns: withCtx(() => [
          createBaseVNode("div", _hoisted_10$4, [
            createBaseVNode("div", _hoisted_11$4, [
              createBaseVNode("div", _hoisted_12$3, [
                createVNode($setup["PaginationOtherFiltersDropdown"], {
                  label: $setup.t('pagination.other_filters'),
                  "active-count": $setup.activeHiddenOrderFiltersCount,
                  "test-id": "invoice-orders-other-filters"
                }, {
                  footer: withCtx(() => [
                    createBaseVNode("button", {
                      type: "button",
                      class: "button is-text is-small invoice-orders-other-filters__clear",
                      "data-testid": "invoice-orders-other-filters-clear",
                      disabled: !$setup.hasActiveHiddenOrderFilters,
                      onClick: $setup.clearHiddenOrderFilters
                    }, toDisplayString($setup.t('pagination.clear_all')), 9 /* TEXT, PROPS */, _hoisted_19$1)
                  ]),
                  default: withCtx(() => [
                    createBaseVNode("div", _hoisted_13$2, [
                      (openBlock(true), createElementBlock(Fragment, null, renderList($setup.hiddenOrderFilterDefinitions, (filterDefinition) => {
                        return (openBlock(), createElementBlock("div", {
                          key: filterDefinition.key,
                          class: "field invoice-orders-other-filters__field"
                        }, [
                          createBaseVNode("label", {
                            class: "label is-small",
                            for: `invoice-orders-other-filter-${filterDefinition.key}`
                          }, toDisplayString(filterDefinition.label), 9 /* TEXT, PROPS */, _hoisted_14$2),
                          createBaseVNode("div", _hoisted_15$2, [
                            createBaseVNode("div", _hoisted_16$2, [
                              createBaseVNode("select", {
                                id: `invoice-orders-other-filter-${filterDefinition.key}`,
                                value: $setup.getHiddenOrderFilterValue(filterDefinition),
                                "data-testid": `invoice-orders-other-filter-${filterDefinition.key}`,
                                onChange: $event => ($setup.applyHiddenOrderFilter(filterDefinition, $event.target.value))
                              }, [
                                (openBlock(true), createElementBlock(Fragment, null, renderList(filterDefinition.options, (option) => {
                                  return (openBlock(), createElementBlock("option", {
                                    key: option.value,
                                    value: option.value
                                  }, toDisplayString(option.label), 9 /* TEXT, PROPS */, _hoisted_18$1))
                                }), 128 /* KEYED_FRAGMENT */))
                              ], 40 /* PROPS, NEED_HYDRATION */, _hoisted_17$1)
                            ])
                          ])
                        ]))
                      }), 128 /* KEYED_FRAGMENT */))
                    ])
                  ]),
                  _: 1 /* STABLE */
                }, 8 /* PROPS */, ["label", "active-count"])
              ]),
              createCommentVNode(" Shortcuts for date filters "),
              createVNode($setup["DatePeriodSelector"], {
                "on-selection-change": $setup.onDateRangeSelected,
                visibility: { showDailySelector: false, showWeeklySelector: false, showMultipleMonthWarning: false, showUpdateButton: false, showMonthSelector: false, showStartDate: false, showEndDate: false, showSelectionValidity: false, showYearSelector: false, showToLabel: false },
                "allow-empty-selection": true,
                events: $setup.orderDateEvents,
                selection: { startDate: $setup.date_from ? $setup.parseLocalDateOnly($setup.date_from) : null, endDate: $setup.date_to ? $setup.parseLocalDateOnly($setup.date_to) : null }
              }, null, 8 /* PROPS */, ["events", "selection"])
            ])
          ])
        ]),
        default: withCtx(() => [
          createVNode($setup["OrdersTable"], {
            orders: $setup.list,
            invoiceView: $setup.props.invoiceView,
            allowSelectMultiple: true,
            "show-draft-assignment-actions": $setup.props.showDraftAssignmentActions,
            groupInvoiceCollection: $setup.props.groupInvoiceCollection,
            showOnlyWithIds: $setup.props.showOnlyWithIds,
            autoExpandAll: $setup.props.autoExpandAll,
            excludedOrderIds: $setup.props.excludedOrderIds,
            "invoice-period-flags": $setup.props.invoicePeriodFlags,
            onFlagStatusChanged: _cache[5] || (_cache[5] = (flag) => $setup.emit('flagStatusChanged', flag)),
            onFlagCreated: _cache[6] || (_cache[6] = (flag) => $setup.emit('flagCreated', flag))
          }, null, 8 /* PROPS */, ["orders", "invoiceView", "show-draft-assignment-actions", "groupInvoiceCollection", "showOnlyWithIds", "autoExpandAll", "excludedOrderIds", "invoice-period-flags"])
        ]),
        _: 2 /* DYNAMIC */
      }, [
        ($setup.props.hideFilter)
          ? {
              name: "afterSearch",
              fn: withCtx(() => [
                createBaseVNode("div", _hoisted_1$8, [
                  createBaseVNode("button", {
                    type: "button",
                    class: "button is-text is-small",
                    "data-testid": "invoice-orders-toggle-filters",
                    "aria-expanded": $setup.areFiltersVisible ? 'true' : 'false',
                    onClick: _cache[0] || (_cache[0] = $event => ($setup.areFiltersVisible = !$setup.areFiltersVisible))
                  }, [
                    createBaseVNode("span", _hoisted_3$6, [
                      createBaseVNode("i", {
                        class: normalizeClass(["fas", $setup.filterToggleIcon]),
                        "aria-hidden": "true"
                      }, null, 2 /* CLASS */)
                    ]),
                    createBaseVNode("span", null, toDisplayString($setup.filterToggleLabel), 1 /* TEXT */)
                  ], 8 /* PROPS */, _hoisted_2$6)
                ])
              ]),
              key: "0"
            }
          : undefined
      ]), 1032 /* PROPS, DYNAMIC_SLOTS */, ["label", "show-filters", "hide-search", "hide-pagination"]))
    : createCommentVNode("v-if", true)
}
const InvoiceOrdersPagination = /*#__PURE__*/_export_sfc(_sfc_main$D, [['render',_sfc_render$8],['__scopeId',"data-v-1072e5f9"],['__file',"InvoiceOrdersPagination.vue"]]);

const getOrders = () => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.get(API_URL + '/orders', {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const createOrder = (customer_id, department_id, reference, notes) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.post(API_URL + '/orders', {
    customer_id,
    department_id,
    reference,
    notes
  }, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const editOrder = (id, customer_id, department_id, reference, notes) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.put(API_URL + '/orders', {
    id,
    customer_id,
    department_id,
    reference,
    notes
  }, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const getOrder = (id, include_all = false) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.get(API_URL + `/order?id=${id}&include_all=${include_all}`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};


const getUserOrder = (id, include_all = false) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.get(API_URL + `/user/order?id=${id}&include_all=${include_all}`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const editOrderNotes = (id, notes) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.put(API_URL + '/orders', {
    id,
    notes
  }, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const _sfc_main$C = {};
const Orders$1 = /*#__PURE__*/_export_sfc(_sfc_main$C, [['__file',"Orders.vue"]]);

const _sfc_main$B = {
  __name: 'invoicesTable',
  props: ['objects'],
  setup(__props, { expose: __expose }) {
  __expose();

const { t } = useI18n();


const redirectUserObjectPage = (objectId) => {
  // Send the user to the object page
  window.location.href = `/user/orders/${objectId}`;
};

// Get the departments (If the departments are not already loaded)
if (departments.value.length === 0) {
  getDepartments();
}

// If the screen is mobile, set the is small variable to true
const isSmall = ref(window.innerWidth < 1024);

// When the window is resized, check if the screen is mobile
window.addEventListener('resize', () => {
  isSmall.value = window.innerWidth < 1024;
});


const __returned__ = { t, redirectUserObjectPage, isSmall, get useI18n() { return useI18n }, ref, departments, getDepartments, isLoading, getDepartmentName, getUserOrder };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$7 = { class: "buttons" };
const _hoisted_2$5 = ["onClick"];
const _hoisted_3$5 = { colspan: "10" };
const _hoisted_4$5 = { class: "card" };
const _hoisted_5$4 = { class: "card-content" };
const _hoisted_6$4 = { class: "is-pulled-right" };
const _hoisted_7$4 = ["onClick"];
const _hoisted_8$4 = { class: "content" };
const _hoisted_9$4 = {
  key: 1,
  class: "notification is-dark mt-6 mb-6"
};

function _sfc_render$7(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", null, [
    createBaseVNode("table", {
      class: normalizeClass(["table is-fullwidth", $setup.isSmall ? 'is-hidden' : ''])
    }, [
      createBaseVNode("thead", null, [
        createBaseVNode("tr", null, [
          createBaseVNode("th", null, toDisplayString(_ctx.$t('objects.columns.id')), 1 /* TEXT */),
          createBaseVNode("th", null, toDisplayString(_ctx.$t('objects.columns.department')), 1 /* TEXT */),
          createBaseVNode("th", null, toDisplayString(_ctx.$t('objects.bookings.columns.reg_1')), 1 /* TEXT */),
          createBaseVNode("th", null, toDisplayString(_ctx.$t('objects.orders.columns.reg_2')), 1 /* TEXT */),
          createBaseVNode("th", null, toDisplayString(_ctx.$t('objects.orders.columns.reg_3')), 1 /* TEXT */),
          createBaseVNode("th", null, toDisplayString(_ctx.$t('common.date')), 1 /* TEXT */),
          createBaseVNode("th", null, toDisplayString(_ctx.$t('tables.actions')), 1 /* TEXT */)
        ])
      ]),
      createBaseVNode("tbody", null, [
        (openBlock(true), createElementBlock(Fragment, null, renderList($props.objects, (object) => {
          return (openBlock(), createElementBlock("tr", {
            key: object.id
          }, [
            createBaseVNode("td", null, toDisplayString(object.id), 1 /* TEXT */),
            createBaseVNode("td", null, toDisplayString($setup.getDepartmentName(object.department_id)), 1 /* TEXT */),
            createBaseVNode("td", null, toDisplayString(object.reg_1), 1 /* TEXT */),
            createBaseVNode("td", null, toDisplayString(object.reg_2), 1 /* TEXT */),
            createBaseVNode("td", null, toDisplayString(object.reg_3), 1 /* TEXT */),
            createBaseVNode("td", null, toDisplayString(object.created_at), 1 /* TEXT */),
            createBaseVNode("td", null, [
              createBaseVNode("div", _hoisted_1$7, [
                createBaseVNode("button", {
                  class: "button is-small is-dark",
                  onClick: $event => ($setup.redirectUserObjectPage(object.id))
                }, toDisplayString(_ctx.$t('common.show')), 9 /* TEXT, PROPS */, _hoisted_2$5)
              ])
            ])
          ]))
        }), 128 /* KEYED_FRAGMENT */))
      ]),
      createBaseVNode("tfoot", null, [
        createBaseVNode("tr", null, [
          createBaseVNode("td", _hoisted_3$5, toDisplayString(_ctx.$t('tables.showing')) + " " + toDisplayString($props.objects.length) + " " + toDisplayString(_ctx.$t('objects.orders.multiple')), 1 /* TEXT */)
        ])
      ])
    ], 2 /* CLASS */),
    createCommentVNode(" Mobile cards "),
    ($props.objects.length > 0)
      ? (openBlock(), createElementBlock("div", {
          key: 0,
          class: normalizeClass(["columns is-multiline is-hidden-desktop mt-6 my-6", $setup.isSmall ? '' : 'is-hidden'])
        }, [
          (openBlock(true), createElementBlock(Fragment, null, renderList($props.objects, (object) => {
            return (openBlock(), createElementBlock("div", {
              class: "column is-full",
              key: object.id
            }, [
              createBaseVNode("div", _hoisted_4$5, [
                createBaseVNode("div", _hoisted_5$4, [
                  createBaseVNode("div", _hoisted_6$4, [
                    createBaseVNode("button", {
                      class: "button is-small is-dark",
                      onClick: $event => ($setup.redirectUserObjectPage(object.id))
                    }, [
                      _cache[0] || (_cache[0] = createBaseVNode("span", { class: "icon" }, [
                        createBaseVNode("i", { class: "fas fa-eye" })
                      ], -1 /* CACHED */)),
                      createBaseVNode("span", null, toDisplayString(_ctx.$t('common.show')), 1 /* TEXT */)
                    ], 8 /* PROPS */, _hoisted_7$4)
                  ]),
                  createBaseVNode("div", _hoisted_8$4, [
                    createBaseVNode("p", null, [
                      createBaseVNode("strong", null, toDisplayString(_ctx.$t('objects.columns.id')) + ":", 1 /* TEXT */),
                      createTextVNode(" " + toDisplayString(object.id), 1 /* TEXT */)
                    ]),
                    createBaseVNode("p", null, [
                      createBaseVNode("strong", null, toDisplayString(_ctx.$t('objects.columns.department')) + ":", 1 /* TEXT */),
                      createTextVNode(" " + toDisplayString($setup.getDepartmentName(object.department_id)), 1 /* TEXT */)
                    ]),
                    createBaseVNode("p", null, [
                      createBaseVNode("strong", null, toDisplayString(_ctx.$t('objects.bookings.columns.reg_1')) + ":", 1 /* TEXT */),
                      createTextVNode(" " + toDisplayString(object.reg_1), 1 /* TEXT */)
                    ]),
                    createBaseVNode("p", null, [
                      createBaseVNode("strong", null, toDisplayString(_ctx.$t('objects.orders.columns.reg_2')) + ":", 1 /* TEXT */),
                      createTextVNode(" " + toDisplayString(object.reg_2), 1 /* TEXT */)
                    ]),
                    createBaseVNode("p", null, [
                      createBaseVNode("strong", null, toDisplayString(_ctx.$t('objects.orders.columns.reg_3')) + ":", 1 /* TEXT */),
                      createTextVNode(" " + toDisplayString(object.reg_3), 1 /* TEXT */)
                    ]),
                    createBaseVNode("p", null, [
                      createBaseVNode("strong", null, toDisplayString(_ctx.$t('common.date')) + ":", 1 /* TEXT */),
                      createTextVNode(" " + toDisplayString(object.created_at), 1 /* TEXT */)
                    ])
                  ])
                ])
              ])
            ]))
          }), 128 /* KEYED_FRAGMENT */))
        ], 2 /* CLASS */))
      : createCommentVNode("v-if", true),
    createCommentVNode(" If there are no objects, show a message "),
    ($props.objects.length === 0 && $setup.isSmall)
      ? (openBlock(), createElementBlock("div", _hoisted_9$4, toDisplayString(_ctx.$t('global.no_data')), 1 /* TEXT */))
      : createCommentVNode("v-if", true)
  ]))
}
const InvoicesTable = /*#__PURE__*/_export_sfc(_sfc_main$B, [['render',_sfc_render$7],['__file',"invoicesTable.vue"]]);

const _sfc_main$A = {
  __name: 'collectedOrderInvoicesTable',
  props: {
  objects: {
    type: Array,
    default: () => [],
  },
  showEmpty: {
    type: Boolean,
    default: false,
  },
  showTotal: {
    type: Boolean,
    default: true,
  },
  isSelector: {
    type: Boolean,
    default: false,
  },
  onSelected: {
    type: Function,
    default: () => {},
  },
},
  emits: ["update:selected"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const { t } = useI18n();

const props = __props;

const emit = __emit;
const { loadList } = usePaginatedListInstance();
const redirect = (path) => {
  // Open the url in a new tab
  window.open(path, "_blank");
};

const parseTransactionCount = (value) => {
  if (typeof value === "number") {
    return value === 0 ? t("global.no_data") : value;
  } else if (typeof value === "string") {
    return parseInt(value);
  } else if (typeof value === "object") {
    return value.length;
  } else if (value === null) {
    // Handle other types if necessary
    return t("global.no_data");
  }
};

const onSelect = (id) => {
  emit("update:selected", id);
  props.onSelected(id);
};

const onSelectorChecked = (id, checked) => {
  if (checked) {
    onSelect(id);
  }
};

const __returned__ = { t, props, emit, loadList, redirect, parseTransactionCount, onSelect, onSelectorChecked, get useI18n() { return useI18n }, get BCheckbox() { return BCheckbox }, EditableTableColumn, usePaginatedListInstance, SessionUser, ActionSettingsWheelButton, ActionSettingsWheelItem, SuperuserInvoiceRowActions };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$6 = { class: "table is-fullwidth is-hoverable is-striped" };
const _hoisted_2$4 = { class: "is-narrow" };
const _hoisted_3$4 = { class: "is-narrow" };
const _hoisted_4$4 = { class: "is-narrow" };
const _hoisted_5$3 = { key: 0 };
const _hoisted_6$3 = { key: 0 };
const _hoisted_7$3 = { key: 0 };
const _hoisted_8$3 = {
  key: 1,
  class: "is-narrow"
};
const _hoisted_9$3 = {
  key: 2,
  class: "is-narrow"
};
const _hoisted_10$3 = { key: 0 };
const _hoisted_11$3 = { colspan: "9" };
const _hoisted_12$2 = { colspan: "9" };

function _sfc_render$6(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("table", _hoisted_1$6, [
    createBaseVNode("thead", null, [
      createBaseVNode("tr", null, [
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.id.label), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.global.language.customer_name), 1 /* TEXT */),
        createBaseVNode("th", _hoisted_2$4, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.customer_number.label), 1 /* TEXT */),
        createBaseVNode("th", _hoisted_3$4, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.processor.label), 1 /* TEXT */),
        createBaseVNode("th", _hoisted_4$4, toDisplayString($setup.SessionUser.objects.orders.meta.title), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString(_ctx.$t("common.status")), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.columns.created_at.label), 1 /* TEXT */),
        ($setup.props.showTotal)
          ? (openBlock(), createElementBlock("th", _hoisted_5$3, toDisplayString(_ctx.$t("tables.orders.total")), 1 /* TEXT */))
          : createCommentVNode("v-if", true),
        _cache[0] || (_cache[0] = createBaseVNode("th", null, [
          createCommentVNode(" Actions / Selector ")
        ], -1 /* CACHED */))
      ])
    ]),
    createBaseVNode("tbody", null, [
      (openBlock(true), createElementBlock(Fragment, null, renderList($setup.props.objects, (object) => {
        return (openBlock(), createElementBlock(Fragment, {
          key: object.id
        }, [
          (object.objects > 0 || $setup.props.showEmpty)
            ? (openBlock(), createElementBlock("tr", _hoisted_6$3, [
                createBaseVNode("td", null, toDisplayString(object.id), 1 /* TEXT */),
                createCommentVNode(" Customer name "),
                createVNode($setup["EditableTableColumn"], {
                  object: object,
                  loadList: $setup.loadList,
                  column: "customer_name",
                  "virtual-column": true,
                  "parse-function": (value) => value.customer_name
                }, null, 8 /* PROPS */, ["object", "loadList", "parse-function"]),
                createCommentVNode(" Customer number "),
                createVNode($setup["EditableTableColumn"], {
                  object: object,
                  loadList: $setup.loadList,
                  column: "customer_number"
                }, null, 8 /* PROPS */, ["object", "loadList"]),
                createCommentVNode(" Processor "),
                createVNode($setup["EditableTableColumn"], {
                  object: object,
                  loadList: $setup.loadList,
                  column: "processor",
                  "parse-function": 
              (value) => (value === null ? $setup.t('global.no_data') : value === 1 ? 'E-conomic' : $setup.t('global.other'))
            
                }, null, 8 /* PROPS */, ["object", "loadList", "parse-function"]),
                createCommentVNode(" Transactions "),
                createVNode($setup["EditableTableColumn"], {
                  object: object,
                  loadList: $setup.loadList,
                  column: "orders",
                  "parse-function": (value) => $setup.parseTransactionCount(value)
                }, null, 8 /* PROPS */, ["object", "loadList", "parse-function"]),
                createCommentVNode(" Closed at "),
                createVNode($setup["EditableTableColumn"], {
                  object: object,
                  loadList: $setup.loadList,
                  column: "closed_at",
                  "parse-function": (value) => (value === null ? $setup.t('global.open') : $setup.t('global.closed') + ' ' + value)
                }, null, 8 /* PROPS */, ["object", "loadList", "parse-function"]),
                createCommentVNode(" Created at "),
                createVNode($setup["EditableTableColumn"], {
                  object: object,
                  loadList: $setup.loadList,
                  column: "created_at"
                }, null, 8 /* PROPS */, ["object", "loadList"]),
                createCommentVNode(" Total net amount "),
                ($setup.props.showTotal)
                  ? (openBlock(), createElementBlock("td", _hoisted_7$3, toDisplayString($setup.SessionUser.functions.currency.toLocal(object.total_net_amount)), 1 /* TEXT */))
                  : createCommentVNode("v-if", true),
                createCommentVNode(" Actions "),
                (!$setup.props.isSelector)
                  ? (openBlock(), createElementBlock("td", _hoisted_8$3, [
                      createVNode($setup["SuperuserInvoiceRowActions"], { "include-buffer": true }, {
                        default: withCtx(() => [
                          createVNode($setup["ActionSettingsWheelButton"], null, {
                            actions: withCtx(() => [
                              createVNode($setup["ActionSettingsWheelItem"], {
                                icon: "fas fa-eye",
                                onClick: $event => ($setup.redirect('/superuser/invoices/' + object.id)),
                                label: $setup.t('common.show')
                              }, null, 8 /* PROPS */, ["onClick", "label"])
                            ]),
                            _: 2 /* DYNAMIC */
                          }, 1024 /* DYNAMIC_SLOTS */)
                        ]),
                        _: 2 /* DYNAMIC */
                      }, 1024 /* DYNAMIC_SLOTS */)
                    ]))
                  : createCommentVNode("v-if", true),
                createCommentVNode(" Selector "),
                ($setup.props.isSelector)
                  ? (openBlock(), createElementBlock("td", _hoisted_9$3, [
                      createVNode($setup["BCheckbox"], {
                        "model-value": false,
                        size: "is-small",
                        "aria-label": `${_ctx.$t('common.select')} #${object.id}`,
                        "data-testid": `collected-invoice-selector-${object.id}`,
                        "onUpdate:modelValue": (checked) => $setup.onSelectorChecked(object.id, checked)
                      }, null, 8 /* PROPS */, ["aria-label", "data-testid", "onUpdate:modelValue"])
                    ]))
                  : createCommentVNode("v-if", true)
              ]))
            : createCommentVNode("v-if", true)
        ], 64 /* STABLE_FRAGMENT */))
      }), 128 /* KEYED_FRAGMENT */)),
      createCommentVNode(" If the list is empty "),
      ($props.objects.length === 0)
        ? (openBlock(), createElementBlock("tr", _hoisted_10$3, [
            createBaseVNode("td", _hoisted_11$3, toDisplayString(_ctx.$t("global.no_data")), 1 /* TEXT */)
          ]))
        : createCommentVNode("v-if", true),
      createCommentVNode(" Show a count of the total number of objects "),
      createBaseVNode("tr", null, [
        createBaseVNode("td", _hoisted_12$2, toDisplayString(_ctx.$t("tables.showing")) + " " + toDisplayString($props.objects.length - $props.objects.filter((object) => object.objects === 0).length) + " / " + toDisplayString($props.objects.length) + " " + toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.meta.labels.multiple), 1 /* TEXT */)
      ])
    ])
  ]))
}
const CollectedOrderInvoicesTable = /*#__PURE__*/_export_sfc(_sfc_main$A, [['render',_sfc_render$6],['__file',"collectedOrderInvoicesTable.vue"]]);

const _sfc_main$z = {
  __name: 'categoriesTable',
  props: ['objects'],
  setup(__props, { expose: __expose }) {
  __expose();

const { t } = useI18n();


const { loadList } = usePaginatedListInstance();
const redirect = (path) => {
  window.location = path;
};


const __returned__ = { t, loadList, redirect, EditableTableColumn, get useI18n() { return useI18n }, ref, usePaginatedListInstance, SessionUser };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$5 = { class: "table is-fullwidth" };
const _hoisted_2$3 = { key: 0 };
const _hoisted_3$3 = { colspan: "4" };
const _hoisted_4$3 = { colspan: "4" };

function _sfc_render$5(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("table", _hoisted_1$5, [
    createBaseVNode("thead", null, [
      createBaseVNode("tr", null, [
        createBaseVNode("th", null, toDisplayString(_ctx.$t('objects.columns.id')), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString(_ctx.$t('tables.categories.name')), 1 /* TEXT */),
        createBaseVNode("th", null, toDisplayString(_ctx.$t('common.description')), 1 /* TEXT */)
      ])
    ]),
    createBaseVNode("tbody", null, [
      (openBlock(true), createElementBlock(Fragment, null, renderList($props.objects, (category) => {
        return (openBlock(), createElementBlock("tr", {
          key: category.id
        }, [
          createBaseVNode("td", null, toDisplayString(category.id), 1 /* TEXT */),
          createCommentVNode(" Name "),
          createVNode($setup["EditableTableColumn"], {
            object: category,
            loadList: $setup.loadList,
            editFunction: $setup.SessionUser.objects.categories.showEditObjectFieldForm,
            column: "name"
          }, null, 8 /* PROPS */, ["object", "loadList", "editFunction"]),
          createCommentVNode(" Description "),
          createVNode($setup["EditableTableColumn"], {
            object: category,
            loadList: $setup.loadList,
            editFunction: $setup.SessionUser.objects.categories.showEditObjectFieldForm,
            column: "description"
          }, null, 8 /* PROPS */, ["object", "loadList", "editFunction"])
        ]))
      }), 128 /* KEYED_FRAGMENT */)),
      createCommentVNode(" If the list is empty "),
      ($props.objects.length === 0)
        ? (openBlock(), createElementBlock("tr", _hoisted_2$3, [
            createBaseVNode("td", _hoisted_3$3, toDisplayString(_ctx.$t('global.no_data')), 1 /* TEXT */)
          ]))
        : createCommentVNode("v-if", true),
      createCommentVNode(" Show a count of the total number of categories "),
      createBaseVNode("tr", null, [
        createBaseVNode("td", _hoisted_4$3, toDisplayString(_ctx.$t('tables.showing')) + " " + toDisplayString($props.objects.length) + " " + toDisplayString($setup.SessionUser.objects.categories.meta.labels.multiple), 1 /* TEXT */)
      ])
    ])
  ]))
}
const CategoriesTable = /*#__PURE__*/_export_sfc(_sfc_main$z, [['render',_sfc_render$5],['__file',"categoriesTable.vue"]]);

const _sfc_main$y = {
  __name: 'CollectedOrderInvoicesPagination',
  props: {
  setCustomerFilter: {
    type: Number,
    default: null
  },
  hideSearch: {
    type: Boolean,
    default: false
  },
  autoLoad: {
    type: Boolean,
    default: true
  },
  onlyReadyToInvoice: {
    type: Boolean,
    default: false
  },
  tableProps: {
    type: Object,
    default: () => ({})
  },
  displayClosed: {
    type: Boolean,
    default: true
  },
  displayBooked: {
    type: Boolean,
    default: true
  },
},
  setup(__props, { expose: __expose }) {
  __expose();


const props = __props;

const { t } = useI18n();
const router = useRouter();
if (!props.onlyReadyToInvoice || props.onlyReadyToInvoice === false) {
  setEndpoint("/collected-invoices", false);
} else {
  setEndpoint("/collected-invoices/ready-to-invoice", false);
}
setOrder("closed_at", "asc", false);
// Hide the search field if the prop is set to true
setHideSearchField(props.hideSearch);

if (props.setCustomerFilter) {
  setFilter("customer_number", props.setCustomerFilter, false);
}

if (!props.displayClosed) {
  setFilter("closed_at", 'is_null', false);
}

if (!props.displayBooked) {
  setFilter("booked_invoice_id", 'is_null', false);
}

if (props.autoLoad) {
  loadList();
}


const __returned__ = { props, t, router, CollectedOrderInvoicesTable, get useRouter() { return useRouter }, isLoaded, isLoading: isLoading$1, list, loadList, metaCurrentPage, metaItemsPerPage, metaTotalItems, setEndpoint, setMetaItemsPerPage, setPage, metaSearch, search, setFilter, setOrder, hideSearchField, setHideSearchField, PaginationNavigation, SessionUser, LoadButtonWhileAwait, PaginationDisplay, OrdersTable, CategoriesTable, get useI18n() { return useI18n } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$4 = ["placeholder"];

function _sfc_render$4(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock(Fragment, null, [
    (!$setup.hideSearchField)
      ? (openBlock(), createElementBlock("input", {
          key: 0,
          onInput: _cache[0] || (_cache[0] = $event => ($setup.search($event.target.value))),
          class: "input",
          type: "text",
          placeholder: _ctx.$t('global.search_for') + ' ' + $setup.SessionUser.objects.collectedOrderInvoices.meta.labels.single
        }, null, 40 /* PROPS, NEED_HYDRATION */, _hoisted_1$4))
      : createCommentVNode("v-if", true),
    createVNode($setup["PaginationDisplay"], {
      metaItemsPerPage: $setup.metaItemsPerPage,
      loadFunction: $setup.loadList,
      isLoading: $setup.isLoading,
      setMetaItemsPerPage: $setup.setMetaItemsPerPage
    }, null, 8 /* PROPS */, ["metaItemsPerPage", "loadFunction", "isLoading", "setMetaItemsPerPage"]),
    createVNode($setup["CollectedOrderInvoicesTable"], mergeProps({
      objects: $setup.list,
      loadList: $setup.loadList
    }, $props.tableProps), null, 16 /* FULL_PROPS */, ["objects", "loadList"]),
    createVNode($setup["PaginationNavigation"], {
      currentPage: $setup.metaCurrentPage,
      totalPages: Math.ceil($setup.metaTotalItems / $setup.metaItemsPerPage),
      loadFunction: $setup.loadList,
      setPage: $setup.setPage,
      isLoading: $setup.isLoading
    }, null, 8 /* PROPS */, ["currentPage", "totalPages", "loadFunction", "setPage", "isLoading"]),
    createVNode($setup["LoadButtonWhileAwait"], {
      class: "is-dark",
      isLoading: $setup.isLoading,
      loadFunction: $setup.loadList,
      icon: "fas fa-sync-alt"
    }, {
      default: withCtx(() => [
        createTextVNode(toDisplayString($setup.t('pagination.reload')), 1 /* TEXT */)
      ]),
      _: 1 /* STABLE */
    }, 8 /* PROPS */, ["isLoading", "loadFunction"])
  ], 64 /* STABLE_FRAGMENT */))
}
const CollectedOrderInvoicesPagination = /*#__PURE__*/_export_sfc(_sfc_main$y, [['render',_sfc_render$4],['__file',"CollectedOrderInvoicesPagination.vue"]]);

const _sfc_main$x = {
  __name: 'PickCustomerInvoiceCollectionModal',
  props: {
  customer_id: {
    type: Number,
    default: null,
    required: true,
  },
  onInvoiceCollectionSelected: {
    type: Function,
    default: () => {}
  },
  onClose: {
    type: Function,
    default: () => {}
  },
},
  emits: ["closeModal", "saveChanges"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();

const props = __props;


const emit = __emit;

const closeModal = () => {
  emit("closeModal");
  props.onClose();
};

// Listen for esc key to close the modal
const handleKeydown = (event) => {
  if (event.key === "Escape") {
    closeModal();
  }
};
window.addEventListener("keydown", handleKeydown);

const ucFirst = (str) => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

const selectInvoiceCollection = (invoiceCollection) => {
  props.onInvoiceCollectionSelected(invoiceCollection);
  emit("saveChanges", invoiceCollection);
};

const get_invoice_collection_object = (invoiceCollection) => {
  return {
    id: invoiceCollection.id, // The invoice collection ID
    customer_number: props.customer_id ?? null, // The customer number associated with the invoice collection
    customer_name: invoiceCollection.customer_name ?? null, // The name of the customer associated with the invoice collection
    created_at: invoiceCollection.created_at ?? null, // The date the invoice collection was created
    updated_at: invoiceCollection.updated_at ?? null, // The date the invoice collection was last updated
    closed_at: invoiceCollection.closed_at ?? null, // The date the invoice collection was closed (if applicable)
    processor: invoiceCollection.processor ?? null, // The processor associated with the invoice collection (if applicable)
    external_id: invoiceCollection.external_id ?? null, // The external ID associated with the invoice collection (if applicable)
    orders: [], // The orders associated with the invoice collection
  }
};
const invoice_collections = ref([
    get_invoice_collection_object({
      id: 1,
      customer_number: props.customer_id,
      created_at: "2023-10-01",
      updated_at: "2023-10-02",
      closed_at: null,
      processor: 1,
      external_id: "EXT-001",
    }),
    get_invoice_collection_object({
      id: 2,
      customer_number: props.customer_id,
      created_at: "2023-10-03",
      updated_at: "2023-10-04",
      closed_at: null,
      processor: 2,
      external_id: "EXT-002",
    }),
    get_invoice_collection_object({
      id: 3,
      customer_number: props.customer_id,
      created_at: "2023-10-05",
      updated_at: "2023-10-06",
      closed_at: null,
      processor: 3,
      external_id: "EXT-003",
    }),
    get_invoice_collection_object({
      id: 4,
      customer_number: props.customer_id,
      created_at: "2023-10-07",
      updated_at: "2023-10-08",
      closed_at: null,
      processor: 4,
      external_id: "EXT-004",
    }),
]);

const selectedDate = ref('');

const onClickCreateNewInvoiceCollection = async () => {
  // Logic to create a new invoice collection
  console.log("Creating new invoice collection... Selected date:", selectedDate.value);
  await SessionUser.objects.collectedOrderInvoices.add(
      props.customer_id,
      'Manual invoice collection',
      'Created by user',
      selectedDate.value
  ).then((response) => {
    console.log(response.data.data.id, "Invoice collection created successfully");
    // Select the newly created invoice collection
    selectInvoiceCollection(parseInt(response.data.data.id));
  }).catch((error) => {
    console.error(error, "Error creating invoice collection");
  });
};

const tabs = ref([
  { name: SessionUser.objects.collectedOrderInvoices.meta.title, slot: 'collectedOrderInvoices', icon: 'fas fa-file-invoice-dollar', hidden: false },
  { name: SessionUser.objects.global.language.add + ' ' + SessionUser.objects.collectedOrderInvoices.meta.labels.single.toLowerCase(), slot: 'createNewInvoiceCollection', icon: 'fas fa-plus', hidden: false },
]);



const __returned__ = { props, emit, closeModal, handleKeydown, ucFirst, selectInvoiceCollection, get_invoice_collection_object, invoice_collections, selectedDate, onClickCreateNewInvoiceCollection, tabs, ref, SessionUser, InvoiceOrdersPagination, ElementTabsBox, CollectedOrderInvoicesOverview, customer_id, searchAndSelectCustomer, isCustomerSelected, PosSelectedCustomer, CollectedOrderInvoices: CollectedOrderInvoices$1, VehiclesPagination, VehiclesTable, OrdersTable, InvoicesTable, CollectedOrderInvoicesTable, CollectedOrderInvoicesPagination, BuefyDateField };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

};

const _hoisted_1$3 = {
  class: "modal is-active",
  ref: "modal"
};
const _hoisted_2$2 = {
  class: "modal-card",
  style: {"width":"90%!important"}
};
const _hoisted_3$2 = { class: "modal-card-head" };
const _hoisted_4$2 = { class: "modal-card-title" };
const _hoisted_5$2 = { class: "modal-card-body" };
const _hoisted_6$2 = { class: "content" };
const _hoisted_7$2 = { class: "field" };
const _hoisted_8$2 = { class: "label" };
const _hoisted_9$2 = { class: "control" };
const _hoisted_10$2 = { class: "has-text-centered" };
const _hoisted_11$2 = ["disabled"];

function _sfc_render$3(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", _hoisted_1$3, [
    createBaseVNode("div", {
      class: "modal-background",
      onClick: $setup.closeModal
    }),
    createBaseVNode("div", _hoisted_2$2, [
      createBaseVNode("header", _hoisted_3$2, [
        createBaseVNode("p", _hoisted_4$2, toDisplayString($setup.SessionUser.objects.global.language.select) + " " + toDisplayString($setup.SessionUser.objects.global.language.invoice.toLowerCase()) + " ( " + toDisplayString($setup.props.customer_id) + " )", 1 /* TEXT */),
        createBaseVNode("button", {
          class: "delete",
          "aria-label": "close",
          onClick: $setup.closeModal
        })
      ]),
      createBaseVNode("section", _hoisted_5$2, [
        createBaseVNode("div", _hoisted_6$2, [
          createCommentVNode(" Create a new invoice collection form "),
          createCommentVNode(" Date: 2023-10-01 "),
          createVNode($setup["ElementTabsBox"], {
            tabs: $setup.tabs,
            "default-active-tab": $setup.tabs[0].slot,
            "allow-compact-when-one-tab": true
          }, {
            collectedOrderInvoices: withCtx(() => [
              createCommentVNode(" Invoice Collections table "),
              createVNode($setup["CollectedOrderInvoicesPagination"], {
                "set-customer-filter": $setup.props.customer_id,
                "table-props": {
                showEmpty: true,
                showTotal: false,
                isSelector: true,
                onSelected: $setup.selectInvoiceCollection,
              },
                "display-booked": false
              }, null, 8 /* PROPS */, ["set-customer-filter", "table-props"])
            ]),
            createNewInvoiceCollection: withCtx(() => [
              createCommentVNode(" Date picker "),
              createBaseVNode("div", _hoisted_7$2, [
                createBaseVNode("label", _hoisted_8$2, toDisplayString($setup.SessionUser.objects.global.language.select) + " " + toDisplayString($setup.SessionUser.objects.global.language.invoice.toLowerCase()) + " " + toDisplayString($setup.SessionUser.objects.global.language.time.date.toLowerCase()), 1 /* TEXT */),
                createBaseVNode("div", _hoisted_9$2, [
                  createVNode($setup["BuefyDateField"], {
                    modelValue: $setup.selectedDate,
                    "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (($setup.selectedDate) = $event)),
                    "value-type": "string",
                    "data-testid": "invoice-collection-date"
                  }, null, 8 /* PROPS */, ["modelValue"])
                ])
              ]),
              createCommentVNode(" Create invoice collection button "),
              createBaseVNode("div", _hoisted_10$2, [
                createBaseVNode("button", {
                  class: "button is-primary",
                  onClick: $setup.onClickCreateNewInvoiceCollection,
                  disabled: !$setup.selectedDate
                }, [
                  _cache[1] || (_cache[1] = createBaseVNode("span", { class: "icon" }, [
                    createBaseVNode("i", { class: "fas fa-plus" })
                  ], -1 /* CACHED */)),
                  createBaseVNode("span", null, toDisplayString($setup.SessionUser.objects.global.language.add) + " " + toDisplayString($setup.SessionUser.objects.collectedOrderInvoices.meta.labels.single.toLowerCase()), 1 /* TEXT */)
                ], 8 /* PROPS */, _hoisted_11$2)
              ])
            ]),
            _: 1 /* STABLE */
          }, 8 /* PROPS */, ["tabs", "default-active-tab"])
        ])
      ]),
      _cache[2] || (_cache[2] = createBaseVNode("footer", { class: "modal-card-foot" }, [
        createCommentVNode(" ")
      ], -1 /* CACHED */))
    ])
  ], 512 /* NEED_PATCH */))
}
const PickCustomerInvoiceCollectionModal = /*#__PURE__*/_export_sfc(_sfc_main$x, [['render',_sfc_render$3],['__file',"PickCustomerInvoiceCollectionModal.vue"]]);

const t$d = (key) => i18n.global.t(key);

// Define a function to show the modal with the Vue component
const showInvoiceCollectionPickerModal = async (customerNumber, onSuccessFunction = () => {}) => {
  // Create a container element for the Vue component
  const div = document.createElement('div');
  let selectedInvoiceCollectionId = null;

  // Dynamically create and mount the Vue component
  // And add a prop to the component "onCustomerSelected"
  const app = createApp(PickCustomerInvoiceCollectionModal, {
    customer_id: customerNumber,
    onInvoiceCollectionSelected: async (selected_invoice_collection_id) => {
      if (!selected_invoice_collection_id) {
        Swal.fire({
          icon: 'error',
          title: 'Ingen faktura samling valgt',
          timer: 2000,
        });
        return null;
      }
      // Handle the customer selection here
      console.log('Selected invoice collection ID:', selected_invoice_collection_id);
      // Return the selected invoice collection ID
      // Call the onSuccess function with the selected invoice collection ID
      await onSuccessFunction(selected_invoice_collection_id);
      selectedInvoiceCollectionId = selected_invoice_collection_id;
      // Close the modal
      Swal.close();
    },
    onClose: () => {
      // Close the modal
      Swal.close();
      // Return
    }
  });

  // This modal is mounted via a standalone Vue app instance.
  // Install i18n explicitly so nested components using useI18n() work.
  app.use(i18n);


  // Mount the Vue app to the dynamically created `div`
  app.mount(div);

  // Show SweetAlert2 dialog with the Vue component rendered inside
  await Swal.fire({
    html: div, // Include the Vue component’s container
    showCancelButton: false,
    showConfirmButton: false,
    allowOutsideClick: false,
    heightAuto: true,
    didDestroy: () => {
      // Clean up the Vue app when the modal is closed
      app.unmount();
    }
  }).finally(() => {
    // Return the selected invoice collection ID
    return selectedInvoiceCollectionId;
  });
};

const showCreateCustomInvoiceCollectionForm = async (customerNumber) => {
  if (!customerNumber) {
    Swal.fire({
      icon: 'error',
      title: 'Ingen kunde valgt',
      timer: 2000,
    });
    return null;
  }
  // Ask for the date of the invoice collection
  const { value: date } = await Swal.fire({
    title: 'Opret ny faktura samling',
    input: 'text',
    inputLabel: 'Dato for faktura samling',
    inputPlaceholder: 'YYYY-MM-DD',
    showCancelButton: true,
    confirmButtonText: 'Opret',
    cancelButtonText: 'Annuller',
    inputValidator: (value) => {
      if (!value) {
        return 'Du skal indtaste en dato!'
      }
    }
  });
  if (date) {
    console.log('Creating new invoice collection... ', date, ' for customer: ', customerNumber);
  } else {
    console.log('Cancelled creating new invoice collection');
    return null;
  }
};

const normalizeClosedAtForDateInput = (value) => {
  if (!value) {
    return '';
  }

  if (value instanceof Date) {
    if (Number.isNaN(value.getTime())) {
      return '';
    }
    return `${value.getFullYear()}-${padTwoDigits(value.getMonth() + 1)}-${padTwoDigits(value.getDate())}`;
  }

  const parsed = String(value).trim();

  if (!parsed) {
    return '';
  }

  const directMatch = parsed.match(/^(\d{4}-\d{2}-\d{2})/);
  if (directMatch && directMatch[1]) {
    return directMatch[1];
  }

  const parsedDate = new Date(parsed);
  if (Number.isNaN(parsedDate.getTime())) {
    return '';
  }

  return `${parsedDate.getFullYear()}-${padTwoDigits(parsedDate.getMonth() + 1)}-${padTwoDigits(parsedDate.getDate())}`;
};

const padTwoDigits = (value) => String(value).padStart(2, '0');

const normalizeClosedAtForApi = (value) => {
  if (!value) {
    return null;
  }

  if (value instanceof Date) {
    if (Number.isNaN(value.getTime())) {
      return null;
    }

    return `${value.getFullYear()}-${padTwoDigits(value.getMonth() + 1)}-${padTwoDigits(value.getDate())}`;
  }

  const inputValue = String(value).trim();
  if (!inputValue) {
    return null;
  }

  const directMatch = inputValue.match(/^(\d{4}-\d{2}-\d{2})/);
  if (directMatch && directMatch[1]) {
    return directMatch[1];
  }

  const parsedDate = new Date(inputValue);
  if (Number.isNaN(parsedDate.getTime())) {
    return null;
  }

  return `${parsedDate.getFullYear()}-${padTwoDigits(parsedDate.getMonth() + 1)}-${padTwoDigits(parsedDate.getDate())}`;
};

const mountSweetAlertDateField$1 = ({ mountId, inputId, initialValue, dataTestid }) => {
  const mountElement = document.getElementById(mountId);
  const inputElement = document.getElementById(inputId);

  if (!mountElement || !inputElement) {
    return {
      cleanup: () => {},
      setValue: () => {},
    };
  }

  const value = ref(initialValue || "");
  const app = createApp({
    setup() {
      watch(value, (nextValue) => {
        inputElement.value = nextValue || "";
      }, { immediate: true });

      return () => h(BuefyDateField, {
        modelValue: value.value,
        valueType: "string",
        dataTestid,
        "onUpdate:modelValue": (nextValue) => {
          value.value = nextValue || "";
        },
      });
    },
  });

  app.use(i18n);
  app.mount(mountElement);

  return {
    cleanup: () => {
      app.unmount();
    },
    setValue: (nextValue) => {
      const normalizedValue = nextValue || "";
      value.value = normalizedValue;
      inputElement.value = normalizedValue;
    },
  };
};

const showEditClosedAtObjectFieldForm = async (id, value, onAfterSubmit = null) => {
  const inputId = 'collected-order-invoice-closed-at-input';
  const pickerId = 'collected-order-invoice-closed-at-picker';
  const clearButtonId = 'collected-order-invoice-closed-at-clear-button';
  let dateField = null;

  return Swal.fire({
    title: ObjectsGlobal.language.field(CollectedOrderInvoices, 'closed_at'),
    html: `<div class="field">
      <label class="label has-text-black">${CollectedOrderInvoices.columns.closed_at.label}</label>
      <div class="control mb-3">
        <input type="hidden" id="${inputId}" value="${normalizeClosedAtForDateInput(value)}">
        <div id="${pickerId}" data-testid="collected-order-invoice-closed-at-picker"></div>
      </div>
      <div class="control">
        <button id="${clearButtonId}" type="button" class="button is-light is-small">${ObjectsGlobal.language.clear}</button>
      </div>
    </div>`,
    showCancelButton: true,
    confirmButtonText: ObjectsGlobal.language.save,
    cancelButtonText: ObjectsGlobal.language.cancel,
    didOpen: () => {
      dateField = mountSweetAlertDateField$1({
        mountId: pickerId,
        inputId,
        initialValue: normalizeClosedAtForDateInput(value),
        dataTestid: "collected-order-invoice-closed-at-input",
      });
      const clearButton = document.getElementById(clearButtonId);
      if (clearButton) {
        clearButton.addEventListener('click', () => {
          dateField?.setValue('');
        });
      }
    },
    willClose: () => {
      dateField?.cleanup();
      dateField = null;
    },
    preConfirm: () => {
      const inputElement = document.getElementById(inputId);
      if (!inputElement) {
        Swal.showValidationMessage('Kunne ikke finde inputfelt for dato.');
        return false;
      }

      const newValue = inputElement.value ? inputElement.value : null;

      if (newValue !== null && !/^\d{4}-\d{2}-\d{2}$/.test(newValue)) {
        Swal.showValidationMessage('Ugyldig dato.');
        return false;
      }

      return CollectedOrderInvoices.set.closed_at(id, newValue).then(() => {
        if (onAfterSubmit !== null) {
          onAfterSubmit();
        }
      }).catch((error) => {
        Swal.showValidationMessage(`Fejl: ${error.message || error}`);
        return false;
      });
    }
  });
};

/**
 * The CollectOrderInvoices object
 */
const CollectedOrderInvoices = {
  get meta() {
    return {
      title: t$d('objects.collected_order_invoices.title'),
      icon: "fas fa-list",
      description: t$d('objects.collected_order_invoices.description'),
      endpoint: "/collected-invoices",
      labels: {
        single: t$d('objects.collected_order_invoices.single'),
        multiple: t$d('objects.collected_order_invoices.multiple'),
      }
    };
  },
  get columns() {
    return {
      id: {
        label: t$d('objects.columns.id'),
        type: "number",
        sortable: true,
        creation: {
          required: false
        }
      },
      customer_number: {
        label: t$d('objects.columns.customer_number'),
        type: "number",
        sortable: true,
        creation: {
          required: true
        }
      },
      name: {
        label: t$d('common.name'),
        type: "string",
        sortable: true,
        creation: {
          required: false
        }
      },
      notes: {
        label: t$d('objects.columns.notes'),
        type: "string",
        sortable: true,
        creation: {
          required: false
        }
      },
      processor: {
        label: t$d('objects.columns.processor'),
        type: "number",
        sortable: true,
        creation: {
          required: false
        }
      },
      external_id: {
        label: t$d('objects.columns.external_id'),
        type: "number",
        sortable: true,
        creation: {
          required: false
        }
      },
      po_number: {
        label: t$d('objects.columns.po_number'),
        type: "string",
        sortable: true,
        creation: {
          required: false
        }
      },
      closed_at: {
        label: t$d('objects.columns.closed_at'),
        type: "date",
        sortable: true,
        creation: {
          required: false
        }
      },
      created_at: {
        label: t$d('common.created'),
        type: "date",
        sortable: true,
        creation: {
          required: false
        }
      },
      updated_at: {
        label: t$d('objects.columns.updated_at'),
        type: "date",
        sortable: true,
        creation: {
          required: false
        }
      },
      total_net_amount: {
        label: t$d('objects.columns.total_net_amount'),
        type: "number",
        sortable: false,
        creation: {
          required: false
        }
      },
    };
  },
  add: async (customer_number, name, description, closed_at = null) => {
    return ObjectsGlobal.add.object(
        CollectedOrderInvoices.meta.endpoint,
        {
          customer_number: parseInt(customer_number),
          name: name,
          description: description,
          closed_at: closed_at,
        }
    );
  },
  set: {
    name: async (id, name) => {
      return ObjectsGlobal.set.column(
        CollectedOrderInvoices.meta.endpoint,
        id,
        "name",
        name
      )
    },
    notes: async (id, notes) => {
      return ObjectsGlobal.set.column(
        CollectedOrderInvoices.meta.endpoint,
        id,
        "notes",
        notes
      )
    },
    processor: async (id, processor = null) => {
      return ObjectsGlobal.set.column(
        CollectedOrderInvoices.meta.endpoint,
        id,
        "processor",
        processor ? parseInt(processor) : null
      )
    },
    external_id: async (id, external_id) => {
      return ObjectsGlobal.set.column(
        CollectedOrderInvoices.meta.endpoint,
        id,
        "external_id",
        parseInt(external_id)
      )
    },
    po_number: async (id, po_number) => {
      return ObjectsGlobal.set.column(
        CollectedOrderInvoices.meta.endpoint,
        id,
        "po_number",
        po_number
      )
    },
    closed_at: async (id, closed_at) => {
      const apiClosedAt = normalizeClosedAtForApi(closed_at);
      if (closed_at && !apiClosedAt) {
        throw new Error('Invalid date format. Expected: Y-m-d');
      }

      return ObjectsGlobal.set.column(
        CollectedOrderInvoices.meta.endpoint,
        id,
        "closed_at",
        apiClosedAt
      )
    }
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(CollectedOrderInvoices.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(CollectedOrderInvoices.meta.endpoint, id);
    }
  },
  functions: {
    download: async (id) => {
      // Send the request
      return authenticatedRequest('/invoices/pdf', 'GET', {
        id: parseInt(id)
      }).then((response) => {
        //console.warn(response);
        // Create a blob from the response
        window.open(response.data.data.url, '_blank');
        return response;
      }).catch((error) => {
        Swal.fire({
          title: 'Der skete en fejl under hentning af PDF',
          text: SessionUser.functions.parseErrorMessage(error),
          icon: 'error'
        });
        throw error;
      });
    },
    split_invoice: async (id) => {
      // Send the request
      return authenticatedRequest('/collected-invoices/split', 'POST', {
        id: parseInt(id)
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    split_by_month: async (dateFrom, dateTo, options = {}) => {
      const invoiceCollectionIds = Array.isArray(options.invoiceCollectionIds)
        ? options.invoiceCollectionIds
        : options.invoice_collection_ids;
      return authenticatedRequest('/collected-invoices/split-by-month', 'POST', {
        dateFrom,
        dateTo,
        ...(options.preview !== undefined ? { preview: !!options.preview } : {}),
        ...(Array.isArray(invoiceCollectionIds) ? { invoice_collection_ids: invoiceCollectionIds } : {}),
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    bulk_action_preview: async (action, invoiceCollectionIds = [], options = {}, locale = null) => {
      return authenticatedRequest('/collected-invoices/bulk-actions/preview', 'POST', {
        action,
        invoice_collection_ids: invoiceCollectionIds.map((id) => parseInt(id)).filter((id) => Number.isInteger(id) && id > 0),
        options,
        ...(locale ? { locale } : {}),
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    bulk_action_apply: async ({
      preview_id,
      action,
      invoice_collection_ids = [],
      options = {},
      confirmation_text,
      locale = null,
    }) => {
      return authenticatedRequest('/collected-invoices/bulk-actions/apply', 'POST', {
        preview_id,
        action,
        invoice_collection_ids: invoice_collection_ids.map((id) => parseInt(id)).filter((id) => Number.isInteger(id) && id > 0),
        options,
        confirmation_text,
        ...(locale ? { locale } : {}),
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    move_to_customer: async (id, customerNumber) => {
      const invoiceCollectionId = parseInt(id);
      const targetCustomerNumber = parseInt(customerNumber);

      if (!Number.isInteger(invoiceCollectionId) || invoiceCollectionId <= 0) {
        throw new Error('Invalid invoice collection id');
      }

      if (!Number.isInteger(targetCustomerNumber) || targetCustomerNumber <= 0) {
        throw new Error('Invalid customer number');
      }

      return authenticatedRequest('/collected-invoices/move-to-customer', 'POST', {
        id: invoiceCollectionId,
        customer_number: targetCustomerNumber,
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    showCreateNewCustom: showCreateCustomInvoiceCollectionForm,
    showInvoiceCollectionPickerForm: showInvoiceCollectionPickerModal,
    add_vehicle_subscriptions: async (id) => {
      // Send the request
      return authenticatedRequest('/collected-invoices/vehicle-subscriptions', 'POST', {
        id: parseInt(id)
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    add_fixed_pricing: async (id) => {
      // Send the request
      return authenticatedRequest('/collected-invoices/fixed-price', 'POST', {
        id: parseInt(id)
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    stripe: {
      book_invoice: async (id) => {
        // Send the request
        return authenticatedRequest('/collected-invoices/stripe/book', 'POST', {
          id: parseInt(id)
        }).then((response) => {
          console.log(response);
          return response;
        }).catch((error) => {
          console.log(error);
          throw error;
        });
      },
    },
    economic: {
      queue: {
        list: async (filters = {}) => {
          return authenticatedRequest('/collected-invoices/economic/queue', 'GET', filters).then((response) => {
            return response;
          }).catch((error) => {
            console.log(error);
            throw error;
          });
        },
        run: async (limit = 10) => {
          return runEconomicTransferQueueBatch({
            endpoint: '/collected-invoices/economic/queue/run',
            limit,
            requestFn: authenticatedRequest,
          }).catch((error) => {
            console.log(error);
            throw error;
          });
        },
        status: async (job_id) => {
          return fetchEconomicTransferJobStatus({
            endpoint: '/collected-invoices/economic/queue/status',
            jobId: job_id,
            requestFn: authenticatedRequest,
          }).catch((error) => {
            console.log(error);
            throw error;
          });
        },
        retry: async (job_id) => {
          return retryEconomicTransferJob({
            endpoint: '/collected-invoices/economic/queue/retry',
            jobId: job_id,
            requestFn: authenticatedRequest,
          }).catch((error) => {
            console.log(error);
            throw error;
          });
        },
        monitor: async (limit = 50) => {
          return fetchEconomicTransferQueueMonitor({
            limit,
            requestFn: authenticatedRequest,
          }).catch((error) => {
            console.log(error);
            throw error;
          });
        },
        dismiss: async (job_id) => {
          return dismissEconomicTransferQueueJob({
            jobId: job_id,
            requestFn: authenticatedRequest,
          }).catch((error) => {
            console.log(error);
            throw error;
          });
        },
        dismissTerminal: async () => {
          return dismissTerminalEconomicTransferQueueJobs({
            requestFn: authenticatedRequest,
          }).catch((error) => {
            console.log(error);
            throw error;
          });
        },
      },
      runCheckDrafts: async () => {
        // Send the request
        return authenticatedRequest('/collected-invoices/economic/run/check-drafts', 'POST', {}).then((response) => {
          console.log(response);
          return response;
        }).catch((error) => {
          console.log(error);
          throw error;
        });
      },
      runCheckErrors: async () => {
        // Send the request
        return authenticatedRequest('/collected-invoices/economic/run/check-errors', 'POST', {}).then((response) => {
          console.log(response);
          return response;
        }).catch((error) => {
          console.log(error);
          throw error;
        });
      },
      compareToEconomic: async (id) => {
        /**
         * Result example:
         * {
         *   "success": true,
         *   "data": {
         *     "collected_invoice_id": 10133,
         *     "draft_id": null,
         *     "booked_id": 28368,
         *     "warnings": [
         *       "Error fetching draft ID: Invoice draft with external id (2ced7a3f-fab2-edbd-075f-ce981867c340) not found"
         *     ],
         *     "draft_total": null,
         *     "booked_total": 694,
         *     "difference": null,
         *     "internal_total": 694
         *   },
         *   "meta": [],
         *   "includes": []
         * }
         */
        // Send the request
        return authenticatedRequest('/collected-invoices/economic/compare', 'GET', {
          collected_invoice_id: parseInt(id)
        }).then((response) => {
          console.warn(response);
          return response;
        }).catch((error) => {
          console.warn(error);
          throw error;
        });
      },
      v2: {
        details: async (collectedInvoiceId) => {
          return authenticatedRequest('/collected-invoices/economic/v2/details', 'GET', {
            collected_invoice_id: parseInt(collectedInvoiceId),
          }).then((response) => {
            console.warn(response);
            return response;
          }).catch((error) => {
            console.warn(error);
            throw error;
          });
        },
        compare: async (collectedInvoiceId) => {
          return authenticatedRequest('/collected-invoices/economic/v2/compare', 'GET', {
            collected_invoice_id: parseInt(collectedInvoiceId),
          }).then((response) => {
            console.warn(response);
            return response;
          }).catch((error) => {
            console.warn(error);
            throw error;
          });
        },
        compareBulk: async (collectedInvoiceIds = []) => {
          const MAX_BULK_COMPARE_IDS = 200;
          const sanitizedIds = (Array.isArray(collectedInvoiceIds) ? collectedInvoiceIds : [])
            .map((id) => parseInt(id))
            .filter((id) => Number.isInteger(id) && id > 0);

          if (!sanitizedIds.length) {
            return {
              data: {
                data: {
                  requested: 0,
                  compared: 0,
                  failed: 0,
                  results: [],
                  errors: [],
                },
              },
            };
          }

          if (sanitizedIds.length <= MAX_BULK_COMPARE_IDS) {
            return authenticatedRequest('/collected-invoices/economic/v2/compare/bulk', 'POST', {
              collected_invoice_ids: sanitizedIds,
            }).then((response) => {
              console.warn(response);
              return response;
            }).catch((error) => {
              console.warn(error);
              throw error;
            });
          }

          const aggregated = {
            requested: sanitizedIds.length,
            compared: 0,
            failed: 0,
            results: [],
            errors: [],
          };

          for (let index = 0; index < sanitizedIds.length; index += MAX_BULK_COMPARE_IDS) {
            const chunkIds = sanitizedIds.slice(index, index + MAX_BULK_COMPARE_IDS);
            const response = await authenticatedRequest('/collected-invoices/economic/v2/compare/bulk', 'POST', {
              collected_invoice_ids: chunkIds,
            });
            const payload = response?.data?.data || response?.data || {};
            const results = Array.isArray(payload?.results) ? payload.results : [];
            const errors = Array.isArray(payload?.errors) ? payload.errors : [];
            const comparedCount = Number(payload?.compared);
            const failedCount = Number(payload?.failed);

            aggregated.compared += Number.isFinite(comparedCount) ? comparedCount : results.length;
            aggregated.failed += Number.isFinite(failedCount) ? failedCount : errors.length;
            aggregated.results.push(...results);
            aggregated.errors.push(...errors);
          }

          return {
            data: {
              data: aggregated,
            },
          };
        },
        revenueStatistics: async (params = {}) => {
          return authenticatedRequest('/collected-invoices/economic/v2/revenue-statistics', 'GET', params)
            .then((response) => {
              console.warn(response);
              return response;
            }).catch((error) => {
              console.warn(error);
              throw error;
            });
        },
      },
      // The additionalBody can contain:
      // - send_as_is: boolean (default: false) - If true, the invoice will be sent to E-conomic as is, without any modifications made by fixed pricing or vehicle subscriptions.
      invoice: async (invoiceId, additionalBody = {
        send_as_is: false, // If true, the invoice will be sent to E-conomic as is, without any modifications made by fixed pricing or vehicle subscriptions.
      }) => {
        const payload = buildCollectedInvoiceEconomicPayload({
          id: invoiceId,
          send_as_is: additionalBody?.send_as_is ?? false,
        });

        return enqueueEconomicTransferJob({
          endpoint: '/collected-invoices/economic',
          payload,
          requestFn: authenticatedRequest,
        }).catch((error) => {
          console.log(error);
          throw error;
        });
      },
      unlink: async (id) => {
        // Send the request
        return authenticatedRequest('/collected-invoices/economic/unlink', 'POST', {
          id: parseInt(id)
        }).then((response) => {
          console.log(response);
          return response;
        }).catch((error) => {
          console.log(error);
          throw error;
        });
      },
    },
    remove_special_arrangements: async (id) => {
      // Send the request
      return authenticatedRequest('/collected-invoices/remove-special-arrangements', 'POST', {
        id: parseInt(id)
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    reset_prices_to_department_and_customer_defaults: async (id) => {
      // Send the request
      return authenticatedRequest('/collected-invoices/reset-prices-of-items-not-included-in-invoice', 'POST', {
        id: parseInt(id)
      }).then((response) => {
        console.log(response);
        return response;
      }).catch((error) => {
        console.log(error);
        throw error;
      });
    },
    createVehicleSubscriptionInvoice: async (customer_number, month, year) => {
      // Send the request
      return authenticatedRequest(
          "/collected-invoices/vehicle-subscriptions/custom",
          "POST",
          {
            customer_number: customer_number,
            month: month,
            year: year,
          }
      ).then((response) => {
        console.log(response);
        // Redirect to the invoice creation page
        SessionUser.functions.redirectTo.superUser('/invoices/' + response.data.data.id, true);
        return response;
      }).catch((error) => {
        console.error(error);
        throw error;
      });
    }
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(CollectedOrderInvoices, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    if (column === 'closed_at') {
      return showEditClosedAtObjectFieldForm(id, value, onAfterSubmit);
    }

    return ObjectsGlobal.showEditObjectFieldForm(
        CollectedOrderInvoices,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$w = {};
const CollectedOrderInvoices_default = /*#__PURE__*/_export_sfc(_sfc_main$w, [['__file',"CollectedOrderInvoices.vue"]]);

const t$c = (key) => i18n.global.t(key);

    /**
     * The DepartmentDailyReports object
     */
    const DepartmentDailyReports = {
      get meta() {
        return {
          title: t$c('objects.department_daily_reports.title'),
          icon: "fas fa-list",
          description: t$c('objects.department_daily_reports.description'),
          endpoint: "/departments/daily-reports",
          labels: {
            single: t$c('objects.department_daily_reports.single'),
            multiple: t$c('objects.department_daily_reports.multiple')
          }
        };
      },
      get columns() {
        return {
          id: {
            label: t$c('objects.columns.id'),
            type: "number",
            sortable: true,
            creation: {
              required: false
            }
          },
          department_id: {
            label: t$c('objects.columns.department_id'),
            type: "select",
            sortable: true,
            creation: {
              required: true
            },
            options: async () => {
              console.log("Getting departments");
              return SessionUser.objects.departments.get.all();
            }
          },
          water_usage: {
            label: t$c('objects.columns.water_usage'),
            type: "number",
            sortable: true,
            creation: {
              required: true
            },
          },
          filled_by: {
            label: t$c('objects.columns.filled_by'),
            type: "number",
            sortable: true,
            creation: {
              required: false
            },
          },
          created_at: {
            label: t$c('common.created'),
            type: "date",
            sortable: true,
            creation: {
              required: false
            }
          },
        };
      },
      add: async (department_id, water_usage_morning = 0, water_usage = 0, notes = null, date = null) => {
        return ObjectsGlobal.add.object(
            DepartmentDailyReports.meta.endpoint,
            {
              department_id: parseInt(department_id),
              water_usage_morning: parseInt(water_usage_morning),
              water_usage: parseInt(water_usage),
              notes: notes ? notes : 'Daily report',
              date: date ? date : todayLocalDateOnly()
            }
        );
      },
      set: {
        water_usage: async (id, water_usage) => {
          return ObjectsGlobal.set.column(
              DepartmentDailyReports.meta.endpoint,
              id,
              "water_usage",
              parseInt(water_usage)
          )
        },
        water_usage_morning: async (id, water_usage_morning) => {
          return ObjectsGlobal.set.column(
              DepartmentDailyReports.meta.endpoint,
              id,
              "water_usage_morning",
              parseInt(water_usage_morning)
          )
        },
      },
      get: {
        all: async () => {
          return ObjectsGlobal.get.objects(DepartmentDailyReports.meta.endpoint);
        },
        single: async (id) => {
          return ObjectsGlobal.get.object(DepartmentDailyReports.meta.endpoint, parseInt(id));
        }
      },
      delete: async (id) => {
        return ObjectsGlobal.delete.object(DepartmentDailyReports.meta.endpoint, parseInt(id));
      },
      functions: {
        showCreateObjectFormDepartment: async (department_id, onAfterSubmit = null) => {
          console.log("Department ID", department_id, "type", typeof department_id);
          return ObjectsGlobal.showCreateObjectForm(DepartmentDailyReports, onAfterSubmit, {department_id: department_id});
        },
        showDeleteObjectForm: (id, onAfterSubmit = null) => {
          return ObjectsGlobal.showDeleteObjectForm(DepartmentDailyReports, id, onAfterSubmit);
        },
        getProductCount: async (department_id, product_id, date, date_to = null) => {
          return authenticatedRequest(
              "/departments/daily-reports/product-count?product_id=" + product_id + "&date=" + date + "&department_id=" + department_id + (date_to ? "&date_to=" + date_to : ""),
              "GET"
          );
        },
        getTransactionCount: async (department_id, date, date_to) => {
          return authenticatedRequest(
              "/departments/daily-reports/transaction-count?date=" + date + "&department_id=" + department_id + (date_to ? "&date_to=" + date_to : ""),
              "GET"
          );
        },
        getOutsideHoursTrend: async (department_ids, date, date_to) => {
          const normalizedDepartmentIds = Array.isArray(department_ids)
            ? department_ids.map((department_id) => parseInt(department_id, 10)).filter((department_id) => department_id > 0)
            : [parseInt(department_ids, 10)].filter((department_id) => department_id > 0);

          return authenticatedRequest(
            "/departments/daily-reports/outside-hours-trend",
            "GET",
            {
              department_ids: normalizedDepartmentIds.join(","),
              date,
              date_to,
            }
          );
        },
        getOverview: async (department_ids, date, date_to = null) => {
          const normalizedDepartmentIds = Array.isArray(department_ids)
            ? department_ids.map((department_id) => parseInt(department_id, 10)).filter((department_id) => department_id > 0)
            : [parseInt(department_ids, 10)].filter((department_id) => department_id > 0);

          return authenticatedRequest(
            "/departments/daily-reports/overview",
            "GET",
            {
              department_ids: normalizedDepartmentIds.join(","),
              date,
              ...(date_to ? { date_to } : {}),
            }
          );
        },
        setProductTarget: async ({ department_id, product_id, target_percentage }) => {
          const normalizedTarget = target_percentage === null || target_percentage === undefined || target_percentage === ""
            ? null
            : Number(target_percentage);

          return authenticatedRequest(
            "/departments/daily-reports/product-targets",
            "PUT",
            {
              department_id: parseInt(department_id, 10),
              product_id: parseInt(product_id, 10),
              target_percentage: normalizedTarget,
            }
          );
        },
        createComplaint: async ({
          department_id,
          customer_number = null,
          wash_date,
          category,
          description,
        }) => {
          const payload = {
            department_id: parseInt(department_id, 10),
            wash_date: String(wash_date || "").trim(),
            category: String(category || "").trim(),
            description,
          };

          if (customer_number !== null && customer_number !== undefined && customer_number !== "") {
            payload.customer_number = parseInt(customer_number, 10);
          }

          return authenticatedRequest(
            "/departments/daily-reports/complaints",
            "POST",
            payload
          );
        },
        getLatest: async (department_id) => {
          return authenticatedRequest(
              "/departments/daily-reports/latest?id=" + department_id,
              "GET"
          );
        },
        getDepartmentDailyReport: async (department_id, date) => {
          return authenticatedRequest(
              "/departments/daily-reports/get?id=" + department_id + "&date=" + date,
              "GET"
          );
        },
        getDepartmentDailyBookingReport: async (department_id, date) => {
          return SessionUser.request(
              "/departments/daily-reports/bookings-count",
              "GET",
              {
                department_id: department_id,
                date: date
              }
          );
        },
      },
      /**
       * Show the create object form
       * @param onAfterSubmit
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showCreateObjectForm: (onAfterSubmit = null) => {
        return ObjectsGlobal.showCreateObjectForm(DepartmentDailyReports, onAfterSubmit);
      },
      /**
       * Show the edit object field form
       * @param id
       * @param column
       * @param value
       * @param onAfterSubmit
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
        return ObjectsGlobal.showEditObjectFieldForm(
            DepartmentDailyReports,
            id,
            column,
            value,
            onAfterSubmit
        );
      }
    };

const _sfc_main$v = {};
const DepartmentDailyReports_default = /*#__PURE__*/_export_sfc(_sfc_main$v, [['__file',"DepartmentDailyReports.vue"]]);

const COMPLAINT_CUSTOMER_SEARCH_DEBOUNCE_MS = 250;
const COMPLAINT_CUSTOMER_SEARCH_MIN_LENGTH = 2;

const COMPLAINT_CUSTOMER_SEARCH_LIMIT = 10;
const COMPLAINT_CUSTOMER_SEARCH_MAX_LIMIT = 20;
const ENDPOINT$1 = "/departments/daily-reports/complaints/customers";

const clampSearchLimit = (value) => {
  const parsed = Number.parseInt(String(value ?? COMPLAINT_CUSTOMER_SEARCH_LIMIT), 10);
  if (!Number.isFinite(parsed)) {
    return COMPLAINT_CUSTOMER_SEARCH_LIMIT;
  }

  return Math.min(COMPLAINT_CUSTOMER_SEARCH_MAX_LIMIT, Math.max(1, parsed));
};

const normalizeComplaintCustomer = (customer) => {
  if (!customer || typeof customer !== "object") {
    return null;
  }

  const customerNumber = Number.parseInt(
    String(customer.customer_number ?? customer.customerNumber ?? ""),
    10
  );
  if (!Number.isFinite(customerNumber) || customerNumber <= 0) {
    return null;
  }

  const customerName = typeof customer.customer_name === "string"
    ? customer.customer_name.trim()
    : typeof customer.customerName === "string"
      ? customer.customerName.trim()
      : null;

  return {
    customer_number: customerNumber,
    customer_name: customerName === "" ? null : customerName,
  };
};

const formatComplaintCustomerLabel = (customer) => {
  const normalizedCustomer = normalizeComplaintCustomer(customer);
  if (!normalizedCustomer) {
    return "";
  }

  if (normalizedCustomer.customer_name) {
    return `${normalizedCustomer.customer_name} - ${normalizedCustomer.customer_number}`;
  }

  return String(normalizedCustomer.customer_number);
};

const searchComplaintCustomers = async (
  search,
  limit = COMPLAINT_CUSTOMER_SEARCH_LIMIT
) => {
  const trimmedSearch = String(search ?? "").trim();
  if (trimmedSearch.length < COMPLAINT_CUSTOMER_SEARCH_MIN_LENGTH) {
    return [];
  }

  const response = await authenticatedRequest(ENDPOINT$1, "GET", {
    search: trimmedSearch,
    limit: clampSearchLimit(limit),
  });

  const rows = Array.isArray(response?.data?.data) ? response.data.data : [];
  return rows
    .map((row) => normalizeComplaintCustomer(row))
    .filter((row) => row !== null);
};

const DEPARTMENT_DAILY_REPORT_COMPLAINT_CATEGORY_OPTIONS = Object.freeze([
  { value: "wash_quality", label: "Vaskekvalitet" },
  { value: "wash_price", label: "Vaskepris" },
  { value: "damage_paint", label: "Skade lak" },
  { value: "damage_mirrors", label: "Skade spejle" },
  { value: "damage_cables_electronics", label: "Skade kabler & elektronik" },
  { value: "damage_plastic_parts", label: "Skade plastikdele" },
  { value: "damage_other", label: "Skade andet" },
  { value: "service", label: "Service" },
  { value: "other", label: "Andet" },
]);

const DEPARTMENT_DAILY_REPORT_COMPLAINT_CATEGORY_LABELS = Object.freeze(
  DEPARTMENT_DAILY_REPORT_COMPLAINT_CATEGORY_OPTIONS.reduce((labels, option) => ({
    ...labels,
    [option.value]: option.label,
  }), {})
);

const getDepartmentDailyReportComplaintCategoryLabel = (value) => (
  DEPARTMENT_DAILY_REPORT_COMPLAINT_CATEGORY_LABELS[String(value || "").trim()] || null
);

const isDepartmentDailyReportComplaintCategory = (value) => (
  getDepartmentDailyReportComplaintCategoryLabel(value) !== null
);

const t$b = (key) => i18n.global.t(key);
const ENDPOINT = "/departments/daily-reports/complaints";
const EDIT_COMPLAINT_CUSTOMER_SEARCH_INPUT_ID = "superuser-complaint-customer-search";
const EDIT_COMPLAINT_CUSTOMER_SEARCH_CONTROL_ID = "superuser-complaint-customer-search-control";
const EDIT_COMPLAINT_CUSTOMER_RESULTS_WRAPPER_ID = "superuser-complaint-customer-results-wrapper";
const EDIT_COMPLAINT_CUSTOMER_RESULTS_ID = "superuser-complaint-customer-results";
const EDIT_COMPLAINT_CUSTOMER_HELP_ID = "superuser-complaint-customer-help";
const EDIT_COMPLAINT_CUSTOMER_CLEAR_ID = "superuser-complaint-customer-clear";
const EDIT_COMPLAINT_WASH_DATE_INPUT_ID = "superuser-complaint-wash-date";
const EDIT_COMPLAINT_WASH_DATE_PICKER_ID = "superuser-complaint-wash-date-picker";
const EDIT_COMPLAINT_CUSTOMER_SEARCH_WRAPPER_STYLE = "position: relative;";
const EDIT_COMPLAINT_CUSTOMER_RESULTS_WRAPPER_STYLE = "position: absolute; top: calc(100% + 4px); left: 0; right: 0; width: 100%; z-index: 30;";
const EDIT_COMPLAINT_CUSTOMER_RESULTS_MENU_STYLE = "display: block; position: static; width: 100%; padding-top: 0;";
const EDIT_COMPLAINT_CUSTOMER_RESULTS_CONTENT_STYLE = "max-height: 14rem; overflow-y: auto;";
const EDIT_COMPLAINT_CUSTOMER_OPTION_STYLE = "width: 100%; justify-content: flex-start; border: 0; border-radius: 0;";

const escapeHtml$4 = (value) =>
  String(value ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");

const buildDepartmentOptions = (departments, selectedDepartmentId) => {
  return departments
    .map((department) => {
      const selected = Number(department.id) === Number(selectedDepartmentId) ? " selected" : "";
      return `<option value="${escapeHtml$4(department.id)}"${selected}>${escapeHtml$4(department.name)}</option>`;
    })
    .join("");
};

const buildComplaintCategoryOptions = (selectedCategory) => {
  const normalizedSelectedCategory = String(selectedCategory ?? "").trim();
  const options = [
    `<option value="">${escapeHtml$4("Vælg kategori")}</option>`,
    ...DEPARTMENT_DAILY_REPORT_COMPLAINT_CATEGORY_OPTIONS.map((category) => {
      const selected = category.value === normalizedSelectedCategory ? " selected" : "";
      return `<option value="${escapeHtml$4(category.value)}"${selected}>${escapeHtml$4(category.label)}</option>`;
    }),
  ];

  return options.join("");
};

const initialComplaintCustomerSelection = (complaint) => normalizeComplaintCustomer({
  customer_number: complaint.customer_number ?? null,
  customer_name: complaint.customer_name ?? null,
});

const initialComplaintWashDate = (complaint) => String(complaint?.wash_date ?? "").trim();
const initialComplaintCategory = (complaint) => String(complaint?.category ?? "").trim();

const mountSweetAlertDateField = ({ mountId, inputId, initialValue, dataTestid }) => {
  const mountElement = document.getElementById(mountId);
  const inputElement = document.getElementById(inputId);

  if (!mountElement || !inputElement) {
    return () => {};
  }

  const app = createApp({
    setup() {
      const value = ref(initialValue || "");

      watch(value, (nextValue) => {
        inputElement.value = nextValue || "";
      }, { immediate: true });

      return () => h(BuefyDateField, {
        modelValue: value.value,
        valueType: "string",
        dataTestid,
        "onUpdate:modelValue": (nextValue) => {
          value.value = nextValue || "";
        },
      });
    },
  });

  app.use(i18n);
  app.mount(mountElement);

  return () => {
    app.unmount();
  };
};

const buildEditComplaintForm = (complaint, departments) => {
  const selectedCustomer = initialComplaintCustomerSelection(complaint);
  const selectedCustomerLabel = formatComplaintCustomerLabel(selectedCustomer);
  const clearButtonStyle = selectedCustomer ? "" : "visibility: hidden; pointer-events: none;";
  const washDate = initialComplaintWashDate(complaint);
  const category = initialComplaintCategory(complaint);

  return `
    <div class="field">
      <label class="label has-text-black" for="superuser-complaint-department">Afdeling</label>
      <div class="control">
        <div class="select is-fullwidth">
          <select
            id="superuser-complaint-department"
            data-testid="superuser-complaint-edit-department"
            class="has-background-light has-text-black"
          >
            ${buildDepartmentOptions(departments, complaint.department_id)}
          </select>
        </div>
      </div>
    </div>
    <div class="field">
      <label class="label has-text-black" for="${EDIT_COMPLAINT_CUSTOMER_SEARCH_INPUT_ID}">Kunde (valgfri)</label>
      <div style="${EDIT_COMPLAINT_CUSTOMER_SEARCH_WRAPPER_STYLE}">
      <div
        class="control"
        id="${EDIT_COMPLAINT_CUSTOMER_SEARCH_CONTROL_ID}"
      >
        <input
          id="${EDIT_COMPLAINT_CUSTOMER_SEARCH_INPUT_ID}"
          data-testid="superuser-complaint-edit-customer-search"
          class="input has-background-light has-text-black"
          type="text"
          autocomplete="off"
          placeholder="Søg kunde eller kundenummer"
          value="${escapeHtml$4(selectedCustomerLabel)}"
        >
      </div>
      <div
        id="${EDIT_COMPLAINT_CUSTOMER_RESULTS_WRAPPER_ID}"
        class="dropdown is-fullwidth complaint-customer-dropdown is-hidden"
        style="${EDIT_COMPLAINT_CUSTOMER_RESULTS_WRAPPER_STYLE}"
      >
        <div class="dropdown-menu" style="${EDIT_COMPLAINT_CUSTOMER_RESULTS_MENU_STYLE}">
          <div
            id="${EDIT_COMPLAINT_CUSTOMER_RESULTS_ID}"
            data-testid="superuser-complaint-edit-customer-results"
            class="dropdown-content"
            style="${EDIT_COMPLAINT_CUSTOMER_RESULTS_CONTENT_STYLE}"
          ></div>
        </div>
      </div>
      </div>
      <button
        id="${EDIT_COMPLAINT_CUSTOMER_CLEAR_ID}"
        data-testid="superuser-complaint-edit-customer-clear"
        type="button"
        class="button is-small mt-2"
        style="${clearButtonStyle}"
      >
        Ryd
      </button>
      <p
        id="${EDIT_COMPLAINT_CUSTOMER_HELP_ID}"
        class="help is-danger is-hidden"
      ></p>
    </div>
    <div class="field">
      <label class="label has-text-black" for="${EDIT_COMPLAINT_WASH_DATE_INPUT_ID}">Dato for vask</label>
      <div class="control">
        <input
          id="${EDIT_COMPLAINT_WASH_DATE_INPUT_ID}"
          type="hidden"
          value="${escapeHtml$4(washDate)}"
        >
        <div id="${EDIT_COMPLAINT_WASH_DATE_PICKER_ID}" data-testid="superuser-complaint-edit-wash-date"></div>
      </div>
    </div>
    <div class="field">
      <label class="label has-text-black" for="superuser-complaint-category">Kategori</label>
      <div class="control">
        <div class="select is-fullwidth">
          <select
            id="superuser-complaint-category"
            data-testid="superuser-complaint-edit-category"
            class="has-background-light has-text-black"
          >
            ${buildComplaintCategoryOptions(category)}
          </select>
        </div>
      </div>
    </div>
    <div class="field">
      <label class="label has-text-black" for="superuser-complaint-description">Beskrivelse</label>
      <div class="control">
        <textarea
          id="superuser-complaint-description"
          data-testid="superuser-complaint-edit-description"
          class="textarea has-background-light has-text-black"
          rows="6"
        >${escapeHtml$4(complaint.description ?? "")}</textarea>
      </div>
    </div>
  `;
};

const createComplaintCustomerLookupState = (complaint) => ({
  selectedCustomer: initialComplaintCustomerSelection(complaint),
  results: [],
  query: "",
  hasSearched: false,
  lookupError: "",
  searchTimer: null,
  closeTimer: null,
  requestId: 0,
});

const setComplaintCustomerHelpMessage = (helpElement, message = "") => {
  if (!helpElement) {
    return;
  }

  helpElement.textContent = message;
  helpElement.classList.toggle("is-hidden", message === "");
};

const hideComplaintCustomerResults = (wrapperElement, resultsElement) => {
  if (resultsElement) {
    resultsElement.innerHTML = "";
  }

  if (!wrapperElement) {
    return;
  }

  wrapperElement.classList.add("is-hidden");
  wrapperElement.classList.remove("is-active");
};

const showComplaintCustomerResults = (wrapperElement) => {
  if (!wrapperElement) {
    return;
  }

  wrapperElement.classList.remove("is-hidden");
  wrapperElement.classList.add("is-active");
};

const resolveComplaintCustomerLookupErrorMessage = (error) => (
  SessionUser.functions.parseErrorMessage(error)
  || error?.response?.data?.data?.message
  || error?.response?.data?.message
  || error?.message
  || "Kundeopslag mislykkedes."
);

const resolveComplaintCustomerNumberFromLookup = (lookupState) => {
  const searchInput = document.getElementById(EDIT_COMPLAINT_CUSTOMER_SEARCH_INPUT_ID);
  const typedValue = String(searchInput?.value || "").trim();
  if (typedValue === "") {
    return null;
  }

  if (lookupState.selectedCustomer) {
    return lookupState.selectedCustomer.customer_number;
  }

  throw new Error("Vælg en kunde fra listen eller ryd feltet.");
};

const setupComplaintCustomerLookupField = (lookupState) => {
  const searchInput = document.getElementById(EDIT_COMPLAINT_CUSTOMER_SEARCH_INPUT_ID);
  const searchControl = document.getElementById(EDIT_COMPLAINT_CUSTOMER_SEARCH_CONTROL_ID);
  const resultsWrapper = document.getElementById(EDIT_COMPLAINT_CUSTOMER_RESULTS_WRAPPER_ID);
  const resultsElement = document.getElementById(EDIT_COMPLAINT_CUSTOMER_RESULTS_ID);
  const helpElement = document.getElementById(EDIT_COMPLAINT_CUSTOMER_HELP_ID);
  const clearButton = document.getElementById(EDIT_COMPLAINT_CUSTOMER_CLEAR_ID);

  if (!searchInput || !searchControl || !resultsWrapper || !resultsElement || !helpElement || !clearButton) {
    return () => {};
  }

  const clearSearchTimer = () => {
    if (lookupState.searchTimer !== null) {
      clearTimeout(lookupState.searchTimer);
      lookupState.searchTimer = null;
    }
  };

  const clearCloseTimer = () => {
    if (lookupState.closeTimer !== null) {
      clearTimeout(lookupState.closeTimer);
      lookupState.closeTimer = null;
    }
  };

  const setSearching = (isSearching) => {
    searchControl.classList.toggle("is-loading", Boolean(isSearching));
  };

  const syncSelectedCustomer = () => {
    clearButton.style.visibility = lookupState.selectedCustomer ? "visible" : "hidden";
    clearButton.style.pointerEvents = lookupState.selectedCustomer ? "auto" : "none";
    if (lookupState.selectedCustomer) {
      searchInput.value = formatComplaintCustomerLabel(lookupState.selectedCustomer);
    }
  };

  const selectCustomer = (customer) => {
    const normalizedCustomer = normalizeComplaintCustomer(customer);
    if (!normalizedCustomer) {
      return;
    }

    lookupState.selectedCustomer = normalizedCustomer;
    lookupState.results = [];
    lookupState.query = "";
    lookupState.hasSearched = false;
    lookupState.lookupError = "";
    setComplaintCustomerHelpMessage(helpElement, "");
    syncSelectedCustomer();
    hideComplaintCustomerResults(resultsWrapper, resultsElement);
  };

  const renderResults = () => {
    resultsElement.innerHTML = "";

    if (lookupState.results.length === 0) {
      if (
        !lookupState.hasSearched
        || lookupState.lookupError !== ""
        || lookupState.query.trim().length < COMPLAINT_CUSTOMER_SEARCH_MIN_LENGTH
      ) {
        hideComplaintCustomerResults(resultsWrapper, resultsElement);
        return;
      }

      const emptyState = document.createElement("div");
      emptyState.className = "dropdown-item has-text-grey";
      emptyState.setAttribute("data-testid", "superuser-complaint-edit-customer-no-results");
      emptyState.textContent = "Ingen kunder fundet.";
      resultsElement.appendChild(emptyState);
      showComplaintCustomerResults(resultsWrapper);
      return;
    }

    lookupState.results.forEach((customer) => {
      const option = document.createElement("button");
      option.type = "button";
      option.className = "dropdown-item button is-white complaint-customer-option";
      option.setAttribute("data-testid", `superuser-complaint-edit-customer-option-${customer.customer_number}`);
      option.setAttribute("style", EDIT_COMPLAINT_CUSTOMER_OPTION_STYLE);
      option.textContent = formatComplaintCustomerLabel(customer);
      option.addEventListener("mousedown", (event) => {
        event.preventDefault();
        clearCloseTimer();
        selectCustomer(customer);
      });
      resultsElement.appendChild(option);
    });

    showComplaintCustomerResults(resultsWrapper);
  };

  const runSearch = async (query, requestId) => {
    lookupState.hasSearched = true;
    lookupState.lookupError = "";
    setComplaintCustomerHelpMessage(helpElement, "");
    setSearching(true);

    try {
      const results = await searchComplaintCustomers(query);
      if (requestId !== lookupState.requestId) {
        return;
      }

      lookupState.results = results;
      renderResults();
    } catch (error) {
      if (requestId !== lookupState.requestId) {
        return;
      }

      lookupState.results = [];
      lookupState.lookupError = resolveComplaintCustomerLookupErrorMessage(error);
      setComplaintCustomerHelpMessage(helpElement, lookupState.lookupError);
      hideComplaintCustomerResults(resultsWrapper, resultsElement);
    } finally {
      if (requestId === lookupState.requestId) {
        setSearching(false);
      }
    }
  };

  const onSearchInput = () => {
    clearCloseTimer();
    clearSearchTimer();
    lookupState.requestId += 1;
    lookupState.query = String(searchInput.value || "");
    lookupState.hasSearched = false;
    lookupState.lookupError = "";
    lookupState.results = [];
    setComplaintCustomerHelpMessage(helpElement, "");

    if (
      lookupState.selectedCustomer
      && searchInput.value.trim() === formatComplaintCustomerLabel(lookupState.selectedCustomer)
    ) {
      return;
    }

    lookupState.selectedCustomer = null;
    syncSelectedCustomer();

    const trimmedQuery = lookupState.query.trim();
    if (trimmedQuery === "" || trimmedQuery.length < COMPLAINT_CUSTOMER_SEARCH_MIN_LENGTH) {
      setSearching(false);
      hideComplaintCustomerResults(resultsWrapper, resultsElement);
      return;
    }

    const requestId = lookupState.requestId;
    lookupState.searchTimer = setTimeout(() => {
      runSearch(trimmedQuery, requestId);
    }, COMPLAINT_CUSTOMER_SEARCH_DEBOUNCE_MS);
  };

  const onSearchFocus = () => {
    clearCloseTimer();
    if (lookupState.selectedCustomer) {
      return;
    }

    if (
      lookupState.results.length > 0
      || (
        lookupState.hasSearched
        && lookupState.lookupError === ""
        && lookupState.query.trim().length >= COMPLAINT_CUSTOMER_SEARCH_MIN_LENGTH
      )
    ) {
      renderResults();
    }
  };

  const onSearchBlur = () => {
    clearCloseTimer();
    lookupState.closeTimer = setTimeout(() => {
      hideComplaintCustomerResults(resultsWrapper, resultsElement);
    }, 150);
  };

  const onClearCustomer = (event) => {
    event.preventDefault();
    clearSearchTimer();
    clearCloseTimer();
    lookupState.requestId += 1;
    lookupState.selectedCustomer = null;
    lookupState.results = [];
    lookupState.query = "";
    lookupState.hasSearched = false;
    lookupState.lookupError = "";
    searchInput.value = "";
    setSearching(false);
    setComplaintCustomerHelpMessage(helpElement, "");
    syncSelectedCustomer();
    hideComplaintCustomerResults(resultsWrapper, resultsElement);
    searchInput.focus();
  };

  searchInput.addEventListener("input", onSearchInput);
  searchInput.addEventListener("focus", onSearchFocus);
  searchInput.addEventListener("blur", onSearchBlur);
  clearButton.addEventListener("click", onClearCustomer);

  syncSelectedCustomer();
  setComplaintCustomerHelpMessage(helpElement, "");

  return () => {
    clearSearchTimer();
    clearCloseTimer();
    setSearching(false);
    searchInput.removeEventListener("input", onSearchInput);
    searchInput.removeEventListener("focus", onSearchFocus);
    searchInput.removeEventListener("blur", onSearchBlur);
    clearButton.removeEventListener("click", onClearCustomer);
  };
};

const DepartmentDailyReportComplaints = {
  get meta() {
    return {
      title: t$b("superuser.pages.complaints.title"),
      icon: "fas fa-comment-alt",
      description: t$b("superuser.pages.complaints.subtitle"),
      endpoint: ENDPOINT,
      labels: {
        single: t$b("superuser.pages.complaints.single"),
        multiple: t$b("superuser.pages.complaints.title"),
      },
    };
  },
  get: {
    all: async (params = {}) => {
      return authenticatedRequest(ENDPOINT, "GET", params).then((response) => response.data.data);
    },
    single: async (id) => {
      return authenticatedRequest(ENDPOINT, "GET", { id }).then((response) => response.data.data);
    },
  },
  update: async (id, payload) => {
    return authenticatedRequest(ENDPOINT, "PUT", {
      id,
      ...payload,
    });
  },
  delete: {
    single: async (id) => {
      return authenticatedRequest(`${ENDPOINT}?id=${id}`, "DELETE");
    },
  },
  functions: {
    showEditForm: async (complaint, onAfterSubmit = null) => {
      const departments = await SessionUser.objects.departments.get.all().then((result) =>
        Array.isArray(result) ? result : []
      );
      const customerLookupState = createComplaintCustomerLookupState(complaint);
      let cleanupCustomerLookup = null;
      let cleanupDateField = null;

      return Swal.fire({
        title: t$b("superuser.pages.complaints.edit_title"),
        html: buildEditComplaintForm(complaint, departments),
        showCancelButton: true,
        confirmButtonText: t$b("common.save"),
        cancelButtonText: t$b("common.cancel"),
        focusConfirm: false,
        didOpen: () => {
          cleanupCustomerLookup = setupComplaintCustomerLookupField(customerLookupState);
          cleanupDateField = mountSweetAlertDateField({
            mountId: EDIT_COMPLAINT_WASH_DATE_PICKER_ID,
            inputId: EDIT_COMPLAINT_WASH_DATE_INPUT_ID,
            initialValue: initialComplaintWashDate(complaint),
            dataTestid: "superuser-complaint-edit-wash-date-picker",
          });
        },
        willClose: () => {
          if (typeof cleanupCustomerLookup === "function") {
            cleanupCustomerLookup();
            cleanupCustomerLookup = null;
          }
          if (typeof cleanupDateField === "function") {
            cleanupDateField();
            cleanupDateField = null;
          }
        },
        preConfirm: async () => {
          try {
            const departmentId = Number.parseInt(
              document.getElementById("superuser-complaint-department")?.value || "",
              10
            );
            if (!Number.isFinite(departmentId) || departmentId <= 0) {
              throw new Error("Afdeling er påkrævet.");
            }

            const washDate = (
              document.getElementById(EDIT_COMPLAINT_WASH_DATE_INPUT_ID)?.value || ""
            ).trim();
            if (washDate === "") {
              throw new Error("Dato for vask er påkrævet.");
            }

            const category = (
              document.getElementById("superuser-complaint-category")?.value || ""
            ).trim();
            if (!isDepartmentDailyReportComplaintCategory(category)) {
              throw new Error("Kategori er påkrævet.");
            }

            const description = (
              document.getElementById("superuser-complaint-description")?.value || ""
            ).trim();
            if (description === "") {
              throw new Error("Beskrivelse er påkrævet.");
            }

            const customerNumber = resolveComplaintCustomerNumberFromLookup(customerLookupState);

            await DepartmentDailyReportComplaints.update(complaint.id, {
              department_id: departmentId,
              customer_number: customerNumber,
              wash_date: washDate,
              category,
              description,
            });

            if (typeof onAfterSubmit === "function") {
              await onAfterSubmit();
            }
          } catch (error) {
            Swal.showValidationMessage(
              SessionUser.functions.parseErrorMessage(error) || error?.message || String(error)
            );
            return false;
          }

          return true;
        },
      });
    },
    showDeleteConfirmationModal: async (id, onAfterSubmit = null) => {
      return Swal.fire({
        title: t$b("superuser.pages.complaints.delete_title"),
        text: t$b("superuser.pages.complaints.delete_message"),
        showCancelButton: true,
        confirmButtonText: t$b("global.confirm_delete"),
        cancelButtonText: t$b("common.cancel"),
        showLoaderOnConfirm: true,
        preConfirm: async () => {
          try {
            await DepartmentDailyReportComplaints.delete.single(id);

            if (typeof onAfterSubmit === "function") {
              await onAfterSubmit();
            }
          } catch (error) {
            Swal.showValidationMessage(
              SessionUser.functions.parseErrorMessage(error) || error?.message || String(error)
            );
            return false;
          }

          return true;
        },
      });
    },
  },
};

const _sfc_main$u = {};
const DepartmentDailyReportComplaints_default = /*#__PURE__*/_export_sfc(_sfc_main$u, [['__file',"DepartmentDailyReportComplaints.vue"]]);

/**
 * The Goals object
 */
const Goals = {
  meta: {
    title: "Mål",
    icon: "fas fa-bullseye",
    description: "Afdelingsmål",
    endpoint: "/goals/department",
    labels: {
      single: "mål",
      multiple: "mål"
    },
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    created_by: {
      label: "Oprettet af",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    departments: {
      label: "Afdelinger",
      type: "array",
      sortable: true,
      creation: {
        required: true
      }
    },
    criteria: {
      label: "Kriterier",
      type: "object",
      sortable: false,
      creation: {
        required: true
      }
    },
    created_at: {
      label: "Oprettet",
      type: "date",
      sortable: true,
      creation: {
        required: false
      }
    },
    updated_at: {
      label: "Opdateret",
      type: "date",
      sortable: true,
      creation: {
        required: false
      }
    },
  },
  add: async (departments, criteria) => {
    return ObjectsGlobal.add.object(
        Goals.meta.endpoint,
        {
          departments: departments,
          criteria: criteria
        }
    );
  },
  set: {
    departments: async (id, departments) => {
      return ObjectsGlobal.set.column(
          Goals.meta.endpoint,
          id,
          "departments",
          departments
      )
    },
    criteria: async (id, criteria) => {
      return ObjectsGlobal.set.column(
          Goals.meta.endpoint,
          id,
          "criteria",
          criteria
      )
    },
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(Goals.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(Goals.meta.endpoint, parseInt(id));
    }
  },
  update: async (id, departments, criteria) => {
    ObjectsGlobal.clearCache();
    return authenticatedRequest(Goals.meta.endpoint, "PUT", {
      id: parseInt(id),
      departments: departments,
      criteria: criteria
    }).then((response) => {
      ObjectsGlobal.clearCache();
      return response;
    });
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(Goals.meta.endpoint, parseInt(id));
  },
  testProgressAlert: async (params) => {
    return authenticatedRequest(Goals.meta.endpoint + "/progress-alert/test", "POST", params);
  },
  functions: {
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(Goals, id, onAfterSubmit);
    },
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @param lockedValues
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null, lockedValues = {}) => {
    return ObjectsGlobal.showCreateObjectForm(Goals, onAfterSubmit, lockedValues);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        Goals,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$t = {};
const Goals_default = /*#__PURE__*/_export_sfc(_sfc_main$t, [['__file',"Goals.vue"]]);

/**
     * The Notifications object
     */
    const Notifications = {
      meta: {
        title: "Notifikationer",
        icon: "fas fa-bell",
        description: "Notifikationer",
        endpoint: "/notifications",
        labels: {
          single: "notifikation",
          multiple: "notifikationer"
        },
      },
      columns: {
        id: {
          label: "ID",
          type: "number",
          sortable: true,
          creation: {
            required: false
          }
        },
        type: {
          label: "Type",
          type: "string",
          sortable: true,
          creation: {
            required: true
          },
        },
        user_id: {
          label: "Bruger ID",
          type: "number",
          sortable: true,
          creation: {
            required: true
          },
        },
        data: {
          label: "Data",
          type: "Array",
          sortable: true,
          creation: {
            required: false
          },
        },
        created_at: {
          label: "Oprettet",
          type: "date",
          sortable: true,
          creation: {
            required: false
          }
        },
      },
      add: async (type, user_id, data = null) => {
        return ObjectsGlobal.add.object(
            Notifications.meta.endpoint,
            {
              user_id: parseInt(user_id),
              type: type,
              data: data
            }
        );
      },
      set: {
        type: async (id, type) => {
          return ObjectsGlobal.set.column(
              Notifications.meta.endpoint,
              id,
              "type",
              type
          )
        },
        user_id: async (id, user_id) => {
          return ObjectsGlobal.set.column(
              Notifications.meta.endpoint,
              id,
              "user_id",
              parseInt(user_id)
          )
        },
        data: async (id, data) => {
          return ObjectsGlobal.set.column(
              Notifications.meta.endpoint,
              id,
              "data",
              data
          )
        },
      },
      get: {
        all: async () => {
          return ObjectsGlobal.get.objects(Notifications.meta.endpoint);
        },
        single: async (id) => {
          return ObjectsGlobal.get.object(Notifications.meta.endpoint, parseInt(id));
        }
      },
      delete: async (id) => {
        return ObjectsGlobal.delete.object(Notifications.meta.endpoint, parseInt(id));
      },
      functions: {
        showDeleteObjectForm: (id, onAfterSubmit = null) => {
          return ObjectsGlobal.showDeleteObjectForm(Notifications, id, onAfterSubmit);
        },
        getNotificationCount: async (user_id = null) => {
          return authenticatedRequest(
              Notifications.meta.endpoint + "/count" + (user_id ? "?user_id=" + user_id : ""),
              "GET"
          );
        },
        markAsRead: async (id) => {
          return authenticatedRequest(
              Notifications.meta.endpoint + "?id=" + id,
              "DELETE"
          );
        },
      },
      /**
       * Show the create object form
       * @param onAfterSubmit
       * @param lockedValues
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showCreateObjectForm: (onAfterSubmit = null, lockedValues = {}) => {
        return ObjectsGlobal.showCreateObjectForm(Notifications, onAfterSubmit, lockedValues);
      },
      /**
       * Show the edit object field form
       * @param id
       * @param column
       * @param value
       * @param onAfterSubmit
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
        return ObjectsGlobal.showEditObjectFieldForm(
            Notifications,
            id,
            column,
            value,
            onAfterSubmit
        );
      }
    };

const _sfc_main$s = {};
const Notifications_default = /*#__PURE__*/_export_sfc(_sfc_main$s, [['__file',"Notifications.vue"]]);

const t$a = (key) => i18n.global.t(key);

/**
 * The Bookings object
 */
const Bookings = {
  get meta() {
    return {
      title: t$a('objects.bookings.title'),
      icon: "fas fa-list",
      description: t$a('objects.bookings.description'),
      endpoint: "/bookings",
      labels: {
        single: t$a('objects.bookings.single'),
        multiple: t$a('objects.bookings.multiple'),
        fields: {
          names: {
            customer_number: {
              label: t$a('objects.bookings.columns.economic_customer_number'),
            },
          },
        },
      },
    };
  },
  get columns() {
    return {
    id: {
      label: t$a('objects.columns.id'),
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    customer_number: {
      label: t$a('objects.columns.customer_number'),
      type: "number",
      sortable: true,
      creation: {
        required: true
      },
    },
    wash_type: {
      label: t$a('objects.bookings.columns.wash_type'),
      type: "string",
      sortable: true,
      creation: {
        required: true
      },
    },
    contact_email: {
      label: t$a('objects.bookings.columns.contact_email'),
      type: "string",
      sortable: true,
      creation: {
        required: true
      },
    },
    reference_number: {
    label: t$a('common.reference'),
      type: "string",
      sortable: true,
      creation: {
        required: true
      },
    },
    regNrTraekker: {
      label: t$a('objects.bookings.columns.reg_1'),
      type: "string",
      sortable: true,
      creation: {
        required: true
      },
    },
    regNrTrailer: {
      label: t$a('objects.bookings.columns.reg_2'),
      type: "string",
      sortable: true,
      creation: {
        required: false
      },
    },
    washCertificateEmail: {
      label: t$a('objects.bookings.columns.wash_certificate_email'),
      type: "string",
      sortable: true,
      creation: {
        required: false
      },
    },
    date: {
      label: t$a('common.date'),
      type: "string",
      sortable: true,
      creation: {
        required: true
      },
    },
    department: {
      label: t$a('objects.columns.department'),
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return SessionUser.objects.department_notification_sms.columns.department.options()
      }
    },
    pickup_bool: {
      label: t$a('objects.bookings.columns.pickup'),
      type: "boolean",
      sortable: true,
      creation: {
        required: false
      },
    },
    notes: {
      label: t$a('objects.columns.notes'),
      type: "string",
      sortable: true,
      creation: {
        required: false
      },
    },
    washCertificateStatus: {
      label: t$a('objects.bookings.columns.wash_certificate_status'),
      type: "select",
      sortable: true,
      creation: {
        required: false
      },
      options: async () => {
        return [
          { id: 'pending', name: "Afventer" },
          { id: 'cancelled', name: "Annulleret" },
          { id: 'completed', name: "Færdig" },
        ];
      }
    },
    washCertificateUrl: {
      label: t$a('objects.bookings.columns.wash_certificate_url'),
      type: "string",
      sortable: true,
      creation: {
        required: false
      },
    },
    status: {
      label: t$a('common.status'),
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return [
          { id: 'pending', name: "Afventer" },
          { id: 'cancelled', name: "Annulleret" },
          { id: 'completed', name: "Færdig" },
        ];
      }
    },
    data: {
      label: t$a('objects.columns.data'),
      type: "string",
      sortable: false,
      creation: {
        required: false
      },
    },
    wash_certificate_pdf: {
      label: t$a('objects.bookings.columns.wash_certificate_pdf'),
      type: "string",
      sortable: false,
      creation: {
        required: false
      },
    },
    created_at: {
      label: t$a('common.created'),
      type: "string",
      sortable: true,
      creation: {
        required: false
      },
    },
    deleted_at: {
      label: t$a('objects.columns.deleted'),
      type: "string",
      sortable: true,
      creation: {
        required: false
      },
    },
  };
  },
  set: {
    reference_number: async (id, reference) => {
      return ObjectsGlobal.set.column(
          Bookings.meta.endpoint,
          id,
          "reference_number",
          reference
      )
    },
  },
  get: {
    single: async (identifier) => {
      return ObjectsGlobal.get.object(Bookings.meta.endpoint, identifier, {authenticated: SessionUser.functions.hasToken()});
    },
  },
  functions: {
    submit: async (form) => {
      console.warn(form);
      return ObjectsGlobal.add.object(Bookings.meta.endpoint, form, {authenticated: SessionUser.functions.hasToken()});
    },
    download: async (id) => {
      return SessionUser.request(
          '/bookings/download_pdf',
          'GET',
          {
            id: id
          }
          );
    },
    getDepartmentBookingsToday: async (department) => {
      /**
       * https://api.truckwash.dk/bookings?filters=department:2,status:pending,date-date_from:2025-09-01,date-date_to:2025-09-01&limit=1&page=1
       */
      return SessionUser.request(
          '/bookings',
          'GET',
          {
            filters: `department:${department},status:pending,date-date_from:${todayLocalDateOnly()},date-date_to:${todayLocalDateOnly()}`,
            limit: 100,
            page: 1
          }
      );
    },
    isBookingCompleted: async (id) => {
      let booking = await Bookings.get.single(id)
          .then(response => {
            console.warn("Booking:", response);
            return response;
          })
          .catch(error => {
            console.error("Error fetching booking:", error);
            return null;
          });
      if (booking) {
        console.warn("Booking status:", booking.status);
        return booking.status === 'completed';
      }
    }
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(Bookings, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        Bookings,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$r = {};
const Bookings_default = /*#__PURE__*/_export_sfc(_sfc_main$r, [['__file',"Bookings.vue"]]);

const t$9 = (key) => i18n.global.t(key);

const getProtectedDeletePayload = (error) => {
  const payload = error?.response?.data?.data;
  if (error?.response?.status !== 409 || payload?.requires_confirmation !== true) {
    return null;
  }
  return payload;
};

const escapeHtml$3 = (value) => String(value ?? "").replace(/[&<>"']/g, (character) => ({
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  "\"": "&quot;",
  "'": "&#39;",
})[character]);

const formatDeleteProtectionReason = (reason) => {
  switch (reason) {
    case "completed":
      return "ordren er fuldført";
    case "order_items":
      return "ordren har varelinjer";
    case "attachments":
      return "ordren har vedhæftninger";
    default:
      return escapeHtml$3(String(reason || "").replace(/_/g, " "));
  }
};

const showProtectedOrderDeleteConfirmation = async (id, protectionPayload, onAfterSubmit = null) => {
  const orderId = String(id);
  const escapedOrderId = escapeHtml$3(orderId);
  const reasons = Array.isArray(protectionPayload?.protected_reasons)
    ? protectionPayload.protected_reasons.map(formatDeleteProtectionReason).filter(Boolean)
    : [];
  const reasonText = reasons.length > 0 ? reasons.join(", ") : "ordren indeholder gemte data";

  const result = await Swal.fire({
    titleText: `Bekræft sletning af ordre #${orderId}`,
    html: `
      <p>Ordren kan stadig slettes, men kræver ekstra bekræftelse fordi ${reasonText}.</p>
      <p>Skriv <strong>${escapedOrderId}</strong> for at slette ordren.</p>
    `,
    input: "text",
    inputAttributes: {
      autocapitalize: "off",
      autocomplete: "off",
    },
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Slet ordre",
    cancelButtonText: "Fortryd",
    showLoaderOnConfirm: true,
    didOpen: () => {
      const confirmButton = Swal.getConfirmButton();
      const input = Swal.getInput();
      input?.setAttribute("data-testid", "protected-order-delete-input");
      const updateConfirmState = () => {
        if (confirmButton) {
          confirmButton.disabled = String(input?.value ?? "").trim() !== orderId;
        }
      };

      input?.addEventListener("input", updateConfirmState);
      updateConfirmState();
    },
    preConfirm: async (value) => {
      if (String(value ?? "").trim() !== orderId) {
        Swal.showValidationMessage("Ordre-id matcher ikke");
        return false;
      }

      try {
        return await Orders.delete.single(id, { confirmed: true });
      } catch (error) {
        Swal.showValidationMessage(SessionUser.functions.parseErrorMessage(error) || "Ordren kunne ikke slettes");
        return false;
      }
    },
    allowOutsideClick: () => !Swal.isLoading(),
  });

  if (!result.isConfirmed) {
    return null;
  }

  if (onAfterSubmit !== null) {
    onAfterSubmit(result.value);
  }

  return result.value;
};

const deleteOrderWithProtectedConfirmation = async (id, onAfterSubmit = null) => {
  try {
    const response = await Orders.delete.single(id);
    if (onAfterSubmit !== null) {
      onAfterSubmit(response);
    }
    return response;
  } catch (error) {
    const protectedDeletePayload = getProtectedDeletePayload(error);
    if (!protectedDeletePayload) {
      throw error;
    }
    return showProtectedOrderDeleteConfirmation(id, protectedDeletePayload, onAfterSubmit);
  }
};

const mountOrderCustomerAssignmentModal = ({
  order,
  title,
  subtitle,
  submitLabel,
  errorMessageText,
  newCollectionDescription,
  onAssigned = null,
}) => {
  const host = document.createElement("div");
  host.dataset.testid = "change-customer-assignment-host";
  document.body.appendChild(host);

  let isDisposed = false;
  let app = null;

  const dispose = () => {
    if (isDisposed) {
      return;
    }

    isDisposed = true;
    app?.unmount?.();
    host.remove();
  };

  app = createApp(AssignDraftOrderCustomerModal, {
    order,
    title,
    subtitle,
    submitLabel,
    errorMessageText,
    newCollectionDescription,
    onClose: () => dispose(),
    onAssigned: async (response) => {
      try {
        if (typeof onAssigned === "function") {
          await onAssigned(response);
        }
      } finally {
        dispose();
      }
    },
  });

  app.use(i18n);
  app.mount(host);

  return dispose;
};



const showChangeOrderCustomerForm = async (id, onAfterSubmit = null) => {
  const normalizedOrderId = normalizePositiveInteger$1(id);
  if (!normalizedOrderId) {
    return;
  }

  mountOrderCustomerAssignmentModal({
    order: {
      id: normalizedOrderId,
      department_id: null,
      invoice_collection_id: null,
    },
    title: t$9("admin.pos.settings_wheel.change_customer"),
    subtitle: `Vælg kunde og fakturasamling for at flytte ordre #${normalizedOrderId} til den valgte kunde.`,
    submitLabel: t$9("admin.pos.settings_wheel.change_customer"),
    errorMessageText: "Der opstod en fejl under ændring af kunde.",
    newCollectionDescription: "Oprettet fra kundeskift",
    onAssigned: async (response) => {
      if (typeof onAfterSubmit === 'function') {
        await onAfterSubmit(response);
        return;
      }

      window.location.reload();
    }
  });
};

const showChangeOrderInvoiceCollectionForm = async (id, onAfterSubmit = null) => {
  let customer_number = null;
  // Get the customer number from the order
  await SessionUser.objects.orders.functions.get_customer_id(id).then((response) => {
    customer_number = response;
    console.log("Customer number:", customer_number);
  }).catch((error) => {
    console.error(error);
  });
  if (!customer_number) {
    console.error("Ingen kunde fundet");
    return;
  }
  // Select the invoice collection
  await SessionUser.objects.collectedOrderInvoices.functions.showInvoiceCollectionPickerForm(
      customer_number,
      async (invoice_collection_id) => {
        if (!invoice_collection_id) {
          Swal.fire({
            icon: 'error',
            title: 'Ingen faktura samling valgt',
            timer: 2000,
          });
          return;
        }
        // Handle the invoice collection selection here
        console.log("Selected invoice collection:", invoice_collection_id);
        console.log("Changing invoice collection for order:", id, " customer:", customer_number);
        console.log("New invoice collection:", invoice_collection_id);
        try {
          const response = await SessionUser.objects.orders.set.invoice_collection_id(
              parseInt(id, 10),
              parseInt(invoice_collection_id, 10)
          );
          console.log("Invoice collection changed successfully:", response);
          Swal.fire({
            icon: 'success',
            title: 'Faktura samling ændret',
            timer: 2000,
          });
          if (typeof onAfterSubmit === 'function') {
            await onAfterSubmit(response);
          }
        } catch (error) {
          console.error("Error changing invoice collection:", error);
          Swal.fire({
            icon: 'error',
            title: 'Fejl ved ændring af faktura samling',
            timer: 2000,
          });
        }
      }
  );
};

const normalizePositiveInteger$1 = (value) => {
  const parsedValue = Number.parseInt(value, 10);
  return Number.isInteger(parsedValue) && parsedValue > 0 ? parsedValue : null;
};

const refreshDraftNavigationCount = () => {
  dispatchNavigationCountRefresh();
};


const getOrderItemsForRepricing = (orderId) => authenticatedRequest('/order/items', 'GET', {
  order_id: orderId,
});

const editOrderItemForRepricing = ({ id, price, notes, reference, quantity }) => authenticatedRequest('/order/items', 'PUT', {
  id,
  price,
  notes,
  reference,
  quantity,
});

const getFinalProductPriceForCustomer = async (productId, departmentId, customerId) => {
  const normalizedProductId = normalizePositiveInteger$1(productId);
  const normalizedDepartmentId = normalizePositiveInteger$1(departmentId);
  const normalizedCustomerId = normalizePositiveInteger$1(customerId);

  if (!normalizedProductId || !normalizedDepartmentId || !normalizedCustomerId) {
    throw new Error("Invalid repricing context");
  }

  const response = await authenticatedRequest("/products", "GET", {
    id: normalizedProductId,
    department_id: normalizedDepartmentId,
    customer_id: normalizedCustomerId,
    final_price: "true",
  });

  const resolvedPrice = Number.parseInt(response?.data?.data?.price, 10);
  if (!Number.isFinite(resolvedPrice)) {
    throw new Error(`Unable to resolve price for product ${normalizedProductId}`);
  }

  return resolvedPrice;
};

const recalculateOrderItemPricesForCustomer = async ({ order_id, department_id, customer_id }) => {
  const normalizedOrderId = normalizePositiveInteger$1(order_id);
  const normalizedDepartmentId = normalizePositiveInteger$1(department_id);
  const normalizedCustomerId = normalizePositiveInteger$1(customer_id);

  if (!normalizedOrderId || !normalizedDepartmentId || !normalizedCustomerId) {
    throw new Error("Invalid order repricing context");
  }

  const response = await getOrderItemsForRepricing(normalizedOrderId);
  const orderItems = Array.isArray(response?.data?.data) ? response.data.data : [];
  const uniqueProductIds = [...new Set(
    orderItems
      .map((item) => normalizePositiveInteger$1(item?.product_id))
      .filter((value) => value !== null)
  )];

  if (uniqueProductIds.length === 0) {
    return {
      items: orderItems,
      updated_count: 0,
    };
  }

  const priceEntries = await Promise.all(
    uniqueProductIds.map(async (productId) => {
      const finalPrice = await getFinalProductPriceForCustomer(productId, normalizedDepartmentId, normalizedCustomerId);
      return [productId, finalPrice];
    })
  );

  const finalPriceMap = new Map(priceEntries);
  const updateRequests = orderItems
    .map((item) => {
      const normalizedItemId = normalizePositiveInteger$1(item?.id);
      const normalizedProductId = normalizePositiveInteger$1(item?.product_id);
      if (!normalizedItemId || !normalizedProductId || !finalPriceMap.has(normalizedProductId)) {
        return null;
      }

      return editOrderItemForRepricing({
        id: normalizedItemId,
        price: finalPriceMap.get(normalizedProductId),
        notes: item?.notes ?? "",
        reference: item?.reference ?? "",
        quantity: normalizePositiveInteger$1(item?.quantity) ?? 1,
      });
    })
    .filter(Boolean);

  await Promise.all(updateRequests);

  return {
    items: orderItems,
    updated_count: updateRequests.length,
  };
};

const assignDraftOrderCustomer = async ({
  order_id,
  customer_id,
  invoice_collection_id,
  department_id = null,
  recalculate_prices = true,
}) => {
  const normalizedOrderId = normalizePositiveInteger$1(order_id);
  const normalizedCustomerId = normalizePositiveInteger$1(customer_id);
  const normalizedInvoiceCollectionId = normalizePositiveInteger$1(invoice_collection_id);

  if (!normalizedOrderId || !normalizedCustomerId || !normalizedInvoiceCollectionId) {
    throw new Error("Order, customer and invoice collection are required");
  }

  const resolvedDepartmentId = normalizePositiveInteger$1(department_id)
    ?? await SessionUser.objects.orders.functions.get_department_id(normalizedOrderId);

  const customerResponse = await SessionUser.objects.orders.set.customer_id(
    normalizedOrderId,
    normalizedCustomerId
  );

  let repricingResponse = null;
  if (recalculate_prices) {
    repricingResponse = await recalculateOrderItemPricesForCustomer({
      order_id: normalizedOrderId,
      department_id: resolvedDepartmentId,
      customer_id: normalizedCustomerId,
    });
  }

  const invoiceCollectionResponse = await SessionUser.objects.orders.set.invoice_collection_id(
    normalizedOrderId,
    normalizedInvoiceCollectionId
  );

  return {
    customerResponse,
    invoiceCollectionResponse,
    repricingResponse,
    customer_id: normalizedCustomerId,
    invoice_collection_id: normalizedInvoiceCollectionId,
    department_id: resolvedDepartmentId,
  };
};

    /**
     * The Orders object
     */
    const Orders = {
      get meta() {
        return {
          title: t$9('objects.orders.title'),
          icon: "fas fa-list",
          description: t$9('objects.orders.description'),
          endpoint: "/orders",
          labels: {
            single: t$9('objects.orders.single'),
            multiple: t$9('objects.orders.multiple'),
            entries: t$9('objects.orders.entries'),
          }
        };
      },
      get columns() {
        return {
        id: {
          label: t$9('objects.columns.id'),
          type: "number",
          sortable: true,
          creation: {
            required: false
          }
        },
        customer_id: {
          label: t$9('objects.columns.customer'),
          type: "number",
          sortable: true,
          creation: {
            required: true
          }
        },
        cashier_id: {
          label: t$9('objects.orders.columns.cashier'),
          type: "number",
          sortable: true,
          creation: {
            required: false
          }
        },
        department_id: {
          label: t$9('objects.columns.department'),
          type: "select",
          sortable: true,
          creation: {
            required: true
          },
          options: async () => {
            return SessionUser.objects.departments.get.all();
          }
        },
        reference: {
          label: t$9('common.reference'),
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        reg_1: {
          label: t$9('objects.orders.columns.license_plate'),
          type: "string",
          sortable: true,
          creation: {
            required: true
          }
        },
        reg_2: {
          label: t$9('objects.orders.columns.reg_2'),
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        reg_3: {
          label: t$9('objects.orders.columns.reg_3'),
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        notes: {
          label: t$9('objects.columns.notes'),
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        invoice_collection_id: {
          label: t$9('common.invoice'),
          type: "number",
          sortable: true,
          creation: {
            required: false
          }
        },
        booking_id: {
          label: t$9('objects.columns.booking'),
          type: "number",
          sortable: true,
          creation: {
            required: false
          }
        },
        wash_id: {
          label: t$9('objects.orders.columns.wash_id'),
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        lane: {
          label: t$9('objects.orders.columns.lane'),
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        po: {
          label: t$9('objects.orders.columns.po'),
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        safety_seal: {
          label: t$9('admin.pos.safety_seal'),
          type: "string",
          sortable: true,
          creation: {
            required: false
          }
        },
        created_at: {
          label: t$9('common.date'),
          type: "datetime",
          sortable: true,
          creation: {
            required: false
          }
        },
        include_in_invoice: {
          label: t$9('pos.order.include_in_invoice'),
          type: "select",
          sortable: true,
          creation: {
            required: false
          },
          options: async () => {
            return [
              { id: 'use_department', name: t$9('pos.order.invoice_override.use_department') },
              { id: 'include', name: t$9('pos.order.invoice_override.include') },
              { id: 'exclude', name: t$9('pos.order.invoice_override.exclude') },
            ];
          }
        },
        total_net_amount: {
          label: t$9('objects.columns.total_net_amount'),
          type: "number",
          sortable: true,
          creation: {
            required: false
          }
        },
        completed_at: {
          label: t$9('objects.columns.completed'),
          type: "date",
          sortable: true,
          creation: {
            required: false
          }
        },
      };
      },
      add: async (customer_id, cashier_id, department_id, reference, reg_1, reg_2, reg_3, notes, invoice_collection_id) => {
        const response = await ObjectsGlobal.add.object(
            Orders.meta.endpoint,
            {
              customer_id: parseInt(customer_id),
              cashier_id: parseInt(cashier_id),
              department_id: parseInt(department_id),
              reference: reference === null ? "" : reference,
              reg_1: reg_1,
              reg_2: reg_2,
              reg_3: reg_3,
              notes: notes === null ? "" : notes,
              invoice_collection_id: parseInt(invoice_collection_id),
            }
        );
        refreshDraftNavigationCount();
        return response;
      },
      set: {
        customer_id: async (id, customer_id) => {
          const response = await ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "customer_id",
              parseInt(customer_id)
          );
          refreshDraftNavigationCount();
          return response;
        },
        cashier_id: async (id, cashier_id) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "cashier_id",
              parseInt(cashier_id)
          )
        },
        department_id: async (id, department_id) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "department_id",
              parseInt(department_id)
          )
        },
        reference: async (id, reference) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "reference",
              reference
          )
        },
        reg_1: async (id, reg_1) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "reg_1",
              reg_1
          )
        },
        reg_2: async (id, reg_2) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "reg_2",
              reg_2
          )
        },
        reg_3: async (id, reg_3) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "reg_3",
              reg_3
          )
        },
        notes: async (id, notes) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "notes",
              notes
          )
        },
        invoice_collection_id: async (id, invoice_collection_id) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "invoice_collection_id",
              parseInt(invoice_collection_id)
          )
        },
        booking_id: async (id, booking_id) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "booking_id",
              booking_id
          )
        },
        wash_id: async (id, wash_id) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "wash_id",
              wash_id
          )
        },
        lane: async (id, lane) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "lane",
              lane
          )
        },
        po: async (id, po) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "po",
              po
          )
        },
        safety_seal: async (id, safety_seal) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "safety_seal",
              safety_seal
          )
        },
        created_at: async (id, created_at) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "created_at",
              created_at
          )
        },
        include_in_invoice: async (id, include_in_invoice) => {
          const normalizedValue = include_in_invoice === 'include'
              ? true
              : include_in_invoice === 'exclude'
                  ? false
                  : null;
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "include_in_invoice",
              normalizedValue
          )
        },
        completed_at: async (id, completed_at) => {
          return ObjectsGlobal.set.column(
              Orders.meta.endpoint,
              id,
              "completed_at",
              completed_at
          )
        },
      },
      get: {
        all: async () => {
          return ObjectsGlobal.get.objects(Orders.meta.endpoint);
        },
        single: async (id) => {
          return ObjectsGlobal.get.object('/order', id);
        },
        multiple: async (ids) => {
          return ObjectsGlobal.get.objectsByIds('/order', ids);
        },
        list: async (optionsObject = {filters: {}, pagination: {page: 1, limit: 100, order: 'id:DESC'}}) => {
          return ObjectsGlobal.get.list(Orders.meta.endpoint, optionsObject);
        },
      },
      delete: {
        single: async (id, optionsObject = null) => {
          const response = optionsObject
              ? await ObjectsGlobal.delete.object(Orders.meta.endpoint, id, optionsObject)
              : await ObjectsGlobal.delete.object(Orders.meta.endpoint, id);
          refreshDraftNavigationCount();
          return response;
        },
      },
      functions: {
        /**
         * Mark the order as completed
         * @param id
         * @returns {Promise<void>}
         */
        mark_as_completed: async (id) => {
          return SessionUser.request(
              Orders.meta.endpoint + "/mark_as_completed",
              "POST",
              {
                id: id
              },
          )
        },
        /**
         * Get the order department id
         * @param id
         */
        get_department_id: async (id) => {
          return SessionUser.request(
              '/order',
              'GET',
              {
                id: id
              }
          ).then((response) => {
            //console.log(response.data.data.department_id);
            return parseInt(response.data.data.department_id);
          }).catch((error) => {
            console.error(error);
          });
        },
        /**
         * Show deletion confirmation modal
         * @param id
         * @param onAfterSubmit
         */
        showDeleteConfirmationModal: (id, onAfterSubmit = null) => {
          return Swal.fire({
            title: `Fjern ${Orders.meta.labels.single}?`,
            text: ObjectsGlobal.language.confirm_delete_message,
            showCancelButton: true,
            showConfirmButton: true,
            confirmButtonText: ObjectsGlobal.language.confirm_delete,
            cancelButtonText: ObjectsGlobal.language.cancel,
            icon: "warning",
          }).then((result) => {
            if (!result.isConfirmed) {
              return null;
            }
            return deleteOrderWithProtectedConfirmation(id, onAfterSubmit);
          });
        },
        deleteWithConfirmation: async (id, onAfterSubmit = null) => {
          return deleteOrderWithProtectedConfirmation(id, onAfterSubmit);
        },
        /**
         * Get the order customer number
         * @param id (order id)
         */
        get_customer_id: async (id) => {
          return SessionUser.request(
              '/order',
              'GET',
              {
                id: id
              }
          ).then((response) => {
            //console.log(response.data.data.customer_id);
            return parseInt(response.data.data.customer_id);
          }).catch((error) => {
            console.error(error);
          });
        },
        /**
         * Change the order customer
         * @param id (order id)
         * @param customer_id (e-conomic customer number)
         */
        change_customer: async (id, customer_id) => {
          return SessionUser.objects.orders.set.customer_id(id, customer_id);
        },
        /**
         * Show the change customer form
         * @param id (order id)
         */
        showChangeCustomerForm: showChangeOrderCustomerForm,
        assignDraftCustomer: assignDraftOrderCustomer,
        /**
         * Show the change invoice collection form
         * @param id (order id)
         */
        showChangeInvoiceCollectionForm: showChangeOrderInvoiceCollectionForm,
        /**
         * Fetch attachments for the order
         * @param id (order id)
         */
        fetchAttachments: async (id) => {
          return SessionUser.request(
              Orders.meta.endpoint + "/attachments",
              "GET",
              {
                id: id
              },
              null,
              null,
              { concurrencyLimit: 5 }
          ).then((response) => {
            return response.data.data;
          }).catch((error) => {
            console.error(error);
            throw error;
          });
        },
        /**
         * Delete an attachment from the order
         * @param id (order id)
         * @param attachment_id (attachment id)
         */
        removeAttachment: async (id, attachment_id) => {
          return SessionUser.request(
              Orders.meta.endpoint + "/attachments",
              "DELETE",
              {
                order_id: id,
                attachment_id: attachment_id
              }
          ).then((response) => {
            return response.data;
          }).catch((error) => {
            console.error(error);
          });
        },
        /**
         * Upload an attachment to the order
         * @param id (order id)
         * @param filename (filename)
         * @param filedata (filedata as base64)
         */
        uploadAttachment: async (id, filename, filedata) => {
          return SessionUser.request(
              Orders.meta.endpoint + "/attachments/upload",
              "POST",
              {
                order_id: id,
                file_name: filename,
                base64_file: filedata
              }
          ).then((response) => {
            return response.data.data;
          }).catch((error) => {
            console.error(error);
          });
        },
        /**
         * Generate a link, to download an attachment from the order
         * @param id (order id)
         * @param attachment_id (attachment id)
         * @param autoOpen
         */
        downloadAttachment: async (id, attachment_id, autoOpen = false) => {
          return SessionUser.request(
              Orders.meta.endpoint + "/attachments/download",
              "GET",
              {
                order_id: id,
                attachment_id: attachment_id
              }
          ).then((response) => {
            const downloadLink = response.data.data.download_link;
            if (autoOpen) {
              // Open the download link in a new tab
              //window.open(downloadLink, '_blank');
              window.open(downloadLink, '_blank', 'noopener,noreferrer');
            }
            return response.data.data.download_link;
          }).catch((error) => {
            console.error(error);
          });
        },
        resendWashCertificate: async (id) => {
          return SessionUser.request(
              Orders.meta.endpoint + "/wash-certificate/resend",
              "POST",
              { id: parseInt(id, 10) }
          ).then((response) => response.data.data);
        },
        showAttachWashCertificateForm(order_id, onAfterSubmit = null) {
          const normalizedOrderId = Number.parseInt(order_id, 10);
          if (!Number.isInteger(normalizedOrderId) || normalizedOrderId <= 0) {
            return Promise.resolve(false);
          }

          return Swal.fire({
            title: t$9('admin.pos.generate_wash_certificate'),
            text: t$9('admin.pos.enter_safety_seal_number'),
            input: 'text',
            inputLabel: t$9('admin.pos.safety_seal'),
            showCancelButton: true,
            confirmButtonText: t$9('admin.pos.generate_wash_certificate'),
            cancelButtonText: t$9('admin.pos.cancel'),
            preConfirm: (safety_seal) => {
              const normalizedSafetySeal = typeof safety_seal === 'string'
                ? safety_seal.trim()
                : safety_seal;

              return SessionUser.request(
                  '/order/wash-certificate',
                  'POST',
                  {
                    id: normalizedOrderId,
                    safety_seal: normalizedSafetySeal
                  }
              ).then((response) => {
                return response.data.data;
              }).catch((error) => {
                console.error(error);
                const parsedError = SessionUser.functions.parseErrorMessage(error);
                const errorMessage = typeof parsedError === 'string' ? parsedError : '';
                Swal.showValidationMessage([
                  t$9('admin.pos.wash_certificate_generation_error'),
                  errorMessage,
                ].filter(Boolean).join(': '));
              });
            },
            heightAuto: false,
          }).then(async (result) => {
            if (!result.isConfirmed || !result.value) {
              return result;
            }

            if (typeof onAfterSubmit === 'function') {
              try {
                await onAfterSubmit(result.value);
              } catch (error) {
                console.error('Error after attaching wash certificate:', error);
              }
            }

            const alreadyExisted = Boolean(result.value.already_existed);
            await Swal.fire({
              title: alreadyExisted
                ? t$9('admin.pos.settings_wheel.attach_wash_certificate')
                : t$9('admin.pos.generate_wash_certificate'),
              text: alreadyExisted
                ? t$9('admin.pos.wash_certificate_already_attached')
                : t$9('admin.pos.wash_certificate_attached'),
              icon: alreadyExisted ? 'info' : 'success',
              showConfirmButton: false,
              timer: 2000,
              heightAuto: false,
            });

            return result.value;
          });
        }
      },
      /**
       * Show the create object form
       * @param onAfterSubmit
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showCreateObjectForm: (onAfterSubmit = null) => {
        return ObjectsGlobal.showCreateObjectForm(Orders, onAfterSubmit);
      },
      /**
       * Show the edit object field form
       * @param id
       * @param column
       * @param value
       * @param onAfterSubmit
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
        const normalizedValue = column === 'include_in_invoice'
            ? (value === true ? 'include' : value === false ? 'exclude' : 'use_department')
            : value;
        return ObjectsGlobal.showEditObjectFieldForm(
            Orders,
            id,
            column,
            normalizedValue,
            onAfterSubmit
        );
      }
    };

const _sfc_main$q = {};
const Orders_default = /*#__PURE__*/_export_sfc(_sfc_main$q, [['__file',"Orders.vue"]]);

/**
 * The Forms object
 */
const Forms = {
  meta: {
    title: "Formularer",
    icon: "fas fa-list",
    description: "Oversigt over formularer",
    endpoint: "/form",
    labels: {
      single: "formular",
      multiple: "formularer",
      fields: {
        names: {
          customer_number: {
            label: "E-conomic kundenummer",
          },
          contact_email: {
            label: "Kontakt email",
          },
          reference: {
            label: "Reference",
          },
          registration_number_tractor: {
            label: "Reg. nr. trækker",
          },
          registration_number_trailer: {
            label: "Reg. nr. trailer",
          },
          wants_wash_certificate: {
            label: "Ønsker vaskecertifikat ( Safety Seal )",
          },
          wants_wash_certificate_email: {
            label: "Email til vaskecertifikat",
          },
          date: {
            label: "Dato",
          },
          department_id: {
            label: "Afdeling",
          },
          wants_pickup: {
            label: "Ønsker afhentning",
          },
          notes: {
            label: "Noter",
          },
        },
      }
    }
  },
  get: {
    single: async (identifier) => {
      return ObjectsGlobal.get.object(Forms.meta.endpoint, identifier, {authenticated: SessionUser.functions.hasToken()});
    }
  },
  functions: {
    submit: async (form) => {
      console.log(form);
      return ObjectsGlobal.add.object(Forms.meta.endpoint, form, {authenticated: SessionUser.functions.hasToken()});
    },
  },
};

const _sfc_main$p = {};
const Forms_default = /*#__PURE__*/_export_sfc(_sfc_main$p, [['__file',"Forms.vue"]]);

const t$8 = (key) => i18n.global.t(key);

/**
 * The Branding object
 */
const Branding = {
  meta: {
    title: t$8("objects.branding.title"),
    icon: "fas fa-list",
    description: t$8("objects.branding.description"),
    endpoint: "/branding",
    labels: {
      single: t$8("objects.branding.single"),
      multiple: t$8("objects.branding.multiple"),
    },
  },
  columns: {
    id: {
      label: t$8("objects.columns.id"),
      type: "number",
      sortable: true,
      creation: { required: false },
    },
    name: {
      label: t$8("objects.columns.name"),
      type: "string",
      sortable: true,
      creation: { required: true },
    },
    description: {
      label: t$8("objects.columns.description"),
      type: "string",
      sortable: true,
      creation: { required: true },
    },
    cvr: {
      label: t$8("user_admin.cvr"),
      type: "number",
      sortable: true,
      creation: { required: true },
    },
    address: {
      label: t$8("objects.columns.address"),
      type: "string",
      sortable: true,
      creation: { required: false },
    },
    phone_country_code: {
      label: t$8("global.phone_country_code"),
      type: "number",
      sortable: true,
      creation: { required: false },
    },
    phone: {
      label: t$8("objects.columns.phone"),
      type: "number",
      sortable: true,
      creation: { required: false },
    },
    email: {
      label: t$8("objects.columns.email"),
      type: "string",
      sortable: true,
      creation: { required: false },
    },
    website: {
      label: t$8("tables.common.website"),
      type: "string",
      sortable: true,
      creation: { required: false },
    },
    banner: {
      label: t$8("objects.columns.image"),
      type: "string",
      sortable: false,
      creation: { required: false },
    },
    logo: {
      label: t$8("objects.columns.image"),
      type: "string",
      sortable: false,
      creation: { required: false },
    },
    favicon: {
      label: t$8("objects.columns.image"),
      type: "string",
      sortable: false,
      creation: { required: false },
    },
    signature: {
      label: t$8("objects.columns.notes"),
      type: "string",
      sortable: false,
      creation: { required: false },
    },
  },
  add: async (brandingOrName, description = null, cvr = null) => {
    const payload =
      typeof brandingOrName === "object" && brandingOrName !== null
        ? brandingOrName
        : {
            name: brandingOrName,
            description,
            cvr,
          };

    return ObjectsGlobal.add.object(Branding.meta.endpoint, payload).then((response) => response.data.data);
  },
  set: {
    all: async (id, branding) => {
      ObjectsGlobal.clearCache();
      return authenticatedRequest(Branding.meta.endpoint, "PUT", {
        id: parseInt(id, 10),
        ...branding,
      }).then((response) => {
        ObjectsGlobal.clearCache();
        return response.data.data;
      });
    },
    name: async (id, name) => ObjectsGlobal.set.column(Branding.meta.endpoint, id, "name", name),
    description: async (id, description) =>
      ObjectsGlobal.set.column(Branding.meta.endpoint, id, "description", description),
    cvr: async (id, cvr) => ObjectsGlobal.set.column(Branding.meta.endpoint, id, "cvr", parseInt(cvr, 10)),
    address: async (id, address) => ObjectsGlobal.set.column(Branding.meta.endpoint, id, "address", address),
    phone_country_code: async (id, phone_country_code) =>
      ObjectsGlobal.set.column(Branding.meta.endpoint, id, "phone_country_code", parseInt(phone_country_code, 10)),
    phone: async (id, phone) => ObjectsGlobal.set.column(Branding.meta.endpoint, id, "phone", parseInt(phone, 10)),
    email: async (id, email) => ObjectsGlobal.set.column(Branding.meta.endpoint, id, "email", email),
    website: async (id, website) => ObjectsGlobal.set.column(Branding.meta.endpoint, id, "website", website),
    banner: async (id, banner) => ObjectsGlobal.set.column(Branding.meta.endpoint, id, "banner", banner),
    logo: async (id, logo) => ObjectsGlobal.set.column(Branding.meta.endpoint, id, "logo", logo),
    favicon: async (id, favicon) => ObjectsGlobal.set.column(Branding.meta.endpoint, id, "favicon", favicon),
    signature: async (id, signature) => ObjectsGlobal.set.column(Branding.meta.endpoint, id, "signature", signature),
  },
  get: {
    all: async () => ObjectsGlobal.get.objects(Branding.meta.endpoint),
    single: async (id) => ObjectsGlobal.get.object(Branding.meta.endpoint, parseInt(id, 10)),
  },
  delete: async (id) => ObjectsGlobal.delete.object(Branding.meta.endpoint, parseInt(id, 10)),
  functions: {},
  showCreateObjectForm: (onAfterSubmit = null) => ObjectsGlobal.showCreateObjectForm(Branding, onAfterSubmit),
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) =>
    ObjectsGlobal.showEditObjectFieldForm(Branding, id, column, value, onAfterSubmit),
};

const _sfc_main$o = {};
const Brandings = /*#__PURE__*/_export_sfc(_sfc_main$o, [['__file',"Brandings.vue"]]);

const t$7 = (key) => i18n.global.t(key);


/**
 * The Vehicles object
 */
const Vehicles = {
  get meta() {
    return {
      title: t$7('common.vehicles'),
      icon: "fas fa-list",
      description: t$7('objects.vehicles.description'),
      endpoint: "/vehicles",
      labels: {
        single: t$7('objects.vehicles.single'),
        multiple: t$7('objects.vehicles.multiple')
      }
    };
  },
  get columns() {
    return {
    id: {
      label: t$7('objects.columns.id'),
      type: "number",
      sortable: true,
      creation: {
        required: false,
      }
    },
    type: {
      label: t$7('vehicles.type'),
      type: "select",
      sortable: true,
      creation: {
        required: true,
      },
      options: async (only_that_allows_subscription = true, options = {isWash: true, addDefaultOption: true, restrictToCategory4: null, includeProductRaw: false}) => {
        // Get all the products, that has 'subscription_allowed' set to true
        let products = await SessionUser.objects.products.get.all();
        let opt = {
          isWash: null,
          addDefaultOption: true,
          restrictToCategory4: null,
          includeProductRaw: false,
          allowsSubscription: true,
          ...(options ? options : {}),
          ...(only_that_allows_subscription ? {allowsSubscription: true} : {}),
        };
        console.warn("Getting products with options", opt);
        // If the options are set, filter the products based on the product flags
        if (opt.isWash !== null) {
          products = products.filter((product) => product.is_wash === opt.isWash);
        }
        if (opt.addDefaultOption !== false) {
          // Add a default option (0, unknown)
          products.unshift({
            id: 0,
            name: "Ukendt"
          });
        }
        // Filter the products based on the subscription_allowed flag and category
        if (opt.allowsSubscription !== null) {
          products = products.filter((product) => product.subscription_allowed === opt.allowsSubscription);
        }
        if (opt.restrictToCategory4 === true) {
          products = products.filter((product) => product.category === 4 || product.id === 0); // Only allow category 4 (car) and defaultValue
        }
        // Map the products to the opt
        return products.map((product) => {
          return {
            ...opt.includeProductRaw ? { product: product } : {},
            id: parseInt(product.id),
            name: product.name,
            addons: product.addons,
            price: product.price,
          }
        });
      },
    },
    reg: {
      label: t$7('objects.vehicles.columns.reg'),
      type: "string",
      sortable: true,
      creation: {
        required: true,
      }
    },
    wash_subscription: {
      label: t$7('objects.vehicles.columns.wash_subscription'),
      type: "boolean",
      sortable: true,
      creation: {
        required: true,
        default: false,
      }
    },
    customer_id: {
      label: t$7('objects.columns.customer_id'),
      type: "number",
      sortable: true,
      creation: {
        required: true,
      }
    },
    reference: {
      label: t$7('common.reference'),
      type: "string",
      sortable: true,
      creation: {
        required: false,
      }
    },
  };
  },
  add: async (type, reg, wash_subscription = false, customer_id, reference = null) => {
      return ObjectsGlobal.add.object(
        Vehicles.meta.endpoint,
        {
          type: parseInt(type),
          reg: reg,
          wash_subscription: ObjectsGlobal.parse.boolean(wash_subscription),
          customer_id: parseInt(customer_id),
          ...(reference ? { reference: reference } : {}),
        }
      );
    },
  set: {
    type: async (id, type) => {
      return ObjectsGlobal.set.column(
        Vehicles.meta.endpoint,
        id,
        "type",
        parseInt(type)
      )
    },
    reg: async (id, reg) => {
      return ObjectsGlobal.set.column(
        Vehicles.meta.endpoint,
        id,
        "reg",
        reg
      )
    },
    wash_subscription: async (id, wash_subscription) => {
      console.log("Setting wash_subscription for vehicle", id, wash_subscription);
      return ObjectsGlobal.set.column(
        Vehicles.meta.endpoint,
        id,
        "wash_subscription",
        ObjectsGlobal.parse.boolean(wash_subscription)
      ).catch((error) => {
        Swal.fire({
          title: "Fejl",
          text: error.response.data.data.message,
          icon: "error",
        });
        throw error;
      });
    },
    reference: async (id, reference) => {
      return ObjectsGlobal.set.column(
        Vehicles.meta.endpoint,
        id,
        "reference",
        reference
      )
    },
  },
  get: {
    all: async (filters = {}) => {
      return ObjectsGlobal.get.objects(Vehicles.meta.endpoint, filters);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(Vehicles.meta.endpoint, id);
    },
    user: async (customer_number) => {
      // Get all vehicles for a specific user
      return ObjectsGlobal.get.objects(
          Vehicles.meta.endpoint,
          {
            filters: "customer_id:" + parseInt(customer_number),
          }
      );
    },
  },
  delete: async (id) => {
    // Delete the object
    return ObjectsGlobal.delete.object(
        Vehicles.meta.endpoint,
        id
    );
  },
  scoped: {
    endpoint: (userId) => `/superuser/users/${encodeURIComponent(userId)}/vehicles`,
    add: async (userId, type, reg, wash_subscription = false, customer_id = null, reference = null) => {
      return ObjectsGlobal.add.object(
          Vehicles.scoped.endpoint(userId),
          {
            type: parseInt(type),
            reg,
            wash_subscription: ObjectsGlobal.parse.boolean(wash_subscription),
            ...(customer_id ? { customer_id: parseInt(customer_id) } : {}),
            ...(reference ? { reference } : {}),
          }
      );
    },
    set: async (userId, id, column, value) => {
      return ObjectsGlobal.set.column(Vehicles.scoped.endpoint(userId), id, column, value);
    },
    delete: async (userId, id) => {
      return ObjectsGlobal.delete.object(Vehicles.scoped.endpoint(userId), id);
    },
  },
  functions: {
    showDeleteObjectForm: async (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(
          Vehicles,
          parseInt(id),
          onAfterSubmit
      );
    },
    showDeleteObjectForUserForm: async (userId, id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(
          {
            ...Vehicles,
            delete: (vehicleId) => Vehicles.scoped.delete(userId, vehicleId),
          },
          parseInt(id),
          onAfterSubmit
      );
    },
    showCreateObjectForCustomerForm: async (customerId, onAfterSubmit = null) => {
      return ObjectsGlobal.showCreateObjectForm(
          Vehicles,
          onAfterSubmit,
          {
            customer_id: parseInt(customerId),
          },
      );
    },
    showCreateObjectForUserForm: async (userId, customerId, onAfterSubmit = null) => {
      return ObjectsGlobal.showCreateObjectForm(
          {
            ...Vehicles,
            add: (type, reg, washSubscription, scopedCustomerId, reference = null) => Vehicles.scoped.add(
                userId,
                type,
                reg,
                washSubscription,
                scopedCustomerId,
                reference
            ),
          },
          onAfterSubmit,
          {
            customer_id: parseInt(customerId),
          },
      );
    },
    showEditObjectFieldForUserForm: async (userId, id, column, value, onAfterSubmit = null, options = {}) => {
      const html = await ObjectsGlobal.generateEditObjectFieldForm(Vehicles, column, value, options);
      return Swal.fire({
        title: ObjectsGlobal.language.field(Vehicles, column),
        html,
        showCancelButton: true,
        confirmButtonText: ObjectsGlobal.language.save,
        cancelButtonText: ObjectsGlobal.language.cancel,
        preConfirm: () => {
          try {
            const newValue = document.getElementById(column).value;
            return Vehicles.scoped.set(userId, id, column, newValue).then(() => {
              if (onAfterSubmit !== null) {
                return Promise.resolve(onAfterSubmit());
              }
              return null;
            }).catch((error) => {
              Swal.showValidationMessage(`Fejl: ${error.message || error}`);
              return false;
            });
          } catch (error) {
            Swal.showValidationMessage(`Fejl: ${error}`);
            return false;
          }
        },
      });
    },
    getVehicleStatus: async (registrationNumber, department = null) => {
      // Get the vehicle status
      return ObjectsGlobal.get.object(
          "/vehicles/status",
          { reg: registrationNumber, ...(department ? { department: department } : {}) },
          { authentication: true }
      );
    },
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(Vehicles, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        Vehicles,
        id,
        column,
        value,
        onAfterSubmit
    );
  },
};

const _sfc_main$n = {};
const Vehicles_default = /*#__PURE__*/_export_sfc(_sfc_main$n, [['__file',"Vehicles.vue"]]);

// Helper function to get i18n translation
const t$6 = (key) => i18n.global.t(key);

/**
 * The DepartmentNotificationSms object
 */
const DepartmentNotificationSms = {
  meta: {
    get title() { return t$6('objects.department_notification_sms.title'); },
    icon: "fas fa-list",
    get description() { return t$6('objects.department_notification_sms.description'); },
    endpoint: "/department/notification/sms",
    labels: {
      get single() { return t$6('objects.department_notification_sms.single'); },
      get multiple() { return t$6('objects.department_notification_sms.multiple'); }
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    department: {
      get label() { return t$6('objects.department_notification_sms.columns.department'); },
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return SessionUser.objects.departments.get.all();
      }
    },
    label: {
      get label() { return t$6('objects.department_notification_sms.columns.label'); },
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
    phone_country_code: {
      get label() { return t$6('objects.department_notification_sms.columns.phone_country_code'); },
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return [
        {
          name: t$6('objects.department_notification_sms.country_codes.denmark'),
          id: 45
        },
        {
          name: t$6('objects.department_notification_sms.country_codes.sweden'),
          id: 46
        },
        {
          name: t$6('objects.department_notification_sms.country_codes.norway'),
          id: 47
        },
        {
          name: t$6('objects.department_notification_sms.country_codes.finland'),
          id: 358
        }
      ];
      }
    },
    phone: {
      get label() { return t$6('objects.department_notification_sms.columns.phone'); },
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
    enabled: {
      get label() { return t$6('common.enabled'); },
      type: "boolean",
      sortable: true,
      creation: {
        required: false
      }
    },
  },
  add: async (department, label, phone_country_code, phone) => {
    return ObjectsGlobal.add.object(
        DepartmentNotificationSms.meta.endpoint,
        {
          department: parseInt(department),
          label: label,
          phone_country_code: parseInt(phone_country_code),
          phone: parseInt(phone)
        }
    );
  },
  set: {
    label: async (id, label) => {
      return ObjectsGlobal.set.column(
        DepartmentNotificationSms.meta.endpoint,
        id,
        "label",
        label
      )
    },
    phone_country_code: async (id, phone_country_code) => {
      return ObjectsGlobal.set.column(
        DepartmentNotificationSms.meta.endpoint,
        id,
        "phone_country_code",
        parseInt(phone_country_code)
      )
    },
    phone: async (id, phone) => {
      return ObjectsGlobal.set.column(
        DepartmentNotificationSms.meta.endpoint,
        id,
        "phone",
        parseInt(phone)
      )
    },
    enabled: async (id, enabled = false) => {
      return ObjectsGlobal.set.column(
        DepartmentNotificationSms.meta.endpoint,
        id,
        "enabled",
        SessionUser.objects.global.parse.boolean(enabled)
      )
    },
    department: async (id, department) => {
      return ObjectsGlobal.set.column(
        DepartmentNotificationSms.meta.endpoint,
        id,
        "department",
        parseInt(department)
      )
    }
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(DepartmentNotificationSms.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(DepartmentNotificationSms.meta.endpoint, id);
    }
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(DepartmentNotificationSms.meta.endpoint, id);
  },
  functions: {
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(DepartmentNotificationSms, id, onAfterSubmit);
    },
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @param lockedValues
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null, lockedValues = {}) => {
    return ObjectsGlobal.showCreateObjectForm(DepartmentNotificationSms, onAfterSubmit, lockedValues);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        DepartmentNotificationSms,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$m = {};
const DepartmentNotificationSms_default = /*#__PURE__*/_export_sfc(_sfc_main$m, [['__file',"DepartmentNotificationSms.vue"]]);

/**
 * The DepartmentTimeBookingsOpeningHours object
 */
const DepartmentTimeBookingsOpeningHours = {
  meta: {
    title: "Tidsbookings åbningstider",
    icon: "fas fa-list",
    description: "Oversigt over afdelings tidsbookings åbningstider.",
    endpoint: "/department/timebookings/opening-hours",
    labels: {
      single: "åbningstid",
      multiple: "åbningstider"
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    department: {
      label: "Afdeling",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return SessionUser.objects.departments.get.all();
      }
    },
    monday_start: {
      label: "Mandag åbningstid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    monday_end: {
      label: "Mandag lukketid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    tuesday_start: {
      label: "Tirsdag åbningstid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    tuesday_end: {
      label: "Tirsdag lukketid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    wednesday_start: {
      label: "Onsdag åbningstid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    wednesday_end: {
      label: "Onsdag lukketid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    thursday_start: {
      label: "Torsdag åbningstid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    thursday_end: {
      label: "Torsdag lukketid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    friday_start: {
      label: "Fredag åbningstid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    friday_end: {
      label: "Fredag lukketid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    saturday_start: {
      label: "Lørdag åbningstid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    saturday_end: {
      label: "Lørdag lukketid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    sunday_start: {
      label: "Søndag åbningstid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    },
    sunday_end: {
      label: "Søndag lukketid",
      type: "time",
      sortable: true,
      creation: {
        required: false
      }
    }
  },
  add: async (department, monday_start = null, monday_end = null, tuesday_start = null, tuesday_end = null, wednesday_start = null, wednesday_end = null, thursday_start = null, thursday_end = null, friday_start = null, friday_end = null, saturday_start = null, saturday_end = null, sunday_start = null, sunday_end = null) => {
    return ObjectsGlobal.add.object(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        {
          department: parseInt(department),
          monday_start: monday_start,
          monday_end: monday_end,
          tuesday_start: tuesday_start,
          tuesday_end: tuesday_end,
          wednesday_start: wednesday_start,
          wednesday_end: wednesday_end,
          thursday_start: thursday_start,
          thursday_end: thursday_end,
          friday_start: friday_start,
          friday_end: friday_end,
          saturday_start: saturday_start,
          saturday_end: saturday_end,
          sunday_start: sunday_start,
          sunday_end: sunday_end,
        }
    );
  },
  set: {
    monday_start: async (id, monday_start) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "monday_start",
        monday_start
      )
    },
    monday_end: async (id, monday_end) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "monday_end",
        monday_end
      )
    },
    tuesday_start: async (id, tuesday_start) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "tuesday_start",
        tuesday_start
      )
    },
    tuesday_end: async (id, tuesday_end) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "tuesday_end",
        tuesday_end
      )
    },
    wednesday_start: async (id, wednesday_start) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "wednesday_start",
        wednesday_start
      )
    },
    wednesday_end: async (id, wednesday_end) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "wednesday_end",
        wednesday_end
      )
    },
    thursday_start: async (id, thursday_start) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "thursday_start",
        thursday_start
      )
    },
    thursday_end: async (id, thursday_end) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "thursday_end",
        thursday_end
      )
    },
    friday_start: async (id, friday_start) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "friday_start",
        friday_start
      )
    },
    friday_end: async (id, friday_end) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "friday_end",
        friday_end
      )
    },
    saturday_start: async (id, saturday_start) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "saturday_start",
        saturday_start
      )
    },
    saturday_end: async (id, saturday_end) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "saturday_end",
        saturday_end
      )
    },
    sunday_start: async (id, sunday_start) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "sunday_start",
        sunday_start
      )
    },
    sunday_end: async (id, sunday_end) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsOpeningHours.meta.endpoint,
        id,
        "sunday_end",
        sunday_end
      )
    },
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(DepartmentTimeBookingsOpeningHours.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(DepartmentTimeBookingsOpeningHours.meta.endpoint, id);
    }
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(DepartmentTimeBookingsOpeningHours.meta.endpoint, id);
  },
  functions: {
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(DepartmentTimeBookingsOpeningHours, id, onAfterSubmit);
    },
    getPublicOpeningHours: async (departmentId) => {
      /**
       * Example usage:
       * https://api.truckwash.dk:4433/department/timebookings/opening-hours/public?id=1
       * This endpoint returns the public opening hours for a specific department.
       */
      // Check if departmentId is valid
      if (!departmentId || isNaN(departmentId)) {
        console.warn('Invalid department ID:', departmentId);
        return [];
      }
      // Make the request to fetch public opening hours
      return SessionUser.request(
        `${DepartmentTimeBookingsOpeningHours.meta.endpoint}/public`,
          'GET',
          {
            id: departmentId,
            },
      ).then(response => {
        return response.data.data;
      }).catch(error => {
        console.error("Error fetching public available times:", error, departmentId);
        throw error;
      });
    }
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @param lockedValues
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null, lockedValues = {}) => {
    return ObjectsGlobal.showCreateObjectForm(DepartmentTimeBookingsOpeningHours, onAfterSubmit, lockedValues);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        DepartmentTimeBookingsOpeningHours,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$l = {};
const DepartmentTimeBookingsOpeningHours_default = /*#__PURE__*/_export_sfc(_sfc_main$l, [['__file',"DepartmentTimeBookingsOpeningHours.vue"]]);

/**
 * The DepartmentTimeBookingsTypes object
 */
const DepartmentTimeBookingsTypes = {
  meta: {
    title: "Tidsbookings typer",
    icon: "fas fa-list",
    description: "Oversigt over afdelings tidsbookings typer.",
    endpoint: "/department/timebookings/types",
    labels: {
      single: "vasketype",
      multiple: "vasketyper",
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    department: {
      label: "Afdeling",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return SessionUser.objects.departments.get.all();
      }
    },
    name: {
      label: "Navn",
      type: "string",
      sortable: true,
      creation: {
        required: false
      }
    },
    product: {
      label: "Produkt",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        // Get all the products, that has 'subscription_allowed' set to true
        let products = await SessionUser.objects.products.get.all();
        products = products.filter((product) => product.id <= 20);
        // Add a default option (0, unknown)
        products.unshift({
          id: 0,
          name: "Ukendt"
        });
        // Map the products to the options
        return products.map((product) => {
          return {
            id: parseInt(product.id),
            name: product.name
          }
        });
      }
    },
    description: {
      label: "Beskrivelse",
      type: "string",
      sortable: true,
      creation: {
        required: false
      }
    },
    duration: {
      label: "Varighed (minutter)",
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
  },
  add: async (department, product, duration, name = null, description = null) => {
    return ObjectsGlobal.add.object(
        DepartmentTimeBookingsTypes.meta.endpoint,
        {
          department: parseInt(department),
          product: parseInt(product),
          name: name,
          description: description,
          duration: parseInt(duration),
        }
    );
  },
  set: {
    name: async (id, name) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsTypes.meta.endpoint,
        id,
        "name",
        name
      )
    },
    product: async (id, product) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsTypes.meta.endpoint,
        id,
        "product",
        parseInt(product)
      )
    },
    description: async (id, description) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsTypes.meta.endpoint,
        id,
        "description",
        description
      )
    },
    duration: async (id, duration) => {
      return ObjectsGlobal.set.column(
        DepartmentTimeBookingsTypes.meta.endpoint,
        id,
        "duration",
        parseInt(duration)
      )
    },
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(DepartmentTimeBookingsTypes.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(DepartmentTimeBookingsTypes.meta.endpoint, id);
    }
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(DepartmentTimeBookingsTypes.meta.endpoint, id);
  },
  functions: {
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(DepartmentTimeBookingsTypes, id, onAfterSubmit);
    },
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @param lockedValues
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null, lockedValues = {}) => {
    return ObjectsGlobal.showCreateObjectForm(DepartmentTimeBookingsTypes, onAfterSubmit, lockedValues);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        DepartmentTimeBookingsTypes,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$k = {};
const DepartmentTimeBookingsTypes_default = /*#__PURE__*/_export_sfc(_sfc_main$k, [['__file',"DepartmentTimeBookingsTypes.vue"]]);

const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;

const normalizeDateFilterValue = (value) => {
  const formatted = formatLocalDateOnly(value);
  return DATE_ONLY_PATTERN.test(formatted) ? formatted : null;
};

/**
 * The DepartmentTimeBookingsEntries object
 */
const DepartmentTimeBookingsEntries = {
  meta: {
    title: "Tidsbookinger",
    icon: "fas fa-list",
    description: "Oversigt over afdelings tidsbookinger.",
    endpoint: "/department/timebookings/entries",
    labels: {
      single: "tidsbooking",
      multiple: "tidsbookinger",
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    department: {
      label: "Afdeling",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return SessionUser.objects.departments.get.all();
      }
    },
    type: {
      label: "Type",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return SessionUser.objects.department_time_bookings_types.get.all();
      }
    },
    start: {
      label: "Start",
      type: "datetime",
      sortable: true,
      creation: {
        required: true
      }
    },
    end: {
      label: "Slut",
      type: "datetime",
      sortable: true,
      creation: {
        required: false
      }
    },
    phone_country_code: {
      label: "Landekode",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return [
          {
            name: "Danmark (+45)",
            id: 45
          },
          {
            name: "Sverige (+46)",
            id: 46
          },
        ];
      }
    },
    phone: {
      label: "Telefonnummer",
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
    reg: {
      label: "Reg. 1.",
      type: "datetime",
      sortable: true,
      creation: {
        required: false
      }
    },
    note: {
      label: "Note",
      type: "string",
      sortable: true,
      creation: {
        required: false
      }
    },
  },
  add: async (department, type, start, phone_country_code, phone, reg = null, note = null, addons = [], publicEndpoint = false) => {
    return ObjectsGlobal.add.object(
        DepartmentTimeBookingsEntries.meta.endpoint + (publicEndpoint ? '/public' : ''),
        {
          department: parseInt(department),
          type: parseInt(type),
          start: start,
          end: null, // End is optional and can be set later
          phone_country_code: parseInt(phone_country_code),
          phone: parseInt(phone),
          reg: reg ? reg : null, // Reg is optional and can be set later
          note: note ? note : null, // Note is optional and can be set later
          addons: addons ? addons : [], // Addons are optional and can be set later
        }
    );
  },
  set: {
    department: async (id, department) => {
      return ObjectsGlobal.set.column(
          DepartmentTimeBookingsEntries.meta.endpoint,
        id,
        "department",
        parseInt(department)
      )
    },
    type: async (id, type) => {
      return ObjectsGlobal.set.column(
          DepartmentTimeBookingsEntries.meta.endpoint,
        id,
        "type",
        parseInt(type)
      )
    },
    start: async (id, start) => {
      return ObjectsGlobal.set.column(
          DepartmentTimeBookingsEntries.meta.endpoint,
        id,
        "start",
        start
      )
    },
    end: async (id, end) => {
      return ObjectsGlobal.set.column(
          DepartmentTimeBookingsEntries.meta.endpoint,
        id,
        "end",
        end
      )
    },
    phone_country_code: async (id, phone_country_code) => {
      return ObjectsGlobal.set.column(
          DepartmentTimeBookingsEntries.meta.endpoint,
        id,
        "phone_country_code",
        parseInt(phone_country_code)
      )
    },
    phone: async (id, phone) => {
      return ObjectsGlobal.set.column(
          DepartmentTimeBookingsEntries.meta.endpoint,
        id,
        "phone",
        parseInt(phone)
      )
    },
    reg: async (id, reg) => {
      return ObjectsGlobal.set.column(
          DepartmentTimeBookingsEntries.meta.endpoint,
        id,
        "reg",
        reg
      )
    },
    note: async (id, note) => {
      return ObjectsGlobal.set.column(
          DepartmentTimeBookingsEntries.meta.endpoint,
        id,
        "note",
        note
      )
    },
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(DepartmentTimeBookingsEntries.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(DepartmentTimeBookingsEntries.meta.endpoint, id);
    }
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(DepartmentTimeBookingsEntries.meta.endpoint, id);
  },
  functions: {
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(DepartmentTimeBookingsEntries, id, onAfterSubmit);
    },
    getPublicEntries: async (departmentId, dateFrom = null, dateTo = null) => {
      /**
       * Example usage:
       * https://api.truckwash.dk:4433/department/timebookings/entries/public?id=1&filters=start-date_from:2025-04-01,start-date_to:2025-05-30&order=start:asc
       * This will return all public available times for the department with ID 1
       * The dateFrom and dateTo parameters are optional and can be used to filter the results by date range.
       * If not provided, it will return all available times.
       */
      if (!departmentId || isNaN(departmentId)) {
        console.warn('Invalid department ID:', departmentId);
        return [];
      }
      dateFrom = normalizeDateFilterValue(dateFrom);
      dateTo = normalizeDateFilterValue(dateTo);

      if (dateFrom && !DATE_ONLY_PATTERN.test(dateFrom)) {
        console.warn('Invalid dateFrom format:', dateFrom, 'Expected format: YYYY-MM-DD');
        dateFrom = null;
      }
      if (dateTo && !DATE_ONLY_PATTERN.test(dateTo)) {
        console.warn('Invalid dateTo format:', dateTo, 'Expected format: YYYY-MM-DD');
        dateTo = null;
      }
      // If the dateFrom or dateTo is not provided, set it to the last 7 days and today respectively
      if (!dateFrom) {
        const lastWeek = new Date();
        lastWeek.setDate(lastWeek.getDate() - 7);
        dateFrom = formatLocalDateOnly(lastWeek); // Format as YYYY-MM-DD
      }
      if (!dateTo) {
        dateTo = todayLocalDateOnly(); // Format as YYYY-MM-DD
      }
      console.log("Fetching public available times for department:", departmentId, "from", dateFrom, "to", dateTo);
      // Make the request to fetch public available times for the department
      return SessionUser.request(
          `${DepartmentTimeBookingsEntries.meta.endpoint}/public`,
          'GET',
          {
            id: departmentId,
            filters: `start-date_from:${dateFrom || ''},start-date_to:${dateTo || ''}`,
            order: "start:asc",
          },
      ).then(response => {
        return response.data.data;
      }).catch(error => {
        console.error("Error fetching public available times:", error, departmentId);
        throw error;
      });
    }
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @param lockedValues
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null, lockedValues = {}) => {
    return ObjectsGlobal.showCreateObjectForm(DepartmentTimeBookingsEntries, onAfterSubmit, lockedValues);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        DepartmentTimeBookingsEntries,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$j = {};
const DepartmentTimeBookingsEntries_default = /*#__PURE__*/_export_sfc(_sfc_main$j, [['__file',"DepartmentTimeBookingsEntries.vue"]]);

const t$5 = (key) => i18n.global.t(key);

/**
 * The DepartmentVariables object
 */
const DepartmentVariables = {
  meta: {
    title: t$5("objects.department_variables.title"),
    icon: "fas fa-list",
    description: t$5("objects.department_variables.description"),
    endpoint: "/superuser/department/variables",
    labels: {
      single: t$5("objects.department_variables.single"),
      multiple: t$5("objects.department_variables.multiple"),
    }
  },
  columns: {
    id: {
      label: t$5("objects.columns.id"),
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    department_id: {
      label: t$5("objects.columns.department_id"),
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return SessionUser.objects.departments.get.all();
      }
    },
    variable: {
      label: t$5("objects.columns.key"),
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
    value: {
      label: t$5("objects.columns.value"),
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
  },
  add: async (department_id, variable, value) => {
    return ObjectsGlobal.add.object(
        DepartmentVariables.meta.endpoint,
        {
          department_id: parseInt(department_id),
          variable: variable,
          value: value
        }
    );
  },
  set: {},
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(DepartmentVariables.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(DepartmentVariables.meta.endpoint, id);
    },
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(DepartmentVariables.meta.endpoint, id);
  },
  functions: {
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(DepartmentVariables, id, onAfterSubmit);
    },
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @param lockedValues
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null, lockedValues = {}) => {
    return ObjectsGlobal.showCreateObjectForm(DepartmentVariables, onAfterSubmit, lockedValues);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        DepartmentVariables,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$i = {};
const DepartmentVariables_default = /*#__PURE__*/_export_sfc(_sfc_main$i, [['__file',"DepartmentVariables.vue"]]);

/**
 * Local vehicle types cache
 * @type {ref<null>}
 */
const vehicle_types_cache = ref(null);
/**
 * Get the vehicle type name
 * @param id
 * @param fallback
 * @returns {string}
 */
const getVehicleTypeName = (id, fallback = null) => {
  if (vehicle_types_cache.value === null) {
    vehicle_types_cache.value = [];
    SessionUser.objects.xlvask_vehicle_types.get.all().then((vehicle_types) => {
      vehicle_types_cache.value = vehicle_types;
    });
  }
  const vehicle_type = vehicle_types_cache.value.find((vehicle_type) => vehicle_type.vehicleTypeId === id);
  return vehicle_type ? vehicle_type.name : fallback === null ? SessionUser.objects.global.language.no_data : fallback;
};

/**
 * The XLVaskVehicleTypes object
 */
const XLVaskVehicleTypes = {
  meta: {
    title: "Køretøjstyper",
    icon: "fas fa-list",
    description: "Oversigt over køretøjstyper",
    endpoint: "/modules/xlvask/internal/vehicle-types",
    labels: {
      single: "køretøjstype",
      multiple: "køretøjstyper"
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    vehicleTypeId: {
      label: "Vehicle Type ID",
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
    product: {
      label: "Produkt",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return SessionUser.objects.vehicles.columns.type.options();
      },
    },
    name: {
      label: "Navn",
      type: "string",
      sortable: true,
      creation: {
        required: false
      }
    },
  },
  add: async (vehicleTypeId, product, name = null) => {
    return ObjectsGlobal.add.object(
        XLVaskVehicleTypes.meta.endpoint,
        {
          vehicleTypeId: vehicleTypeId,
          product: parseInt(product),
          name: name,
        }
    );
  },
  set: {
    vehicleTypeId: async (id, vehicleTypeId) => {
      return ObjectsGlobal.set.column(
        XLVaskVehicleTypes.meta.endpoint,
        parseInt(id),
        "vehicleTypeId",
        vehicleTypeId
      )
    },
    product: async (id, product) => {
      return ObjectsGlobal.set.column(
        XLVaskVehicleTypes.meta.endpoint,
        parseInt(id),
        "product",
        parseInt(product)
      )
    },
    name: async (id, name) => {
      return ObjectsGlobal.set.column(
        XLVaskVehicleTypes.meta.endpoint,
        parseInt(id),
        "name",
        name
      )
    },
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(XLVaskVehicleTypes.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(XLVaskVehicleTypes.meta.endpoint, id);
    }
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(XLVaskVehicleTypes.meta.endpoint, id);
  },
  functions: {
    getVehicleTypeName: getVehicleTypeName,
    /**
     * Show the delete object form
     * @param id
     * @param onAfterSubmit
     * @returns {Promise<SweetAlertResult<Awaited<any>>>}
     */
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(XLVaskVehicleTypes, id, onAfterSubmit);
    },
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @param lockedValues
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null, lockedValues = {}) => {
    return ObjectsGlobal.showCreateObjectForm(XLVaskVehicleTypes, onAfterSubmit, lockedValues);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        XLVaskVehicleTypes,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$h = {};
const XLVaskVehicleTypes_default = /*#__PURE__*/_export_sfc(_sfc_main$h, [['__file',"XLVaskVehicleTypes.vue"]]);

const normalizeRelayOption = (option) => {
  const id = String(option?.id ?? "").trim();
  if (id === "") {
    return null;
  }

  const name = String(option?.name ?? id).trim();
  return {
    ...option,
    id,
    name: name === "" ? id : name,
  };
};

const listShellyRelayOptions = async () => {
  const response = await authenticatedRequest("/department/lanes/relay-options", "GET", {});
  const rows = Array.isArray(response?.data?.data) ? response.data.data : [];

  return rows
    .map((row) => normalizeRelayOption(row))
    .filter((row) => row !== null);
};

const t$4 = (key) => i18n.global.t(key);
    const buildShellyRelaySelectOptions = async () => ([
      { id: 0, name: t$4('global.not_configured') },
      ...(await listShellyRelayOptions())
    ]);

    const normalizeRelaySelection = (relayId) => {
      const normalizedRelayId = String(relayId ?? "").trim();
      if (normalizedRelayId === "" || normalizedRelayId === "0" || normalizedRelayId.toLowerCase() === "null") {
        return null;
      }

      return normalizedRelayId;
    };

    const OPERATIONAL_STATUSES = ["AVAILABLE", "OCCUPIED", "RESERVED"];
    const SELF_SERVE_CONFIGURATION_FIELDS = [
      { field: "relay_in_id", label: "Indgangsrelæ" },
      { field: "relay_out_id", label: "Udgangsrelæ" },
      { field: "relay_machine_id", label: "Maskinrelæ" },
      { field: "relay_machine_program_picker_id", label: "Programvælgerrelæ" },
      { field: "relay_machine_cleaner_id", label: "Vaskerelæ" },
      { field: "dynamic_image_id", label: "Maskinstatusbillede" },
      { field: "machine_type_id", label: "Maskintype" },
    ];

    const hasConfiguredValue = (value) => {
      if (value === null || value === undefined) {
        return false;
      }

      if (typeof value === "string") {
        const normalizedValue = value.trim().toLowerCase();
        return normalizedValue !== "" && normalizedValue !== "0" && normalizedValue !== "null";
      }

      if (typeof value === "number") {
        return value > 0;
      }

      return Boolean(value);
    };

    const getSelfServeConfigurationWarnings = (object) => {
      if (Array.isArray(object?.dognvask_configuration_warnings)) {
        return object.dognvask_configuration_warnings;
      }

      return SELF_SERVE_CONFIGURATION_FIELDS
        .filter(({ field }) => !hasConfiguredValue(object?.[field]))
        .map(({ field, label }) => ({
          field,
          label,
          message: `${label} mangler`,
        }));
    };

    const isSelfServeConfigured = (object) => {
      if (typeof object?.dognvask_configured === "boolean") {
        return object.dognvask_configured;
      }
      if (typeof object?.selfserve_configured === "boolean") {
        return object.selfserve_configured;
      }

      return getSelfServeConfigurationWarnings(object).length === 0;
    };

    const isMachineStatusEnabled = (object) => {
      if (typeof object?.machine_status_enabled === "boolean") {
        return object.machine_status_enabled;
      }

      return OPERATIONAL_STATUSES.includes(String(object?.status ?? "").toUpperCase());
    };

    /**
     * The Department Lanes object
     */
    const DepartmentLanes = {
      get meta() {
        return {
          title: t$4('objects.department_lanes.title'),
          icon: "fas fa-list",
          description: t$4('objects.department_lanes.description'),
          endpoint: "/department/lanes",
          labels: {
            single: t$4('objects.department_lanes.single'),
            multiple: t$4('objects.department_lanes.multiple')
          }
        };
      },
      get columns() {
        return {
          id: {
            label: t$4('objects.columns.id'),
            type: "number",
            sortable: true,
            creation: {
              required: false
            }
          },
          department: {
            label: t$4('objects.columns.department'),
            type: "select",
            sortable: true,
            creation: {
              required: true
            },
            options: async () => {
              return SessionUser.objects.departments.get.all();
            }
          },
          name: {
            label: t$4('common.name'),
            type: "string",
            sortable: true,
            creation: {
              required: true
            }
          },
          relay_in_id: {
            label: t$4('objects.columns.relay_in_id'),
            type: "select",
            sortable: true,
            creation: {
              required: false
            },
            options: buildShellyRelaySelectOptions
          },
          relay_out_id: {
            label: t$4('objects.columns.relay_out_id'),
            type: "select",
            sortable: true,
            creation: {
              required: false
            },
            options: buildShellyRelaySelectOptions
          },
          relay_machine_id: {
            label: t$4('objects.columns.relay_machine_id'),
            type: "select",
            sortable: true,
            creation: {
              required: false
            },
            options: buildShellyRelaySelectOptions
          },
          relay_machine_program_picker_id: {
            label: t$4('objects.columns.relay_machine_program_picker_id'),
            type: "select",
            sortable: true,
            creation: {
              required: false
            },
            options: buildShellyRelaySelectOptions
          },
          relay_machine_cleaner_id: {
            label: t$4('objects.columns.relay_machine_cleaner_id'),
            type: "select",
            sortable: true,
            creation: {
              required: false
            },
            options: buildShellyRelaySelectOptions
          },
          dynamic_image_id: {
            label: t$4('objects.columns.dynamic_image_id'),
            type: "number",
            sortable: true,
            creation: {
              required: false
            }
          },
          machine_type_id: {
            label: 'Self-serve maskintype',
            type: "select",
            sortable: true,
            creation: {
              required: false
            },
            options: async () => {
              const machineTypes = await SessionUser.objects.self_serve_machine_types.get.all();
              return [
                { id: 0, name: t$4('global.none') },
                ...machineTypes.map((entry) => ({
                  id: entry.id,
                  name: entry.name,
                }))
              ];
            }
          },
          selfserve_enabled: {
            label: "Self-Serve aktiv",
            type: "boolean",
            sortable: true,
            creation: {
              required: false
            }
          }
        };
      },
      add: async (
        department,
        name,
        relay_in_id = null,
        relay_out_id = null,
        relay_machine_id = null,
        relay_machine_program_picker_id = null,
        relay_machine_cleaner_id = null,
        dynamic_image_id = null,
        machine_type_id = null,
        selfserve_enabled = true
      ) => {
        return ObjectsGlobal.add.object(
            DepartmentLanes.meta.endpoint,
            {
              department: parseInt(department),
              name: name,
              relay_in_id: normalizeRelaySelection(relay_in_id),
              relay_out_id: normalizeRelaySelection(relay_out_id),
              relay_machine_id: normalizeRelaySelection(relay_machine_id),
              relay_machine_program_picker_id: normalizeRelaySelection(relay_machine_program_picker_id),
              relay_machine_cleaner_id: normalizeRelaySelection(relay_machine_cleaner_id),
              dynamic_image_id: dynamic_image_id ? parseInt(dynamic_image_id) : null,
              machine_type_id: machine_type_id ? parseInt(machine_type_id) : null,
              selfserve_enabled: Boolean(selfserve_enabled)
            }
        );
      },
      set: {
        department: async (id, department) => {
          return ObjectsGlobal.set.column(
              DepartmentLanes.meta.endpoint,
              id,
              "department",
              department
          )
        },
        name: async (id, name) => {
          return ObjectsGlobal.set.column(
              DepartmentLanes.meta.endpoint,
              id,
              "name",
              name
          )
        },
        relay_in_id: async (id, relay_in_id) => {
          return ObjectsGlobal.set.column(
              DepartmentLanes.meta.endpoint,
              id,
              "relay_in_id",
              normalizeRelaySelection(relay_in_id)
          )
        },
        relay_out_id: async (id, relay_out_id) => {
          return ObjectsGlobal.set.column(
              DepartmentLanes.meta.endpoint,
              id,
              "relay_out_id",
              normalizeRelaySelection(relay_out_id)
          )
        },
        relay_machine_id: async (id, relay_machine_id) => {
          return ObjectsGlobal.set.column(
              DepartmentLanes.meta.endpoint,
              id,
              "relay_machine_id",
              normalizeRelaySelection(relay_machine_id)
          )
        },
        relay_machine_program_picker_id: async (id, relay_machine_program_picker_id) => {
          return ObjectsGlobal.set.column(
              DepartmentLanes.meta.endpoint,
              id,
              "relay_machine_program_picker_id",
              normalizeRelaySelection(relay_machine_program_picker_id)
          )
        },
        relay_machine_cleaner_id: async (id, relay_machine_cleaner_id) => {
          return ObjectsGlobal.set.column(
              DepartmentLanes.meta.endpoint,
              id,
              "relay_machine_cleaner_id",
              normalizeRelaySelection(relay_machine_cleaner_id)
          )
        },
        dynamic_image_id: async (id, dynamic_image_id) => {
          return ObjectsGlobal.set.column(
              DepartmentLanes.meta.endpoint,
              id,
              "dynamic_image_id",
              dynamic_image_id ? parseInt(dynamic_image_id) : null
          )
        },
        machine_type_id: async (id, machine_type_id) => {
          return ObjectsGlobal.set.column(
              DepartmentLanes.meta.endpoint,
              id,
              "machine_type_id",
              machine_type_id && parseInt(machine_type_id) !== 0 ? parseInt(machine_type_id) : null
          )
        },
        selfserve_enabled: async (id, selfserve_enabled) => {
          return ObjectsGlobal.set.column(
              DepartmentLanes.meta.endpoint,
              id,
              "selfserve_enabled",
              Boolean(selfserve_enabled)
          )
        },
      },
      get: {
        all: async () => {
          return ObjectsGlobal.get.objects(DepartmentLanes.meta.endpoint);
        },
        single: async (id) => {
          return ObjectsGlobal.get.object(DepartmentLanes.meta.endpoint, id);
        }
      },
      enumerations: {
        status: [
          "OCCUPIED",
          "AVAILABLE",
          "RESERVED",
          "FAULT",
          "MAINTENANCE",
          "CLOSED",
        ]
      },
      functions: {
        getDepartmentName: getDepartmentName$2,
        getStatusToggles: async (departmentId) => {
          return SessionUser.request('/department/lanes/status-toggles', 'GET', {
            department_id: parseInt(departmentId)
          });
        },
        setMachineStatusEnabled: async (laneId, enabled) => {
          return SessionUser.request('/modules/self-serve/lane/status', 'PUT', {
            lane_id: parseInt(laneId),
            enabled: Boolean(enabled),
          });
        },
        isMachineStatusEnabled,
        isSelfServeConfigured,
        getSelfServeConfigurationWarnings,
        isOperational: (object) => {
          return object.status === "AVAILABLE" || object.status === "OCCUPIED" || object.status === "RESERVED";
        },
        isConfigured: (object) => {
          let requiredFields = [
            "relay_in_id",
            "relay_out_id",
            "relay_machine_id"
          ];
          return requiredFields.every(field => object[field] !== null && object[field] !== "" );
        },
        isFaulty: (object) => {
          return object.status === "FAULT" || object.status === "MAINTENANCE" || object.status === "CLOSED";
        },
        isWashing: (object) => {
          return object.status === "OCCUPIED";
        },
        stopWashing: async (object) => {
          // Create the request payload
          const payload = {
            lane_id: object.id,
            command: 'STOP',
          };
          // Send the request to stop the wash
          SessionUser.request('/modules/self-serve/lane/command', 'post', payload)
              .then(response => {
                if (response.data.success) {
                  alert('Vask stoppet succesfuldt.');
                } else {
                  alert('Fejl ved stop af vask: ' + (response.data.message || 'Ukendt fejl.'));
                }
              })
              .catch(error => {
                console.error('Error stopping wash:', error);
                alert('Der opstod en fejl ved stop af vasken. Prøv igen senere.');
              });

        },
        /**
         * Force enable the machine relay for a lane
         * @param {number} laneId - The ID of the lane
         * @returns {Promise} - The API response
         */
        forceEnableMachine: async (laneId) => {
          return SessionUser.request('/modules/self-serve/lane/force/machine/enable', 'post', {
            lane_id: parseInt(laneId)
          });
        },
        /**
         * Force disable the machine relay for a lane
         * @param {number} laneId - The ID of the lane
         * @returns {Promise} - The API response
         */
        forceDisableMachine: async (laneId) => {
          return SessionUser.request('/modules/self-serve/lane/force/machine/disable', 'post', {
            lane_id: parseInt(laneId)
          });
        }
      },
      /**
       * Show the create object form
       * @param onAfterSubmit
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showCreateObjectForm: (onAfterSubmit = null) => {
        return ObjectsGlobal.showCreateObjectForm(DepartmentLanes, onAfterSubmit);
      },
      /**
       * Show the edit object field form
       * @param id
       * @param column
       * @param value
       * @param onAfterSubmit
       * @returns {Promise<SweetAlertResult<Awaited<any>>>}
       */
      showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
        return ObjectsGlobal.showEditObjectFieldForm(
            DepartmentLanes,
            id,
            column,
            value,
            onAfterSubmit
        );
      }
    };

const _sfc_main$g = {};
const DepartmentLanes_default = /*#__PURE__*/_export_sfc(_sfc_main$g, [['__file',"DepartmentLanes.vue"]]);

const t$3 = (key) => i18n.global.t(key);

const parseConfig$1 = (config) => {
  if (config === null || config === undefined || config === '') {
    return {};
  }

  if (typeof config === 'object') {
    return config;
  }

  try {
    return JSON.parse(config);
  } catch (error) {
    return { value: config };
  }
};

const validateDepartmentGateConfig = (config) => {
  const normalizedConfig = parseConfig$1(config);
  const normalizedType = String(normalizedConfig?.type ?? '').trim().toUpperCase();

  if (normalizedType !== 'PHONE_CALL') {
    if (normalizedType !== 'RELAY') {
      return normalizedConfig;
    }

    const relayId = String(normalizedConfig?.relay_id ?? '').trim();
    if (relayId === '') {
      throw new Error("RELAY gates require a 'relay_id' value.");
    }

    if (normalizedConfig?.pulse_seconds !== undefined && normalizedConfig?.pulse_seconds !== null && normalizedConfig?.pulse_seconds !== '') {
      const pulseSeconds = Number(normalizedConfig.pulse_seconds);
      if (!Number.isFinite(pulseSeconds) || pulseSeconds <= 0) {
        throw new Error("RELAY gates require a positive 'pulse_seconds' value when provided.");
      }
    }

    return {
      ...normalizedConfig,
      type: 'RELAY',
      relay_id: relayId,
    };
  }

  const phoneNumber = String(normalizedConfig?.phone_number ?? '').trim();
  if (phoneNumber === '') {
    throw new Error("PHONE_CALL gates require a 'phone_number' value.");
  }

  const threshold = Number(normalizedConfig?.call_duration_threshold);
  if (!Number.isFinite(threshold) || threshold <= 0) {
    throw new Error("PHONE_CALL gates require a positive 'call_duration_threshold'.");
  }

  return normalizedConfig;
};

const CONFIG_VALUE_TYPE = {
  STRING: 'string',
  NUMBER: 'number',
  BOOLEAN: 'boolean',
  OBJECT: 'object',
  ARRAY: 'array',
  NULL: 'null'
};

const CONFIG_MODAL_MAX_WIDTH = 1100;
const CONFIG_MODAL_MIN_WIDTH = 700;
const CONFIG_MODAL_HORIZONTAL_MARGIN = 64;

const escapeHtml$2 = (value = '') => String(value)
  .replaceAll('&', '&amp;')
  .replaceAll('<', '&lt;')
  .replaceAll('>', '&gt;')
  .replaceAll('"', '&quot;')
  .replaceAll("'", '&#039;');

const inferConfigValueType = (value) => {
  if (value === null) {
    return CONFIG_VALUE_TYPE.NULL;
  }
  if (Array.isArray(value)) {
    return CONFIG_VALUE_TYPE.ARRAY;
  }
  if (typeof value === 'number') {
    return CONFIG_VALUE_TYPE.NUMBER;
  }
  if (typeof value === 'boolean') {
    return CONFIG_VALUE_TYPE.BOOLEAN;
  }
  if (typeof value === 'object') {
    return CONFIG_VALUE_TYPE.OBJECT;
  }
  return CONFIG_VALUE_TYPE.STRING;
};

const serializeConfigValue = (value, type = inferConfigValueType(value)) => {
  if (type === CONFIG_VALUE_TYPE.NULL) {
    return '';
  }

  if (type === CONFIG_VALUE_TYPE.OBJECT || type === CONFIG_VALUE_TYPE.ARRAY) {
    return JSON.stringify(value, null, 2);
  }

  return String(value ?? '');
};

const parseConfigFieldValue = (type, rawValue) => {
  const normalizedValue = String(rawValue ?? '').trim();

  switch (type) {
    case CONFIG_VALUE_TYPE.STRING:
      return rawValue ?? '';
    case CONFIG_VALUE_TYPE.NUMBER: {
      if (normalizedValue === '') {
        throw new Error('Value is required for number fields.');
      }
      const parsed = Number(normalizedValue);
      if (Number.isNaN(parsed)) {
        throw new Error('Invalid number format.');
      }
      return parsed;
    }
    case CONFIG_VALUE_TYPE.BOOLEAN: {
      const lowerValue = normalizedValue.toLowerCase();
      if (lowerValue !== 'true' && lowerValue !== 'false') {
        throw new Error("Boolean values must be 'true' or 'false'.");
      }
      return lowerValue === 'true';
    }
    case CONFIG_VALUE_TYPE.OBJECT: {
      if (normalizedValue === '') {
        return {};
      }
      let parsed;
      try {
        parsed = JSON.parse(normalizedValue);
      } catch (error) {
        throw new Error('Object values must be valid JSON.');
      }
      if (parsed === null || Array.isArray(parsed) || typeof parsed !== 'object') {
        throw new Error('Object values must decode to a JSON object.');
      }
      return parsed;
    }
    case CONFIG_VALUE_TYPE.ARRAY: {
      if (normalizedValue === '') {
        return [];
      }
      let parsed;
      try {
        parsed = JSON.parse(normalizedValue);
      } catch (error) {
        throw new Error('Array values must be valid JSON.');
      }
      if (!Array.isArray(parsed)) {
        throw new Error('Array values must decode to a JSON array.');
      }
      return parsed;
    }
    case CONFIG_VALUE_TYPE.NULL:
      return null;
    default:
      return rawValue ?? '';
  }
};

const getConfigEntries = (config) => {
  const parsedConfig = parseConfig$1(config);

  if (!parsedConfig || Array.isArray(parsedConfig) || typeof parsedConfig !== 'object') {
    return [];
  }

  return Object.entries(parsedConfig).map(([key, value]) => {
    const type = inferConfigValueType(value);
    return {
      key,
      type,
      value: serializeConfigValue(value, type)
    };
  });
};

const renderConfigTypeOptions = (selectedType = CONFIG_VALUE_TYPE.STRING) => {
  return [
    { value: CONFIG_VALUE_TYPE.STRING, label: 'String' },
    { value: CONFIG_VALUE_TYPE.NUMBER, label: 'Number' },
    { value: CONFIG_VALUE_TYPE.BOOLEAN, label: 'Boolean' },
    { value: CONFIG_VALUE_TYPE.OBJECT, label: 'Object (JSON)' },
    { value: CONFIG_VALUE_TYPE.ARRAY, label: 'Array (JSON)' },
    { value: CONFIG_VALUE_TYPE.NULL, label: 'Null' }
  ].map((option) => (
    `<option value="${option.value}" ${selectedType === option.value ? 'selected' : ''}>${option.label}</option>`
  )).join('');
};

const renderConfigValueInput = (type, value = '') => {
  const escapedValue = escapeHtml$2(value);

  if (type === CONFIG_VALUE_TYPE.OBJECT || type === CONFIG_VALUE_TYPE.ARRAY) {
    const placeholder = type === CONFIG_VALUE_TYPE.OBJECT ? '{"key":"value"}' : '["value"]';
    return `<textarea class="textarea has-background-light has-text-black" rows="3" data-config-value placeholder="${placeholder}">${escapedValue}</textarea>`;
  }

  if (type === CONFIG_VALUE_TYPE.BOOLEAN) {
    const normalizedValue = String(value ?? '').trim().toLowerCase();
    return `<div class="select is-fullwidth">
      <select class="has-background-light has-text-black" data-config-value>
        <option value="" ${(normalizedValue !== 'true' && normalizedValue !== 'false') ? 'selected' : ''}>Select value</option>
        <option value="true" ${normalizedValue === 'true' ? 'selected' : ''}>true</option>
        <option value="false" ${normalizedValue === 'false' ? 'selected' : ''}>false</option>
      </select>
    </div>`;
  }

  if (type === CONFIG_VALUE_TYPE.NULL) {
    return `<input class="input has-background-light has-text-black" type="text" data-config-value value="" placeholder="Always null" disabled>`;
  }

  const inputType = type === CONFIG_VALUE_TYPE.NUMBER ? 'number' : 'text';
  const placeholder = type === CONFIG_VALUE_TYPE.NUMBER ? '0' : 'Value';
  return `<input class="input has-background-light has-text-black" type="${inputType}" data-config-value placeholder="${placeholder}" value="${escapedValue}">`;
};

const renderConfigRow = (entry, index) => {
  return `<div class="columns is-multiline is-variable is-2 is-vcentered mb-2" data-config-row data-row-index="${index}">
    <div class="column is-12-mobile is-4-tablet">
      <label class="label is-small has-text-grey mb-1 is-hidden-tablet">Field</label>
      <input class="input has-background-light has-text-black" type="text" data-config-key placeholder="Key" value="${escapeHtml$2(entry.key)}">
    </div>
    <div class="column is-12-mobile is-2-tablet">
      <label class="label is-small has-text-grey mb-1 is-hidden-tablet">Type</label>
      <div class="select is-fullwidth">
        <select class="has-background-light has-text-black" data-config-type>
          ${renderConfigTypeOptions(entry.type)}
        </select>
      </div>
    </div>
    <div class="column is-12-mobile is-5-tablet">
      <label class="label is-small has-text-grey mb-1 is-hidden-tablet">Value</label>
      <div data-config-value-slot>
        ${renderConfigValueInput(entry.type, entry.value)}
      </div>
    </div>
    <div class="column is-12-mobile is-1-tablet has-text-right-tablet">
      <label class="label is-small has-text-grey mb-1 is-hidden-mobile">&nbsp;</label>
      <button class="button is-danger is-light" type="button" data-config-remove>
        <span class="icon is-small"><i class="fas fa-trash"></i></span>
      </button>
    </div>
  </div>`;
};

const getConfigModalWidth = () => {
  const viewportWidth = typeof window !== 'undefined' && Number.isFinite(window.innerWidth)
    ? window.innerWidth
    : CONFIG_MODAL_MAX_WIDTH + CONFIG_MODAL_HORIZONTAL_MARGIN;
  const availableWidth = Math.max(0, viewportWidth - CONFIG_MODAL_HORIZONTAL_MARGIN);

  if (availableWidth <= CONFIG_MODAL_MIN_WIDTH) {
    return '94vw';
  }

  return `${Math.min(CONFIG_MODAL_MAX_WIDTH, availableWidth)}px`;
};

const buildConfigModalHtml = (currentConfig) => {
  const entries = getConfigEntries(currentConfig);
  const normalizedEntries = entries.length > 0 ? entries : [{
    key: '',
    type: CONFIG_VALUE_TYPE.STRING,
    value: ''
  }];

  return `<div id="department-gates-config-modal">
    <div class="mb-3 has-text-left">
      <label class="label has-text-black mb-1">${DepartmentGates.columns.config.label}</label>
      <p class="is-size-7 has-text-grey">Edit each config field directly. JSON values can still be used for Object and Array types.</p>
      <p class="is-size-7 has-text-grey mt-2">For PHONE_CALL gates, set <code>type=PHONE_CALL</code>, <code>phone_number</code>, and a positive <code>call_duration_threshold</code>.</p>
      <p class="is-size-7 has-text-grey">The <code>is_entrance</code> and <code>is_exit</code> columns decide whether the gate is offered as IVR option 1 or 2.</p>
    </div>
    <div class="columns is-hidden-mobile is-vcentered mb-2">
      <div class="column is-4"><p class="is-size-7 has-text-weight-semibold has-text-grey" data-config-header-key>Field</p></div>
      <div class="column is-2"><p class="is-size-7 has-text-weight-semibold has-text-grey" data-config-header-type>Type</p></div>
      <div class="column is-5"><p class="is-size-7 has-text-weight-semibold has-text-grey" data-config-header-value>Value</p></div>
      <div class="column is-1"></div>
    </div>
    <div id="department-gates-config-rows">
      ${normalizedEntries.map((entry, index) => renderConfigRow(entry, index)).join('')}
    </div>
    <div class="has-text-left mt-2">
      <button class="button is-small is-link is-light" type="button" id="department-gates-config-add-row" data-config-add-row>
        <span class="icon is-small"><i class="fas fa-plus"></i></span>
        <span>Add field</span>
      </button>
    </div>
  </div>`;
};

const bindConfigModalEvents = () => {
  const container = document.getElementById('department-gates-config-modal');
  const rowsContainer = container?.querySelector('#department-gates-config-rows');
  const addRowButton = container?.querySelector('[data-config-add-row]');
  if (!rowsContainer || !addRowButton) {
    return;
  }

  let nextIndex = rowsContainer.querySelectorAll('[data-config-row]').length;

  const appendRow = () => {
    const rowWrapper = document.createElement('div');
    rowWrapper.innerHTML = renderConfigRow({
      key: '',
      type: CONFIG_VALUE_TYPE.STRING,
      value: ''
    }, nextIndex);
    nextIndex += 1;
    const row = rowWrapper.firstElementChild;
    if (row) {
      rowsContainer.appendChild(row);
    }
  };

  addRowButton.addEventListener('click', appendRow);

  rowsContainer.addEventListener('change', (event) => {
    const typeSelect = event.target.closest('[data-config-type]');
    if (!typeSelect) {
      return;
    }

    const row = typeSelect.closest('[data-config-row]');
    const valueSlot = row?.querySelector('[data-config-value-slot]');
    if (!row || !valueSlot) {
      return;
    }

    const currentValue = row.querySelector('[data-config-value]')?.value ?? '';
    valueSlot.innerHTML = renderConfigValueInput(typeSelect.value, currentValue);
  });

  rowsContainer.addEventListener('click', (event) => {
    const removeButton = event.target.closest('[data-config-remove]');
    if (!removeButton) {
      return;
    }

    const row = removeButton.closest('[data-config-row]');
    if (!row) {
      return;
    }

    const allRows = rowsContainer.querySelectorAll('[data-config-row]');
    if (allRows.length <= 1) {
      const keyInput = row.querySelector('[data-config-key]');
      const typeSelect = row.querySelector('[data-config-type]');
      const valueSlot = row.querySelector('[data-config-value-slot]');
      if (keyInput) keyInput.value = '';
      if (typeSelect) typeSelect.value = CONFIG_VALUE_TYPE.STRING;
      if (valueSlot) valueSlot.innerHTML = renderConfigValueInput(CONFIG_VALUE_TYPE.STRING, '');
      return;
    }

    row.remove();
  });
};

const collectConfigFromModal = () => {
  const container = document.getElementById('department-gates-config-modal');
  const rows = container?.querySelectorAll('[data-config-row]') ?? [];
  const config = {};

  for (const row of rows) {
    const keyInput = row.querySelector('[data-config-key]');
    const typeInput = row.querySelector('[data-config-type]');
    const valueInput = row.querySelector('[data-config-value]');

    const key = keyInput?.value?.trim() ?? '';
    const type = typeInput?.value ?? CONFIG_VALUE_TYPE.STRING;
    const rawValue = valueInput?.value ?? '';

    if (key === '' && String(rawValue).trim() === '') {
      continue;
    }
    if (key === '') {
      throw new Error('Field name is required for all config entries.');
    }
    if (Object.prototype.hasOwnProperty.call(config, key)) {
      throw new Error(`Duplicate field name '${key}'.`);
    }

    config[key] = parseConfigFieldValue(type, rawValue);
  }

  return config;
};

const GATE_MANAGE_FIELD_IDS = {
  name: 'department-gate-name',
  isEntrance: 'department-gate-is-entrance',
  isExit: 'department-gate-is-exit',
  transportType: 'department-gate-transport-type',
  phoneNumber: 'department-gate-phone-number',
  callDurationThreshold: 'department-gate-call-duration-threshold',
  relayId: 'department-gate-relay-id',
  pulseSeconds: 'department-gate-pulse-seconds'
};

const normalizeDepartmentGateTransportType = (value) =>
  String(value ?? '').trim().toUpperCase() === 'RELAY' ? 'RELAY' : 'PHONE_CALL';

const normalizeDepartmentGateDraft = (value = {}) => {
  const config = parseConfig$1(value?.config);
  const threshold = config?.call_duration_threshold;
  const pulseSeconds = config?.pulse_seconds;

  return {
    id: value?.id ?? null,
    department: value?.department ?? value?.department_id ?? null,
    name: String(value?.name ?? ''),
    is_entrance: Boolean(value?.is_entrance),
    is_exit: Boolean(value?.is_exit),
    transport_type: normalizeDepartmentGateTransportType(value?.transport_type ?? config?.type),
    phone_number: String(config?.phone_number ?? ''),
    call_duration_threshold:
      threshold === undefined || threshold === null || threshold === '' ? '30' : String(threshold),
    relay_id: String(config?.relay_id ?? ''),
    pulse_seconds:
      pulseSeconds === undefined || pulseSeconds === null || pulseSeconds === '' ? '1' : String(pulseSeconds)
  };
};

const buildDepartmentGateManageHtml = (draft) => {
  const transportType = normalizeDepartmentGateTransportType(draft.transport_type);
  const showPhoneCallFields = transportType === 'PHONE_CALL';

  return `<div id="department-gate-manage-form">
    <div class="field">
      <label class="label has-text-black">${DepartmentGates.columns.name.label}</label>
      <div class="control">
        <input class="input has-background-light has-text-black" type="text" id="${GATE_MANAGE_FIELD_IDS.name}" value="${escapeHtml$2(draft.name)}" placeholder="Gate name">
      </div>
    </div>
    <div class="columns is-multiline is-variable is-3">
      <div class="column is-12-mobile is-6-tablet">
        <label class="label has-text-black">${DepartmentGates.columns.is_entrance.label}</label>
        <div class="select is-fullwidth">
          <select id="${GATE_MANAGE_FIELD_IDS.isEntrance}" class="has-background-light has-text-black">
            <option value="true" ${draft.is_entrance ? 'selected' : ''}>${ObjectsGlobal.language.yes}</option>
            <option value="false" ${!draft.is_entrance ? 'selected' : ''}>${ObjectsGlobal.language.no}</option>
          </select>
        </div>
      </div>
      <div class="column is-12-mobile is-6-tablet">
        <label class="label has-text-black">${DepartmentGates.columns.is_exit.label}</label>
        <div class="select is-fullwidth">
          <select id="${GATE_MANAGE_FIELD_IDS.isExit}" class="has-background-light has-text-black">
            <option value="true" ${draft.is_exit ? 'selected' : ''}>${ObjectsGlobal.language.yes}</option>
            <option value="false" ${!draft.is_exit ? 'selected' : ''}>${ObjectsGlobal.language.no}</option>
          </select>
        </div>
      </div>
    </div>
    <div class="field">
      <label class="label has-text-black">Transport type</label>
      <div class="select is-fullwidth">
        <select id="${GATE_MANAGE_FIELD_IDS.transportType}" class="has-background-light has-text-black">
          <option value="PHONE_CALL" ${transportType === 'PHONE_CALL' ? 'selected' : ''}>PHONE_CALL</option>
          <option value="RELAY" ${transportType === 'RELAY' ? 'selected' : ''}>RELAY</option>
        </select>
      </div>
      <p class="help has-text-grey">PHONE_CALL gates require a number and positive threshold. RELAY gates require a relay id.</p>
    </div>
    <div data-gate-phone-call-fields style="display: ${showPhoneCallFields ? 'block' : 'none'}">
      <div class="field">
        <label class="label has-text-black">Phone number</label>
        <div class="control">
          <input class="input has-background-light has-text-black" type="text" id="${GATE_MANAGE_FIELD_IDS.phoneNumber}" value="${escapeHtml$2(draft.phone_number)}" placeholder="+4512345678">
        </div>
      </div>
      <div class="field">
        <label class="label has-text-black">Call duration threshold</label>
        <div class="control">
          <input class="input has-background-light has-text-black" type="number" min="1" id="${GATE_MANAGE_FIELD_IDS.callDurationThreshold}" value="${escapeHtml$2(draft.call_duration_threshold)}" placeholder="30">
        </div>
      </div>
    </div>
    <div data-gate-relay-fields style="display: ${showPhoneCallFields ? 'none' : 'block'}">
      <div class="field">
        <label class="label has-text-black">Relay id</label>
        <div class="control">
          <input class="input has-background-light has-text-black" type="text" id="${GATE_MANAGE_FIELD_IDS.relayId}" value="${escapeHtml$2(draft.relay_id)}" placeholder="M-7">
        </div>
      </div>
      <div class="field">
        <label class="label has-text-black">Pulse seconds</label>
        <div class="control">
          <input class="input has-background-light has-text-black" type="number" min="1" step="1" id="${GATE_MANAGE_FIELD_IDS.pulseSeconds}" value="${escapeHtml$2(draft.pulse_seconds)}" placeholder="1">
        </div>
      </div>
    </div>
  </div>`;
};

const syncDepartmentGateManageFields = () => {
  const transportTypeField = document.getElementById(GATE_MANAGE_FIELD_IDS.transportType);
  const phoneCallFields = document.querySelector('[data-gate-phone-call-fields]');
  const relayFields = document.querySelector('[data-gate-relay-fields]');
  const isPhoneCall = normalizeDepartmentGateTransportType(transportTypeField?.value) === 'PHONE_CALL';

  if (phoneCallFields) {
    phoneCallFields.style.display = isPhoneCall ? 'block' : 'none';
  }
  if (relayFields) {
    relayFields.style.display = isPhoneCall ? 'none' : 'block';
  }
};

const bindDepartmentGateManageEvents = () => {
  const transportTypeField = document.getElementById(GATE_MANAGE_FIELD_IDS.transportType);
  if (!transportTypeField) {
    return;
  }

  transportTypeField.addEventListener('change', syncDepartmentGateManageFields);
  syncDepartmentGateManageFields();
};

const getDepartmentGateManageFieldValue = (fieldId) => document.getElementById(fieldId)?.value ?? '';

const collectDepartmentGateManageForm = (draft) => {
  const department = Number(draft?.department ?? 0);
  if (!Number.isFinite(department) || department <= 0) {
    throw new Error('Department is required.');
  }

  const name = String(getDepartmentGateManageFieldValue(GATE_MANAGE_FIELD_IDS.name)).trim();
  if (name === '') {
    throw new Error('Name is required.');
  }

  const transportType = normalizeDepartmentGateTransportType(
    getDepartmentGateManageFieldValue(GATE_MANAGE_FIELD_IDS.transportType)
  );
  const relayPulseSeconds = String(getDepartmentGateManageFieldValue(GATE_MANAGE_FIELD_IDS.pulseSeconds)).trim();
  const config =
    transportType === 'RELAY'
      ? validateDepartmentGateConfig({
          type: 'RELAY',
          relay_id: getDepartmentGateManageFieldValue(GATE_MANAGE_FIELD_IDS.relayId),
          ...(relayPulseSeconds !== '' ? { pulse_seconds: Number(relayPulseSeconds) } : {})
        })
      : validateDepartmentGateConfig({
          type: 'PHONE_CALL',
          phone_number: getDepartmentGateManageFieldValue(GATE_MANAGE_FIELD_IDS.phoneNumber),
          call_duration_threshold: Number(
            getDepartmentGateManageFieldValue(GATE_MANAGE_FIELD_IDS.callDurationThreshold)
          )
        });

  return {
    department,
    name,
    is_entrance: ObjectsGlobal.parse.boolean(getDepartmentGateManageFieldValue(GATE_MANAGE_FIELD_IDS.isEntrance)),
    is_exit: ObjectsGlobal.parse.boolean(getDepartmentGateManageFieldValue(GATE_MANAGE_FIELD_IDS.isExit)),
    config
  };
};

const updateDepartmentGate = async (id, payload) => {
  ObjectsGlobal.clearCache();
  return authenticatedRequest(DepartmentGates.meta.endpoint, 'PUT', {
    id,
    ...payload
  }).then((response) => {
    ObjectsGlobal.clearCache();
    return response;
  });
};

const showManageDepartmentGateForm = async (value = {}, onAfterSubmit = null) => {
  const draft = normalizeDepartmentGateDraft(value);
  const isEditing = Number(draft.id || 0) > 0;

  return Swal.fire({
    title: isEditing ? `Rediger ${DepartmentGates.meta.labels.single.toLowerCase()}` : ObjectsGlobal.language.title(DepartmentGates),
    width: 720,
    html: buildDepartmentGateManageHtml(draft),
    showCancelButton: true,
    showLoaderOnConfirm: true,
    allowOutsideClick: () => !Swal.isLoading(),
    confirmButtonText: ObjectsGlobal.language.save,
    cancelButtonText: ObjectsGlobal.language.cancel,
    didOpen: () => {
      bindDepartmentGateManageEvents();
    },
    preConfirm: async () => {
      try {
        const payload = collectDepartmentGateManageForm(draft);
        if (isEditing) {
          await updateDepartmentGate(draft.id, payload);
        } else {
          await DepartmentGates.add(
            payload.department,
            payload.name,
            payload.is_entrance,
            payload.is_exit,
            payload.config
          );
        }
        if (onAfterSubmit !== null) {
          await onAfterSubmit(payload);
        }
      } catch (error) {
        Swal.showValidationMessage(`Fejl: ${error.message || error}`);
        return false;
      }
    }
  });
};

const showEditConfigObjectFieldForm = async (id, value, onAfterSubmit = null) => {
  return Swal.fire({
    title: ObjectsGlobal.language.field(DepartmentGates, 'config'),
    width: getConfigModalWidth(),
    html: buildConfigModalHtml(value),
    showCancelButton: true,
    confirmButtonText: ObjectsGlobal.language.save,
    cancelButtonText: ObjectsGlobal.language.cancel,
    didOpen: () => {
      bindConfigModalEvents();
    },
    preConfirm: () => {
      try {
        const config = validateDepartmentGateConfig(collectConfigFromModal());
        return DepartmentGates.set.config(id, config).then(() => {
          if (onAfterSubmit !== null) {
            onAfterSubmit();
          }
        }).catch((error) => {
          Swal.showValidationMessage(`Fejl: ${error.message || error}`);
          return false;
        });
      } catch (error) {
        Swal.showValidationMessage(error.message || `${error}`);
        return false;
      }
    }
  });
};

const DepartmentGates = {
  get meta() {
    return {
      title: t$3('objects.department_gates.title'),
      icon: 'fas fa-door-open',
      description: t$3('objects.department_gates.description'),
      endpoint: '/department/gates',
      labels: {
        single: t$3('objects.department_gates.single'),
        multiple: t$3('objects.department_gates.multiple')
      }
    };
  },
  get columns() {
    return {
      id: {
        label: t$3('objects.columns.id'),
        type: 'number',
        sortable: true,
        creation: { required: false }
      },
      department: {
        label: t$3('objects.columns.department'),
        type: 'select',
        sortable: true,
        creation: { required: true },
        options: async () => SessionUser.objects.departments.get.all()
      },
      name: {
        label: t$3('common.name'),
        type: 'string',
        sortable: true,
        creation: { required: true }
      },
      is_entrance: {
        label: t$3('objects.columns.is_entrance'),
        type: 'boolean',
        sortable: true,
        creation: { required: true }
      },
      is_exit: {
        label: t$3('objects.columns.is_exit'),
        type: 'boolean',
        sortable: true,
        creation: { required: true }
      },
      config: {
        label: t$3('objects.columns.config'),
        type: 'string',
        sortable: false,
        creation: { required: true }
      }
    };
  },
  add: async (department, name, is_entrance = false, is_exit = false, config = '{}') => {
    return ObjectsGlobal.add.object(DepartmentGates.meta.endpoint, {
      department: parseInt(department),
      name,
      is_entrance: SessionUser.objects.global.parse.boolean(is_entrance),
      is_exit: SessionUser.objects.global.parse.boolean(is_exit),
      config: parseConfig$1(config)
    });
  },
  update: async (id, payload) => updateDepartmentGate(id, payload),
  set: {
    department: async (id, department) => {
      return ObjectsGlobal.set.column(DepartmentGates.meta.endpoint, id, 'department', parseInt(department));
    },
    name: async (id, name) => {
      return ObjectsGlobal.set.column(DepartmentGates.meta.endpoint, id, 'name', name);
    },
    is_entrance: async (id, is_entrance = false) => {
      return ObjectsGlobal.set.column(
        DepartmentGates.meta.endpoint,
        id,
        'is_entrance',
        SessionUser.objects.global.parse.boolean(is_entrance)
      );
    },
    is_exit: async (id, is_exit = false) => {
      return ObjectsGlobal.set.column(
        DepartmentGates.meta.endpoint,
        id,
        'is_exit',
        SessionUser.objects.global.parse.boolean(is_exit)
      );
    },
    config: async (id, config) => {
      return ObjectsGlobal.set.column(DepartmentGates.meta.endpoint, id, 'config', parseConfig$1(config));
    }
  },
  get: {
    all: async () => ObjectsGlobal.get.objects(DepartmentGates.meta.endpoint),
    single: async (id) => ObjectsGlobal.get.object(DepartmentGates.meta.endpoint, id)
  },
  delete: async (id) => ObjectsGlobal.delete.object(DepartmentGates.meta.endpoint, id),
  functions: {
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(DepartmentGates, id, onAfterSubmit);
    },
    showManageObjectForm: (value = {}, onAfterSubmit = null) => {
      return showManageDepartmentGateForm(value, onAfterSubmit);
    }
  },
  showCreateObjectForm: (onAfterSubmit = null, lockedValues = {}) => {
    return ObjectsGlobal.showCreateObjectForm(DepartmentGates, onAfterSubmit, lockedValues);
  },
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    if (column === 'config') {
      return showEditConfigObjectFieldForm(id, value, onAfterSubmit);
    }

    return ObjectsGlobal.showEditObjectFieldForm(DepartmentGates, id, column, value, onAfterSubmit);
  }
};

const _sfc_main$f = {};
const DepartmentGates_default = /*#__PURE__*/_export_sfc(_sfc_main$f, [['__file',"DepartmentGates.vue"]]);

const t$2 = (key) => i18n.global.t(key);

const parseConfig = (config) => {
  if (config === null || config === undefined || config === '') {
    return {};
  }

  if (typeof config === 'object') {
    return config;
  }

  try {
    return JSON.parse(config);
  } catch (error) {
    return { value: config };
  }
};

const DepartmentRelays = {
  get meta() {
    return {
      title: t$2('objects.department_relays.title'),
      icon: 'fas fa-bolt',
      description: t$2('objects.department_relays.description'),
      endpoint: '/department/relays',
      labels: {
        single: t$2('objects.department_relays.single'),
        multiple: t$2('objects.department_relays.multiple')
      }
    };
  },
  get columns() {
    return {
      id: {
        label: t$2('objects.columns.id'),
        type: 'number',
        sortable: true,
        creation: { required: false }
      },
      department: {
        label: t$2('objects.columns.department'),
        type: 'select',
        sortable: true,
        creation: { required: true },
        options: async () => SessionUser.objects.departments.get.all()
      },
      relay_id: {
        label: t$2('objects.columns.relay_id'),
        type: 'string',
        sortable: true,
        creation: { required: true }
      },
      name: {
        label: t$2('common.name'),
        type: 'string',
        sortable: true,
        creation: { required: true }
      },
      type: {
        label: t$2('objects.columns.type'),
        type: 'string',
        sortable: true,
        creation: { required: true }
      },
      config: {
        label: t$2('objects.columns.config'),
        type: 'string',
        sortable: false,
        creation: { required: true }
      }
    };
  },
  add: async (department, relay_id, name, type, config = '{}') => {
    return ObjectsGlobal.add.object(DepartmentRelays.meta.endpoint, {
      department: parseInt(department),
      relay_id,
      name,
      type,
      config: parseConfig(config)
    });
  },
  set: {
    department: async (id, department) => {
      return ObjectsGlobal.set.column(DepartmentRelays.meta.endpoint, id, 'department', parseInt(department));
    },
    relay_id: async (id, relay_id) => {
      return ObjectsGlobal.set.column(DepartmentRelays.meta.endpoint, id, 'relay_id', relay_id);
    },
    name: async (id, name) => {
      return ObjectsGlobal.set.column(DepartmentRelays.meta.endpoint, id, 'name', name);
    },
    type: async (id, type) => {
      return ObjectsGlobal.set.column(DepartmentRelays.meta.endpoint, id, 'type', type);
    },
    config: async (id, config) => {
      return ObjectsGlobal.set.column(DepartmentRelays.meta.endpoint, id, 'config', parseConfig(config));
    }
  },
  get: {
    all: async () => ObjectsGlobal.get.objects(DepartmentRelays.meta.endpoint),
    single: async (id) => ObjectsGlobal.get.object(DepartmentRelays.meta.endpoint, id)
  },
  delete: async (id) => ObjectsGlobal.delete.object(DepartmentRelays.meta.endpoint, id),
  functions: {
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(DepartmentRelays, id, onAfterSubmit);
    },
  },
  showCreateObjectForm: (onAfterSubmit = null, lockedValues = {}) => {
    return ObjectsGlobal.showCreateObjectForm(DepartmentRelays, onAfterSubmit, lockedValues);
  },
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(DepartmentRelays, id, column, value, onAfterSubmit);
  }
};

const _sfc_main$e = {};
const DepartmentRelays_default = /*#__PURE__*/_export_sfc(_sfc_main$e, [['__file',"DepartmentRelays.vue"]]);

const t$1 = (key) => i18n.global.t(key);
const tf = (key, fallback) => {
  const value = t$1(key);
  return value === key ? fallback : value;
};

const normalizeCompletionSafetySeal = (safetySeal) => {
  if (safetySeal === null || safetySeal === undefined) {
    return null;
  }

  const normalizedSafetySeal = typeof safetySeal === "string"
    ? safetySeal.trim()
    : String(safetySeal).trim();

  if (normalizedSafetySeal === "" || !/^\d+$/.test(normalizedSafetySeal)) {
    return null;
  }

  const parsedSafetySeal = Number(normalizedSafetySeal);
  return Number.isSafeInteger(parsedSafetySeal) && parsedSafetySeal > 0 && parsedSafetySeal <= 999999999
    ? parsedSafetySeal
    : null;
};

/**
 * The OrderBookings object
 */
const OrderBookings = {
  meta: {
    get title() {
      return tf("nav.bookings", "Bookings");
    },
    icon: "fas fa-list",
    get description() {
      const multipleLabel = tf("nav.bookings", "Bookings");
      return `Oversigt over ${String(multipleLabel).toLowerCase()}`;
    },
    endpoint: "/order-bookings",
    labels: {
      get single() {
        return tf("objects.order_bookings.single", "Booking");
      },
      get multiple() {
        return tf("nav.bookings", "Bookings");
      },
      fields: {
        names: {
          customer_number: {
            label: "E-conomic kundenummer",
          },
        },
      },
    },
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    customer_number: {
      label: "Kundenummer",
      type: "number",
      sortable: true,
      creation: {
        required: true
      },
    },
    department: {
      label: "Afdeling",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return SessionUser.objects.department_notification_sms.columns.department.options()
      }
    },
    reg_1: {
      label: "Reg. 1",
      type: "string",
      sortable: true,
      creation: {
        required: true
      },
    },
    reg_2: {
      label: "Reg. 2",
      type: "string",
      sortable: true,
      creation: {
        required: true
      },
    },
    reg_3: {
      label: "Reg. 3",
      type: "string",
      sortable: true,
      creation: {
        required: true
      },
    },
    datetime: {
      label: "Dato",
      type: "datetime",
      sortable: true,
      creation: {
        required: true
      },
    },
    note: {
      label: "Notat",
      type: "string",
      sortable: true,
      creation: {
        required: false
      },
    },
    reference: {
      label: "Reference",
      type: "string",
      sortable: true,
      creation: {
        required: false
      },
    },
    po: {
      label: "PO Nummer",
      type: "string",
      sortable: true,
      creation: {
        required: false
      },
    },
    pickup: {
      label: "Hentning",
      type: "boolean",
      sortable: true,
      creation: {
        required: false
      },
    },
    items: {
      label: "Varer",
      type: "array",
      sortable: false,
      creation: {
        required: false
      },
    },
    order_id: {
      label: "Order",
      type: "select",
      sortable: true,
      creation: {
        required: false
      },
      options: async (options = { filters: {
          //customer_id: 12345679,
          //department_id: 2
        }, pagination: { limit: 10, page: 1, order: 'id:DESC' } }) => {
        return SessionUser.objects.orders.get.list(options).then((orders) => {
          return [
              { id: null, name: "Ingen" },
              ...orders.map((order) => {
                return {
                  ...order,
                  name: `#${order.id} - ${getDepartmentName(order.department_id)} - ${order.created_at}`
                };
              })
          ];
        });
      }
    },
    /**
     *     status: {
     *       label: "Status",
     *       type: "select",
     *       sortable: true,
     *       creation: {
     *         required: false
     *       },
     *       options: async () => {
     *         return [
     *           { id: 'pending', name: "Afventer" },
     *           { id: 'cancelled', name: "Annulleret" },
     *           { id: 'completed', name: "Færdig" },
     *         ];
     *       }
     *     },
     */
    created_at: {
      label: "Oprettet",
      type: "string",
      sortable: true,
      creation: {
        required: false
      },
    },
    deleted_at: {
      label: "Slettet",
      type: "string",
      sortable: true,
      creation: {
        required: false
      },
    },
  },
  add: async (customer_number, department, reg_1, reg_2 = null, reg_3 = null, datetime, note = null, reference = null, po = null, pickup = false, items = []) => {
    return ObjectsGlobal.add.object(
        OrderBookings.meta.endpoint,
        {
          customer_number: parseInt(customer_number),
          department: parseInt(department),
          reg_1,
          reg_2,
          reg_3,
          datetime,
          note,
          reference,
          po,
          pickup,
          items,
        },
        {authenticated: SessionUser.functions.hasToken()}
    );
  },
  set: {
    customer_number: async (id, customer_number) => {
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "customer_number",
          parseInt(customer_number)
      )
    },
    department: async (id, department) => {
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "department",
          parseInt(department)
      )
    },
    reg_1: async (id, reg_1) => {
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "reg_1",
          reg_1
      )
    },
    reg_2: async (id, reg_2) => {
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "reg_2",
          reg_2
      )
    },
    reg_3: async (id, reg_3) => {
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "reg_3",
          reg_3
      )
    },
    datetime: async (id, datetime) => {
      // Input format: 2025-11-05T13:00
      // Output format: 2025-11-05 13:00:00
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "datetime",
          datetime.replace("T", " ") + ":00"
      )
    },
    note: async (id, note) => {
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "note",
          note
      )
    },
    reference: async (id, reference) => {
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "reference",
          reference
      )
    },
    po: async (id, po) => {
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "po",
          po
      )
    },
    pickup: async (id, pickup) => {
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "pickup",
          pickup === true || pickup === 1 || pickup === "1" || pickup === "true"
      )
    },
    items: async (id, items) => {
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "items",
          items
      )
    },
    order_id: async (id, order_id) => {
      return ObjectsGlobal.set.column(
          OrderBookings.meta.endpoint,
          id,
          "order_id",
          order_id ? parseInt(order_id) : null
      )
    },
  },
  get: {
    single: async (identifier) => {
      return ObjectsGlobal.get.object(OrderBookings.meta.endpoint, identifier, {authenticated: SessionUser.functions.hasToken()});
    },
    all: async (queryParams = {}) => {
      return ObjectsGlobal.get.objects(OrderBookings.meta.endpoint, queryParams, {authenticated: SessionUser.functions.hasToken()});
    },
    list: async (optionsObject = {filters: {}, pagination: {page: 1, limit: 100}, search: ''}) => {
      return ObjectsGlobal.get.list(OrderBookings.meta.endpoint, optionsObject);
    },
  },
  delete: {
    single: async (id) => {
      return ObjectsGlobal.delete.object(
          OrderBookings.meta.endpoint,
          id,
          { authenticated: SessionUser.functions.hasToken() }
      );
    }
  },
  functions: {
    showDeleteConfirmationModal: async (id, onAfterDelete = null) => {
      return ObjectsGlobal.showDeleteConfirmationModal(
          OrderBookings,
          id,
          onAfterDelete
      );
    },
    complete: async (id, safetySeal = null, onAfterComplete = null) => {
      return ObjectsGlobal.performAction(
          OrderBookings.meta.endpoint,
          id,
          "complete",
          { safety_seal: normalizeCompletionSafetySeal(safetySeal) },
          onAfterComplete
      );
    },
    resendBookingConfirmation: async (id) => {
      return SessionUser.request(
          OrderBookings.meta.endpoint + "/booking-confirmation/resend",
          "POST",
          { id: parseInt(id, 10) }
      ).then((response) => response.data.data);
    },
    resendBookingCompletionConfirmation: async (id) => {
      return SessionUser.request(
          OrderBookings.meta.endpoint + "/completion-confirmation/resend",
          "POST",
          { id: parseInt(id, 10) }
      ).then((response) => response.data.data);
    }
  },
  /**
   * Show the create object form
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(OrderBookings, onAfterSubmit);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @param options
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null, options = { filters: {}, pagination: { limit: 10, page: 1 } }) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        OrderBookings,
        id,
        column,
        value,
        onAfterSubmit,
        options
    );
  }
};

const _sfc_main$d = {};
const OrderBookings_default = /*#__PURE__*/_export_sfc(_sfc_main$d, [['__file',"OrderBookings.vue"]]);

/**
 * The Module Action Logs object
 */
const ModuleActionLogs = {
  meta: {
    title: "Modul handlingslogs",
    icon: "fas fa-history",
    description: "Oversigt over modul handlingslogs",
    endpoint: "/modules/action-logs",
    labels: {
      single: "handlingslog",
      multiple: "handlingslogs"
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
    },
    module: {
      label: "Modul",
      type: "string",
      sortable: true,
    },
    action: {
      label: "Handling",
      type: "string",
      sortable: true,
    },
    status_code: {
      label: "Statuskode",
      type: "number",
      sortable: true,
    },
    data: {
      label: "Data",
      type: "object",
      sortable: false,
    },
    created_at: {
      label: "Oprettet",
      type: "datetime",
      sortable: true,
    }
  },
  get: {
    all: async (filters = {}, pagination = { page: 1, limit: 10, order: 'id:DESC' }) => {
      return ObjectsGlobal.get.list(ModuleActionLogs.meta.endpoint, {
        filters: filters,
        pagination: pagination
      });
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(ModuleActionLogs.meta.endpoint, id);
    }
  }
};

const _sfc_main$c = {};
const ModuleActionLogs_default = /*#__PURE__*/_export_sfc(_sfc_main$c, [['__file',"ModuleActionLogs.vue"]]);

const SELF_SERVE_TASK_BUTTON_RESET = "reset";
const SELF_SERVE_TASK_BUTTON_START = "start";
const SELF_SERVE_TASK_BUTTON_PROGRAM_PICKER = "program_picker";

const SELF_SERVE_TASK_BUTTON_OPTIONS = [
  {
    id: SELF_SERVE_TASK_BUTTON_RESET,
    name: "Reset",
    description: "Reset button",
  },
  {
    id: SELF_SERVE_TASK_BUTTON_PROGRAM_PICKER,
    name: "Program picker",
    description: "Program picker wheel",
  },
  ...Array.from({ length: 12 }, (_, index) => ({
    id: index,
    name: `Program ${index + 1}`,
    description: `Machine button ${index}`,
  })),
  {
    id: SELF_SERVE_TASK_BUTTON_START,
    name: "Start",
    description: "Start button",
  },
];

const KNOWN_SPECIAL_BUTTONS = new Set([
  SELF_SERVE_TASK_BUTTON_RESET,
  SELF_SERVE_TASK_BUTTON_START,
  SELF_SERVE_TASK_BUTTON_PROGRAM_PICKER,
]);

const BUTTON_LABELS = new Map(
  SELF_SERVE_TASK_BUTTON_OPTIONS.map((option) => [String(option.id), option.name])
);

const normalizeListInput = (value) => {
  if (Array.isArray(value)) {
    return value;
  }

  if (typeof value === "string") {
    const trimmed = value.trim();
    if (!trimmed) {
      return [];
    }

    try {
      const parsed = JSON.parse(trimmed);
      if (Array.isArray(parsed)) {
        return normalizeListInput(parsed);
      }
    } catch {
      // Comma-separated values are accepted for quick manual edits.
    }

    return trimmed.split(",").map((entry) => entry.trim()).filter(Boolean);
  }

  return [];
};

const normalizeSelfServeTaskButton = (value) => {
  if (value === null || value === undefined) {
    return null;
  }

  const text = String(value).trim();
  if (!text) {
    return null;
  }

  const lowerText = text.toLowerCase();
  if (KNOWN_SPECIAL_BUTTONS.has(lowerText)) {
    return lowerText;
  }

  const parsed = Number(text);
  if (!Number.isInteger(parsed) || parsed < 0 || parsed > 11) {
    return null;
  }

  return parsed;
};

const normalizeSelfServeTaskButtons = (value) => {
  const normalized = [];
  const seen = new Set();

  for (const entry of normalizeListInput(value)) {
    const button = normalizeSelfServeTaskButton(entry);
    if (button === null) {
      continue;
    }

    const key = `${typeof button}:${button}`;
    if (seen.has(key)) {
      continue;
    }

    seen.add(key);
    normalized.push(button);
  }

  return normalized;
};

const formatSelfServeTaskButton = (button) => {
  const normalized = normalizeSelfServeTaskButton(button);
  if (normalized === null) {
    return null;
  }

  return BUTTON_LABELS.get(String(normalized)) || `Button ${normalized}`;
};

const formatSelfServeTaskButtons = (buttons, emptyLabel = "Ingen") => {
  const labels = normalizeSelfServeTaskButtons(buttons)
    .map(formatSelfServeTaskButton)
    .filter(Boolean);

  return labels.length > 0 ? labels.join(", ") : emptyLabel;
};

const escapeHtml$1 = (value = "") => String(value)
  .replaceAll("&", "&amp;")
  .replaceAll("<", "&lt;")
  .replaceAll(">", "&gt;")
  .replaceAll("\"", "&quot;");

const parseNullableInt = (value, fallback = null) => {
  if (value === null || typeof value === "undefined" || value === "") {
    return fallback;
  }

  const parsed = Number.parseInt(value, 10);
  return Number.isNaN(parsed) ? fallback : parsed;
};

const parseIntOrZero$1 = (value) => {
  const parsed = Number.parseInt(value, 10);
  return Number.isNaN(parsed) ? 0 : parsed;
};

const parseNullablePositiveInt$1 = (value, fallback = null) => {
  const parsed = parseNullableInt(value, fallback);
  return parsed && parsed > 0 ? parsed : fallback;
};

const buildOptionHtml = (options, selectedValue = null) =>
  options.map((option) => {
    const optionValue = option?.id ?? "";
    const isSelected = String(optionValue) === String(selectedValue ?? "");
    return `<option value="${escapeHtml$1(optionValue)}" ${isSelected ? "selected" : ""}>${escapeHtml$1(option?.name ?? optionValue)}</option>`;
  }).join("");

const getFieldValue = (id) => document.getElementById(id)?.value ?? "";
const setFieldValue = (id, value) => {
  const element = document.getElementById(id);
  if (element) {
    element.value = value ?? "";
  }
};

const setFieldDisplay = (wrapperId, visible) => {
  const element = document.getElementById(wrapperId);
  if (element) {
    element.style.display = visible ? "block" : "none";
  }
};

const populateSelect = (id, options, selectedValue = null) => {
  const element = document.getElementById(id);
  if (!element) {
    return;
  }
  element.innerHTML = buildOptionHtml(options, selectedValue);
};

const getCheckedValues = (name) => Array.from(document.querySelectorAll(`input[name="${name}"]:checked`))
  .map((element) => element.value);

const wrapField = (id, label, innerHtml, visible = true) => `
  <div class="field" id="${id}-wrapper" style="display: ${visible ? "block" : "none"}">
    <label class="label has-text-black">${escapeHtml$1(label)}</label>
    <div class="control">${innerHtml}</div>
  </div>
`;

const buildInput = (id, value = "", type = "text", min = null) =>
  `<input class="input has-background-light has-text-black" type="${type}" id="${id}" value="${escapeHtml$1(value)}" ${min !== null ? `min="${min}"` : ""}>`;

const buildSelect = (id, options, selectedValue = null) =>
  `<div class="select is-fullwidth"><select id="${id}" class="has-background-light has-text-black">${buildOptionHtml(options, selectedValue)}</select></div>`;

const buildCheckboxList = (name, options, selectedValues = []) => options.map((option) => {
  const checked = selectedValues.includes(String(option.id)) || selectedValues.includes(option.id);
  return `
    <label class="checkbox is-block has-text-black" style="margin-bottom: 0.5rem;">
      <input type="checkbox" name="${name}" value="${escapeHtml$1(option.id)}" ${checked ? "checked" : ""}>
      ${escapeHtml$1(option.name ?? option.id)}
    </label>
  `;
}).join("");

const showValidationMessage = (message) => {
  Swal.showValidationMessage(message);
  return false;
};

const saveRecord = async (endpoint, payload, recordId = null) => {
  if (recordId) {
    await authenticatedRequest(endpoint, "PUT", { id: recordId, ...payload });
    return;
  }
  await authenticatedRequest(endpoint, "POST", payload);
};

const questionScopeModeFor = (record, initialData = {}) => {
  const department = parseIntOrZero$1(record?.department ?? initialData.department);
  const lane = parseIntOrZero$1(record?.lane ?? initialData.lane);
  const product = parseIntOrZero$1(record?.product ?? initialData.product);
  return department === 0 && lane === 0 && product === 0 ? "shared" : "legacy";
};

const scopedModeFor = (record, initialData = {}) => {
  const machineTypeId = parseNullableInt(record?.machine_type_id ?? initialData.machine_type_id);
  return machineTypeId ? "machine_type" : "legacy";
};

const showSelfServeQuestionForm = async ({ object, record = null, initialData = {}, onAfterSubmit = null }) => {
  const products = await SessionUser.objects.products.get.all();
  const scopeMode = questionScopeModeFor(record, initialData);
  const initialDepartment = parseIntOrZero$1(record?.department ?? initialData.department);
  const initialLane = parseIntOrZero$1(record?.lane ?? initialData.lane);
  const initialProduct = parseIntOrZero$1(record?.product ?? initialData.product);
  const initialConditionId = parseNullableInt(record?.condition_id ?? initialData.condition_id, 0);
  const initialOrderPriority = parseIntOrZero$1(record?.order_priority ?? initialData.order_priority);

  const html = [
    wrapField("scope_mode", "Scope", buildSelect("scope_mode", [
      { id: "shared", name: "Fælles" },
      { id: "legacy", name: "Afdeling / bane / køretøjstype" },
    ], scopeMode)),
    wrapField("department", "Afdeling", buildInput("department", initialDepartment, "number", 0), scopeMode === "legacy"),
    wrapField("lane", "Bane", buildInput("lane", initialLane, "number", 0), scopeMode === "legacy"),
    wrapField("product", "Køretøjstype", buildSelect("product", [{ id: 0, name: "Ingen" }, ...products], initialProduct), scopeMode === "legacy"),
    wrapField("condition_id", "Betingelse (Hvis)", buildSelect("condition_id", [{ id: 0, name: "Ingen" }], initialConditionId)),
    wrapField("question", "Spørgsmål", buildInput("question", record?.question ?? initialData.question ?? "")),
    wrapField("description", "Beskrivelse", buildInput("description", record?.description ?? initialData.description ?? "")),
    wrapField("order_priority", "Rækkefølge", buildInput("order_priority", initialOrderPriority, "number", 0)),
  ].join("");

  return Swal.fire({
    title: record ? `Rediger ${object.meta.labels.single}` : `Opret ${object.meta.labels.single}`,
    html,
    showCancelButton: true,
    confirmButtonText: SessionUser.objects.global.language.save,
    cancelButtonText: SessionUser.objects.global.language.cancel,
    didOpen: async () => {
      const updateScopeVisibility = () => {
        const isLegacy = getFieldValue("scope_mode") === "legacy";
        setFieldDisplay("department-wrapper", isLegacy);
        setFieldDisplay("lane-wrapper", isLegacy);
        setFieldDisplay("product-wrapper", isLegacy);
      };

      const updateConditionOptions = async () => {
        const isLegacy = getFieldValue("scope_mode") === "legacy";
        const options = await object.columns.condition_id.options({
          department: isLegacy ? getFieldValue("department") : 0,
          product: isLegacy ? getFieldValue("product") : 0,
        });
        populateSelect("condition_id", options, getFieldValue("condition_id") || initialConditionId || 0);
      };

      document.getElementById("scope_mode")?.addEventListener("change", async () => {
        updateScopeVisibility();
        await updateConditionOptions();
      });
      document.getElementById("department")?.addEventListener("change", updateConditionOptions);
      document.getElementById("product")?.addEventListener("change", updateConditionOptions);

      updateScopeVisibility();
      await updateConditionOptions();
    },
    preConfirm: async () => {
      const payload = {
        question: getFieldValue("question").trim(),
        description: getFieldValue("description").trim(),
        order_priority: parseIntOrZero$1(getFieldValue("order_priority")),
        condition_id: parseNullableInt(getFieldValue("condition_id")),
      };

      if (!payload.question) {
        return showValidationMessage("Spørgsmål er påkrævet.");
      }

      if (!payload.description) {
        return showValidationMessage("Beskrivelse er påkrævet.");
      }

      if (getFieldValue("scope_mode") === "legacy") {
        payload.department = parseIntOrZero$1(getFieldValue("department"));
        payload.lane = parseIntOrZero$1(getFieldValue("lane"));
        payload.product = parseIntOrZero$1(getFieldValue("product"));
      } else {
        payload.department = 0;
        payload.lane = 0;
        payload.product = 0;
      }

      try {
        await saveRecord(object.meta.endpoint, payload, record?.id);
        if (onAfterSubmit) {
          await onAfterSubmit();
        }
      } catch (error) {
        return showValidationMessage(error?.response?.data?.message || error?.message || "Kunne ikke gemme spørgsmålet.");
      }
    }
  });
};

const showSelfServeConditionForm = async ({ object, record = null, initialData = {}, onAfterSubmit = null }) => {
  const products = await SessionUser.objects.products.get.all();
  const machineTypes = await SessionUser.objects.self_serve_machine_types.get.all();
  const scopeMode = scopedModeFor(record, initialData);
  const initialDepartment = parseIntOrZero$1(record?.department ?? initialData.department);
  const initialLane = parseIntOrZero$1(record?.lane ?? initialData.lane);
  const initialProduct = parseIntOrZero$1(record?.product ?? initialData.product);
  const initialMachineTypeId = parseNullableInt(record?.machine_type_id ?? initialData.machine_type_id, 0);
  const initialConditionId = parseNullableInt(record?.condition_id ?? initialData.condition_id, 0);

  const html = [
    wrapField("scope_mode", "Scope", buildSelect("scope_mode", [
      { id: "machine_type", name: "Maskintype" },
      { id: "legacy", name: "Afdeling / bane / køretøjstype" },
    ], scopeMode)),
    wrapField("machine_type_id", "Maskintype", buildSelect("machine_type_id", [{ id: 0, name: "Vælg maskintype" }, ...machineTypes], initialMachineTypeId), scopeMode === "machine_type"),
    wrapField("department", "Afdeling", buildInput("department", initialDepartment, "number", 0), scopeMode === "legacy"),
    wrapField("lane", "Bane", buildInput("lane", initialLane, "number", 0), scopeMode === "legacy"),
    wrapField("product", "Køretøjstype", buildSelect("product", [{ id: 0, name: "Ingen" }, ...products], initialProduct), scopeMode === "legacy"),
    wrapField("condition_id", "Overordnet betingelse", buildSelect("condition_id", [{ id: 0, name: "Ingen" }], initialConditionId)),
    wrapField("name", "Navn", buildInput("name", record?.name ?? initialData.name ?? "")),
    wrapField("description", "Beskrivelse", buildInput("description", record?.description ?? initialData.description ?? "")),
  ].join("");

  return Swal.fire({
    title: record ? `Rediger ${object.meta.labels.single}` : `Opret ${object.meta.labels.single}`,
    html,
    showCancelButton: true,
    confirmButtonText: SessionUser.objects.global.language.save,
    cancelButtonText: SessionUser.objects.global.language.cancel,
    didOpen: async () => {
      const updateScopeVisibility = () => {
        const isMachineType = getFieldValue("scope_mode") === "machine_type";
        setFieldDisplay("machine_type_id-wrapper", isMachineType);
        setFieldDisplay("department-wrapper", !isMachineType);
        setFieldDisplay("lane-wrapper", !isMachineType);
        setFieldDisplay("product-wrapper", !isMachineType);
      };

      const updateConditionOptions = async () => {
        const isMachineType = getFieldValue("scope_mode") === "machine_type";
        const options = await object.columns.condition_id.options({
          department: isMachineType ? 0 : getFieldValue("department"),
          product: isMachineType ? 0 : getFieldValue("product"),
          machine_type_id: isMachineType ? getFieldValue("machine_type_id") : null,
        });
        populateSelect("condition_id", options, getFieldValue("condition_id") || initialConditionId || 0);
      };

      document.getElementById("scope_mode")?.addEventListener("change", async () => {
        updateScopeVisibility();
        await updateConditionOptions();
      });
      document.getElementById("machine_type_id")?.addEventListener("change", updateConditionOptions);
      document.getElementById("department")?.addEventListener("change", updateConditionOptions);
      document.getElementById("product")?.addEventListener("change", updateConditionOptions);

      updateScopeVisibility();
      await updateConditionOptions();
    },
    preConfirm: async () => {
      const payload = {
        name: getFieldValue("name").trim(),
        description: getFieldValue("description").trim(),
        condition_id: parseNullableInt(getFieldValue("condition_id")),
      };

      if (!payload.name) {
        return showValidationMessage("Navn er påkrævet.");
      }

      if (!payload.description) {
        return showValidationMessage("Beskrivelse er påkrævet.");
      }

      if (getFieldValue("scope_mode") === "machine_type") {
        payload.machine_type_id = parseNullableInt(getFieldValue("machine_type_id"));
        payload.department = 0;
        payload.lane = 0;
        payload.product = 0;

        if (!payload.machine_type_id) {
          return showValidationMessage("Maskintype er påkrævet for denne scope.");
        }
      } else {
        payload.machine_type_id = null;
        payload.department = parseIntOrZero$1(getFieldValue("department"));
        payload.lane = parseIntOrZero$1(getFieldValue("lane"));
        payload.product = parseIntOrZero$1(getFieldValue("product"));
      }

      try {
        await saveRecord(object.meta.endpoint, payload, record?.id);
        if (onAfterSubmit) {
          await onAfterSubmit();
        }
      } catch (error) {
        return showValidationMessage(error?.response?.data?.message || error?.message || "Kunne ikke gemme betingelsen.");
      }
    }
  });
};

const showSelfServeTaskForm = async ({ object, record = null, initialData = {}, onAfterSubmit = null }) => {
  const products = await SessionUser.objects.products.get.all();
  const machineTypes = await SessionUser.objects.self_serve_machine_types.get.all();
  const scopeMode = scopedModeFor(record, initialData);
  const initialDepartment = parseIntOrZero$1(record?.department ?? initialData.department);
  const initialLane = parseIntOrZero$1(record?.lane ?? initialData.lane);
  const initialProduct = parseIntOrZero$1(record?.product ?? initialData.product);
  const initialMachineTypeId = parseNullableInt(record?.machine_type_id ?? initialData.machine_type_id, 0);
  const initialConditionId = parseNullableInt(record?.condition_id ?? initialData.condition_id, 0);
  const initialOrderPriority = parseIntOrZero$1(record?.order_priority ?? initialData.order_priority);

  const html = [
    wrapField("scope_mode", "Scope", buildSelect("scope_mode", [
      { id: "machine_type", name: "Maskintype" },
      { id: "legacy", name: "Afdeling / bane / køretøjstype" },
    ], scopeMode)),
    wrapField("machine_type_id", "Maskintype", buildSelect("machine_type_id", [{ id: 0, name: "Vælg maskintype" }, ...machineTypes], initialMachineTypeId), scopeMode === "machine_type"),
    wrapField("department", "Afdeling", buildInput("department", initialDepartment, "number", 0), scopeMode === "legacy"),
    wrapField("lane", "Bane", buildInput("lane", initialLane, "number", 0), scopeMode === "legacy"),
    wrapField("product", "Køretøjstype", buildSelect("product", [{ id: 0, name: "Ingen" }, ...products], initialProduct), scopeMode === "legacy"),
    wrapField("condition_id", "Hvis", buildSelect("condition_id", [{ id: 0, name: "Altid" }], initialConditionId)),
    wrapField("task", "Opgave", buildInput("task", record?.task ?? initialData.task ?? "")),
    wrapField("description", "Beskrivelse", buildInput("description", record?.description ?? initialData.description ?? "")),
    wrapField("order_priority", "Rækkefølge", buildInput("order_priority", initialOrderPriority, "number", 0)),
    wrapField("services", "Tjenester", buildCheckboxList("services", [
      { id: "MACHINE", name: "MACHINE" }
    ], record?.services ?? initialData.services ?? [])),
    wrapField("buttons", "Knapper", buildCheckboxList(
      "buttons",
      SELF_SERVE_TASK_BUTTON_OPTIONS,
      (record?.buttons ?? initialData.buttons ?? []).map(String)
    )),
    wrapField("dynamic_images_vehicle_type", "Køretøjstype (maskine UI)", buildSelect(
      "dynamic_images_vehicle_type",
      [{ id: "", name: "Ingen" }, ...products],
      record?.dynamic_images_vehicle_type ?? initialData.dynamic_images_vehicle_type ?? ""
    )),
  ].join("");

  return Swal.fire({
    title: record ? `Rediger ${object.meta.labels.single}` : `Opret ${object.meta.labels.single}`,
    html,
    showCancelButton: true,
    confirmButtonText: SessionUser.objects.global.language.save,
    cancelButtonText: SessionUser.objects.global.language.cancel,
    didOpen: async () => {
      const updateScopeVisibility = () => {
        const isMachineType = getFieldValue("scope_mode") === "machine_type";
        setFieldDisplay("machine_type_id-wrapper", isMachineType);
        setFieldDisplay("department-wrapper", !isMachineType);
        setFieldDisplay("lane-wrapper", !isMachineType);
        setFieldDisplay("product-wrapper", !isMachineType);
      };

      const updateConditionOptions = async () => {
        const isMachineType = getFieldValue("scope_mode") === "machine_type";
        const options = await object.columns.condition_id.options({
          department: isMachineType ? 0 : getFieldValue("department"),
          product: isMachineType ? 0 : getFieldValue("product"),
          machine_type_id: isMachineType ? getFieldValue("machine_type_id") : null,
        });
        populateSelect("condition_id", options, getFieldValue("condition_id") || initialConditionId || 0);
      };

      document.getElementById("scope_mode")?.addEventListener("change", async () => {
        updateScopeVisibility();
        await updateConditionOptions();
      });
      document.getElementById("machine_type_id")?.addEventListener("change", updateConditionOptions);
      document.getElementById("department")?.addEventListener("change", updateConditionOptions);
      document.getElementById("product")?.addEventListener("change", updateConditionOptions);

      updateScopeVisibility();
      await updateConditionOptions();
    },
    preConfirm: async () => {
      const selectedConditionId = parseNullablePositiveInt$1(getFieldValue("condition_id"));
      const payload = {
        task: getFieldValue("task").trim(),
        description: getFieldValue("description").trim(),
        order_priority: parseIntOrZero$1(getFieldValue("order_priority")),
        condition_id: selectedConditionId,
        gate_type: selectedConditionId ? "CONDITION" : "ALWAYS",
        gate_ref_id: selectedConditionId,
        services: getCheckedValues("services"),
        buttons: normalizeSelfServeTaskButtons(getCheckedValues("buttons")),
        dynamic_images_vehicle_type: parseNullableInt(getFieldValue("dynamic_images_vehicle_type")),
      };

      if (!payload.task) {
        return showValidationMessage("Opgave er påkrævet.");
      }

      if (!payload.description) {
        return showValidationMessage("Beskrivelse er påkrævet.");
      }

      if (getFieldValue("scope_mode") === "machine_type") {
        payload.machine_type_id = parseNullableInt(getFieldValue("machine_type_id"));
        payload.department = 0;
        payload.lane = 0;
        payload.product = 0;

        if (!payload.machine_type_id) {
          return showValidationMessage("Maskintype er påkrævet for denne scope.");
        }
      } else {
        payload.machine_type_id = null;
        payload.department = parseIntOrZero$1(getFieldValue("department"));
        payload.lane = parseIntOrZero$1(getFieldValue("lane"));
        payload.product = parseIntOrZero$1(getFieldValue("product"));
      }

      try {
        await saveRecord(object.meta.endpoint, payload, record?.id);
        if (onAfterSubmit) {
          await onAfterSubmit();
        }
      } catch (error) {
        return showValidationMessage(error?.response?.data?.message || error?.message || "Kunne ikke gemme opgaven.");
      }
    }
  });
};

/**
 * Local questions cache
 * @type {ref<null>}
 */
const questions_cache = ref(null);

/**
 * Get the question text
 * @param id
 * @param fallback
 * @returns {string}
 */
const getQuestionText = (id, fallback = null) => {
  if (questions_cache.value === null) {
    questions_cache.value = [];
    SessionUser.objects.self_serve_questions.get.all().then((questions) => {
      questions_cache.value = questions;
    });
  }
  const question = questions_cache.value.find((question) => question.id === parseInt(id));
  return question ? question.question : fallback === null ? SessionUser.objects.global.language.no_data : fallback;
};

const normalizePayload$3 = (payload) => ({
  department: parseInt(payload.department || 0),
  lane: parseInt(payload.lane || 0),
  product: parseInt(payload.product || 0),
  question: payload.question,
  description: payload.description,
  condition_id: payload.condition_id && parseInt(payload.condition_id) !== 0 ? parseInt(payload.condition_id) : null,
  order_priority: parseInt(payload.order_priority || 0),
});

const buildScopedQuestionName = async (question) => {
  const [departments, products] = await Promise.all([
    SessionUser.objects.departments.get.all(),
    SessionUser.objects.products.get.all()
  ]);

  const departmentName = departments.find(d => parseInt(d.id) === parseInt(question.department))?.name || question.department;
  const productName = products.find(p => parseInt(p.id) === parseInt(question.product))?.name || question.product;

  return `${departmentName}-${question.lane}-${productName}: ${question.question}`;
};

/**
 * The SelfServeQuestions object
 */
const SelfServeQuestions = {
  meta: {
    title: "Selvbetjeningsspørgsmål",
    icon: "fas fa-question-circle",
    description: "Oversigt over selvbetjeningsspørgsmål",
    endpoint: "/department/selfserve/questions",
    labels: {
      single: "spørgsmål",
      multiple: "spørgsmål"
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    department: {
      label: "Afdeling",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    lane: {
      label: "Bane",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    product: {
      label: "Køretøjstype",
      type: "select",
      sortable: true,
      creation: {
        required: false
      },
      options: async (lockedValues = {}) => {
        const products = await SessionUser.objects.products.get.all();
        if (lockedValues && lockedValues.vehicle_type) {
          return products.filter(p => parseInt(p.id) === parseInt(lockedValues.vehicle_type));
        }
        return products;
      }
    },
    question: {
      label: "Spørgsmål",
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
    description: {
      label: "Beskrivelse",
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
    condition_id: {
      label: "Betingelse (Hvis)",
      type: "select",
      sortable: true,
      creation: {
        required: false
      },
      options: async (lockedValues = {}) => {
        let conditions = await SessionUser.objects.self_serve_conditions.get.all();
        const departmentId = lockedValues.department || lockedValues.department_id;
        const productId = lockedValues.product || lockedValues.vehicle_type || lockedValues.product_id;

        conditions = conditions.filter(c => !c.machine_type_id);

        if (departmentId) {
          conditions = conditions.filter(c => parseInt(c.department || 0) === parseInt(departmentId));
        }

        if (productId) {
          conditions = conditions.filter(c => parseInt(c.product || 0) === parseInt(productId));
        }

        const options = await Promise.all(conditions.map(async (condition) => ({
          ...condition,
          name: await SessionUser.objects.self_serve_conditions.functions.formatConditionName(condition.id)
        })));

        options.unshift({
          id: 0,
          name: "Ingen"
        });

        return options;
      },
      parse: (id) => {
        return SessionUser.objects.self_serve_conditions.functions.getConditionName(id);
      }
    },
    order_priority: {
      label: "Rækkefølge",
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
  },
  add: async (departmentOrPayload, lane, product, question, description, condition_id, order_priority) => {
    const payload = typeof departmentOrPayload === "object"
      ? normalizePayload$3(departmentOrPayload)
      : normalizePayload$3({
          department: departmentOrPayload,
          lane,
          product,
          question,
          description,
          condition_id,
          order_priority,
        });

    return ObjectsGlobal.add.object(SelfServeQuestions.meta.endpoint, payload);
  },
  set: {
    question: async (id, question) => {
      return ObjectsGlobal.set.column(SelfServeQuestions.meta.endpoint, id, "question", question);
    },
    description: async (id, description) => {
      return ObjectsGlobal.set.column(SelfServeQuestions.meta.endpoint, id, "description", description);
    },
    order_priority: async (id, order_priority) => {
      return ObjectsGlobal.set.column(SelfServeQuestions.meta.endpoint, id, "order_priority", parseInt(order_priority || 0));
    },
    condition_id: async (id, condition_id) => {
      return ObjectsGlobal.set.column(
        SelfServeQuestions.meta.endpoint,
        id,
        "condition_id",
        (condition_id && parseInt(condition_id) !== 0) ? parseInt(condition_id) : null
      );
    },
    product: async (id, product) => {
      return ObjectsGlobal.set.column(SelfServeQuestions.meta.endpoint, id, "product", parseInt(product || 0));
    },
    lane: async (id, lane) => {
      return ObjectsGlobal.set.column(SelfServeQuestions.meta.endpoint, id, "lane", parseInt(lane || 0));
    },
    department: async (id, department) => {
      return ObjectsGlobal.set.column(SelfServeQuestions.meta.endpoint, id, "department", parseInt(department || 0));
    },
  },
  get: {
    all: async (filters = {}) => {
      return ObjectsGlobal.get.objects(SelfServeQuestions.meta.endpoint, filters);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(SelfServeQuestions.meta.endpoint, id);
    }
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(SelfServeQuestions.meta.endpoint, id);
  },
  functions: {
    getQuestionText: getQuestionText,
    formatQuestionName: async (questionId) => {
      const questions = await SessionUser.objects.self_serve_questions.get.all();
      const question = questions.find(q => parseInt(q.id) === parseInt(questionId));
      if (!question) return SessionUser.objects.global.language.no_data;

      return buildScopedQuestionName(question);
    },
    getScopeLabel: async (question) => {
      if (
        parseInt(question.department || 0) === 0
        && parseInt(question.lane || 0) === 0
        && parseInt(question.product || 0) === 0
      ) {
        return "Fælles";
      }

      return `Afdeling ${question.department || 0} / Bane ${question.lane || 0} / Køretøjstype ${question.product || 0}`;
    },
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(SelfServeQuestions, id, onAfterSubmit);
    },
  },
  showCreateObjectForm: (initialData = {}, onAfterSubmit = null) => {
    return showSelfServeQuestionForm({
      object: SelfServeQuestions,
      initialData,
      onAfterSubmit,
    });
  },
  showEditObjectForm: (record, onAfterSubmit = null) => {
    return showSelfServeQuestionForm({
      object: SelfServeQuestions,
      record,
      onAfterSubmit,
    });
  },
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null, options = {}) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        SelfServeQuestions,
        id,
        column,
        value,
        onAfterSubmit,
        options
    );
  }
};

const _sfc_main$b = {};
const SelfServeQuestions_default = /*#__PURE__*/_export_sfc(_sfc_main$b, [['__file',"SelfServeQuestions.vue"]]);

/**
 * Local tasks cache
 * @type {ref<null>}
 */
const tasks_cache = ref(null);

/**
 * Get the task text
 * @param id
 * @param fallback
 * @returns {string}
 */
const getTaskText = (id, fallback = null) => {
  if (tasks_cache.value === null) {
    tasks_cache.value = [];
    SessionUser.objects.self_serve_tasks.get.all().then((tasks) => {
      tasks_cache.value = tasks;
    });
  }
  const task = tasks_cache.value.find((task) => task.id === parseInt(id));
  return task ? task.task : fallback === null ? SessionUser.objects.global.language.no_data : fallback;
};

const buildScopedTaskName = async (task) => {
  if (!task) {
    return SessionUser.objects.global.language.no_data;
  }

  if (task.machine_type_id) {
    const machineTypeName = await SessionUser.objects.self_serve_machine_types.functions.getMachineTypeName(task.machine_type_id);
    return `[Maskintype] ${machineTypeName}: ${task.task}`;
  }

  const [departments, products] = await Promise.all([
    SessionUser.objects.departments.get.all(),
    SessionUser.objects.products.get.all()
  ]);

  const departmentName = departments.find(d => parseInt(d.id) === parseInt(task.department))?.name || task.department;
  const productName = products.find(p => parseInt(p.id) === parseInt(task.product))?.name || task.product;

  return `${departmentName}-${task.lane}-${productName}: ${task.task}`;
};

const parseIntOrZero = (value) => {
  const parsed = Number.parseInt(value, 10);
  return Number.isNaN(parsed) ? 0 : parsed;
};

const parseNullablePositiveInt = (value) => {
  const parsed = Number.parseInt(value, 10);
  return Number.isNaN(parsed) || parsed <= 0 ? null : parsed;
};

const normalizePayload$2 = (payload = {}) => {
  const gateTypeCandidate = String(payload.gate_type || "").toUpperCase();
  const normalizedGateType = ["ALWAYS", "CONDITION", "QUESTION"].includes(gateTypeCandidate)
    ? gateTypeCandidate
    : (parseNullablePositiveInt(payload.gate_ref_id ?? payload.condition_id) ? "CONDITION" : "ALWAYS");
  const normalizedGateRefId = normalizedGateType === "ALWAYS"
    ? null
    : parseNullablePositiveInt(payload.gate_ref_id ?? payload.condition_id);

  return {
    department: parseIntOrZero(payload.department),
    lane: parseIntOrZero(payload.lane),
    product: parseIntOrZero(payload.product),
    machine_type_id: parseNullablePositiveInt(payload.machine_type_id),
    condition_id: normalizedGateRefId,
    gate_type: normalizedGateType,
    gate_ref_id: normalizedGateRefId,
    task: payload.task,
    description: payload.description,
    order_priority: parseIntOrZero(payload.order_priority),
    services: Array.isArray(payload.services) ? payload.services : [],
    buttons: normalizeSelfServeTaskButtons(payload.buttons),
    dynamic_images_vehicle_type: parseNullablePositiveInt(payload.dynamic_images_vehicle_type),
  };
};

/**
 * The SelfServeTasks object
 */
const SelfServeTasks = {
  meta: {
    title: "Selvbetjeningsopgaver",
    icon: "fas fa-tasks",
    description: "Oversigt over selvbetjeningsopgaver",
    endpoint: "/department/selfserve/tasks",
    labels: {
      single: "opgave",
      multiple: "opgaver"
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    department: {
      label: "Afdeling",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    lane: {
      label: "Bane",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    product: {
      label: "Køretøjstype",
      type: "select",
      sortable: true,
      creation: {
        required: false
      },
      options: async (lockedValues = {}) => {
        const products = await SessionUser.objects.products.get.all();
        if (lockedValues && lockedValues.vehicle_type) {
          return products.filter(p => parseInt(p.id) === parseInt(lockedValues.vehicle_type));
        }
        return products;
      }
    },
    machine_type_id: {
      label: "Maskintype",
      type: "select",
      sortable: true,
      creation: {
        required: false
      },
      options: async () => {
        const machineTypes = await SessionUser.objects.self_serve_machine_types.get.all();
        return [
          { id: 0, name: "Ingen" },
          ...machineTypes.map((entry) => ({
            id: entry.id,
            name: entry.name,
          }))
        ];
      },
      parse: (id) => {
        if (!id) {
          return "Ingen";
        }
        return SessionUser.objects.self_serve_machine_types.functions.getMachineTypeName(id);
      }
    },
    condition_id: {
      label: "Hvis",
      type: "select",
      sortable: true,
      creation: {
        required: false
      },
      options: async (lockedValues = {}) => {
        let conditions = await SessionUser.objects.self_serve_conditions.get.all();
        const departmentId = lockedValues.department || lockedValues.department_id;
        const productId = lockedValues.product || lockedValues.vehicle_type || lockedValues.product_id;
        const machineTypeId = lockedValues.machine_type_id;

        if (machineTypeId) {
          conditions = conditions.filter(c => parseInt(c.machine_type_id || 0) === parseInt(machineTypeId));
        } else {
          conditions = conditions.filter(c => !c.machine_type_id);

          if (departmentId) {
            conditions = conditions.filter(c => parseInt(c.department || 0) === parseInt(departmentId));
          }
          if (productId) {
            conditions = conditions.filter(c => parseInt(c.product || 0) === parseInt(productId));
          }
        }

        const options = await Promise.all(conditions.map(async (condition) => ({
          ...condition,
          name: await SessionUser.objects.self_serve_conditions.functions.formatConditionName(condition.id)
        })));

        options.unshift({
          id: 0,
          name: "Altid"
        });

        return options;
      },
      parse: (id) => {
        return SessionUser.objects.self_serve_conditions.functions.getConditionName(id);
      }
    },
    task: {
      label: "Opgave",
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
    description: {
      label: "Beskrivelse",
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
    order_priority: {
      label: "Rækkefølge",
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
    services: {
      label: "Tjenester",
      type: "multi-select",
      sortable: false,
      creation: {
        required: false
      },
      options: async () => {
        return [
          { id: "MACHINE", name: "MACHINE" }
        ];
      },
      parse: (services) => {
        if (!services || !Array.isArray(services) || services.length === 0) {
          return "Ingen";
        }
        return services.join(", ");
      }
    },
    buttons: {
      label: "Knapper",
      type: "multi-select",
      sortable: false,
      creation: {
        required: false
      },
      options: async () => SELF_SERVE_TASK_BUTTON_OPTIONS,
      parse: (buttons) => formatSelfServeTaskButtons(buttons)
    },
    dynamic_images_vehicle_type: {
      label: "Køretøjstype (maskine UI)",
      type: "select",
      sortable: false,
      creation: {
        required: false
      },
      options: async () => {
        const products = await SessionUser.objects.products.get.all();
        const options = products.map(p => ({ id: p.id, name: p.name }));
        options.unshift({ id: null, name: "Ingen" });
        return options;
      },
      parse: (vehicleTypeId) => {
        if (!vehicleTypeId) return "Ingen";
        return SessionUser.objects.products.functions.getProductName(vehicleTypeId);
      }
    },
  },
  add: async (departmentOrPayload, lane, product, condition_id, task, description, order_priority) => {
    const payload = typeof departmentOrPayload === "object"
      ? normalizePayload$2(departmentOrPayload)
      : normalizePayload$2({
          department: departmentOrPayload,
          lane,
          product,
          condition_id,
          task,
          description,
          order_priority,
        });

    return ObjectsGlobal.add.object(SelfServeTasks.meta.endpoint, payload);
  },
  set: {
    task: (id, task) => ObjectsGlobal.set.column(SelfServeTasks.meta.endpoint, id, "task", task),
    description: (id, description) => ObjectsGlobal.set.column(SelfServeTasks.meta.endpoint, id, "description", description),
    order_priority: (id, order_priority) => ObjectsGlobal.set.column(SelfServeTasks.meta.endpoint, id, "order_priority", parseInt(order_priority || 0)),
    condition_id: (id, condition_id) => ObjectsGlobal.set.column(SelfServeTasks.meta.endpoint, id, "condition_id", (condition_id && parseInt(condition_id) !== 0) ? parseInt(condition_id) : null),
    machine_type_id: (id, machine_type_id) => ObjectsGlobal.set.column(SelfServeTasks.meta.endpoint, id, "machine_type_id", (machine_type_id && parseInt(machine_type_id) !== 0) ? parseInt(machine_type_id) : null),
    product: (id, product) => ObjectsGlobal.set.column(SelfServeTasks.meta.endpoint, id, "product", parseInt(product || 0)),
    lane: (id, lane) => ObjectsGlobal.set.column(SelfServeTasks.meta.endpoint, id, "lane", parseInt(lane || 0)),
    department: (id, department) => ObjectsGlobal.set.column(SelfServeTasks.meta.endpoint, id, "department", parseInt(department || 0)),
    services: (id, services) => ObjectsGlobal.set.column(SelfServeTasks.meta.endpoint, id, "services", Array.isArray(services) ? services : []),
    buttons: (id, buttons) => ObjectsGlobal.set.column(SelfServeTasks.meta.endpoint, id, "buttons", normalizeSelfServeTaskButtons(buttons)),
    dynamic_images_vehicle_type: (id, vehicleType) => ObjectsGlobal.set.column(SelfServeTasks.meta.endpoint, id, "dynamic_images_vehicle_type", vehicleType ? parseInt(vehicleType) : null),
  },
  get: {
    all: (filters = {}) => ObjectsGlobal.get.objects(SelfServeTasks.meta.endpoint, filters),
    single: (id) => ObjectsGlobal.get.object(SelfServeTasks.meta.endpoint, id)
  },
  delete: (id) => ObjectsGlobal.delete.object(SelfServeTasks.meta.endpoint, id),
  attachments: {
    list: (taskId) => authenticatedRequest(SelfServeTasks.meta.endpoint + "/attachments", "GET", { id: taskId })
          .then(response => response.data),
    delete: (taskId, attachmentId) => authenticatedRequest(SelfServeTasks.meta.endpoint + "/attachments", "DELETE", { task_id: taskId, attachment_id: attachmentId })
          .then(response => response.data),
    upload: (taskId, base64File, fileName) => authenticatedRequest(SelfServeTasks.meta.endpoint + "/attachments/upload", "POST", {
        task_id: taskId,
        base64_file: base64File,
        file_name: fileName
      }).then(response => response.data),
    download: (taskId, attachmentId) => authenticatedRequest(SelfServeTasks.meta.endpoint + "/attachments/download", "GET", {
        task_id: taskId,
        attachment_id: attachmentId
      }).then(response => response.data)
  },
  functions: {
    getTaskText: getTaskText,
    formatTaskName: async (taskId) => {
      const tasks = await SessionUser.objects.self_serve_tasks.get.all();
      const task = tasks.find(t => parseInt(t.id) === parseInt(taskId));
      if (!task) return SessionUser.objects.global.language.no_data;

      return buildScopedTaskName(task);
    },
    getScopeLabel: async (task) => {
      if (task.machine_type_id) {
        const machineTypeName = await SessionUser.objects.self_serve_machine_types.functions.getMachineTypeName(task.machine_type_id);
        return `Maskintype: ${machineTypeName}`;
      }

      if (
        parseInt(task.department || 0) === 0
        && parseInt(task.lane || 0) === 0
        && parseInt(task.product || 0) === 0
      ) {
        return "Fælles";
      }

      return `Afdeling ${task.department || 0} / Bane ${task.lane || 0} / Køretøjstype ${task.product || 0}`;
    },
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(SelfServeTasks, id, onAfterSubmit);
    },
  },
  showCreateObjectForm: (initialData = {}, onAfterSubmit = null) => {
    return showSelfServeTaskForm({
      object: SelfServeTasks,
      initialData,
      onAfterSubmit,
    });
  },
  showEditObjectForm: (record, onAfterSubmit = null) => {
    return showSelfServeTaskForm({
      object: SelfServeTasks,
      record,
      onAfterSubmit,
    });
  },
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null, options = {}) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        SelfServeTasks,
        id,
        column,
        value,
        onAfterSubmit,
        options
    );
  }
};

const _sfc_main$a = {};
const SelfServeTasks_default = /*#__PURE__*/_export_sfc(_sfc_main$a, [['__file',"SelfServeTasks.vue"]]);

/**
 * Local conditions cache
 * @type {ref<null>}
 */
const conditions_cache = ref(null);

/**
 * Get the condition name
 * @param id
 * @param fallback
 * @returns {string}
 */
const getConditionName = (id, fallback = null) => {
  if (conditions_cache.value === null) {
    conditions_cache.value = [];
    SessionUser.objects.self_serve_conditions.get.all().then((conditions) => {
      conditions_cache.value = conditions;
    });
  }
  const condition = conditions_cache.value.find((condition) => condition.id === parseInt(id));
  return condition ? condition.name : fallback === null ? SessionUser.objects.global.language.no_data : fallback;
};

const buildScopedConditionName = async (condition) => {
  if (!condition) {
    return SessionUser.objects.global.language.no_data;
  }

  if (condition.machine_type_id) {
    const machineTypeName = await SessionUser.objects.self_serve_machine_types.functions.getMachineTypeName(condition.machine_type_id);
    return `[Maskintype] ${machineTypeName}: ${condition.name}`;
  }

  const [departments, products] = await Promise.all([
    SessionUser.objects.departments.get.all(),
    SessionUser.objects.products.get.all()
  ]);

  const departmentName = departments.find(d => parseInt(d.id) === parseInt(condition.department))?.name || condition.department;
  const productName = products.find(p => parseInt(p.id) === parseInt(condition.product))?.name || condition.product;

  return `${departmentName}-${condition.lane}-${productName}: ${condition.name}`;
};

const normalizePayload$1 = (payload) => ({
  department: parseInt(payload.department || 0),
  lane: parseInt(payload.lane || 0),
  product: parseInt(payload.product || 0),
  machine_type_id: payload.machine_type_id && parseInt(payload.machine_type_id) !== 0 ? parseInt(payload.machine_type_id) : null,
  condition_id: payload.condition_id && parseInt(payload.condition_id) !== 0 ? parseInt(payload.condition_id) : null,
  name: payload.name,
  description: payload.description,
});

/**
 * The SelfServeConditions object
 */
const SelfServeConditions = {
  meta: {
    title: "Selvbetjeningsbetingelser",
    icon: "fas fa-filter",
    description: "Oversigt over selvbetjeningsbetingelser",
    endpoint: "/department/selfserve/conditions",
    labels: {
      single: "betingelse",
      multiple: "betingelser"
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    department: {
      label: "Afdeling",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    lane: {
      label: "Bane",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    product: {
      label: "Køretøjstype",
      type: "select",
      sortable: true,
      creation: {
        required: false
      },
      options: async (lockedValues = {}) => {
        const products = await SessionUser.objects.products.get.all();
        if (lockedValues && (lockedValues.vehicle_type || lockedValues.product)) {
          return products.filter(p => parseInt(p.id) === parseInt(lockedValues.vehicle_type || lockedValues.product));
        }
        return products;
      }
    },
    machine_type_id: {
      label: "Maskintype",
      type: "select",
      sortable: true,
      creation: {
        required: false
      },
      options: async () => {
        const machineTypes = await SessionUser.objects.self_serve_machine_types.get.all();
        return [
          { id: 0, name: "Ingen" },
          ...machineTypes.map((entry) => ({
            id: entry.id,
            name: entry.name,
          }))
        ];
      },
      parse: (id) => {
        if (!id) {
          return "Ingen";
        }
        return SessionUser.objects.self_serve_machine_types.functions.getMachineTypeName(id);
      }
    },
    condition_id: {
      label: "Betingelse (Hvis)",
      type: "select",
      sortable: true,
      creation: {
        required: false
      },
      options: async (lockedValues = {}) => {
        let conditions = await SessionUser.objects.self_serve_conditions.get.all();
        const departmentId = lockedValues.department || lockedValues.department_id;
        const productId = lockedValues.product || lockedValues.vehicle_type || lockedValues.product_id;
        const machineTypeId = lockedValues.machine_type_id;

        if (machineTypeId) {
          conditions = conditions.filter(c => parseInt(c.machine_type_id || 0) === parseInt(machineTypeId));
        } else {
          conditions = conditions.filter(c => !c.machine_type_id);

          if (departmentId) {
            conditions = conditions.filter(c => parseInt(c.department || 0) === parseInt(departmentId));
          }

          if (productId) {
            conditions = conditions.filter(c => parseInt(c.product || 0) === parseInt(productId));
          }
        }

        const options = await Promise.all(conditions.map(async (condition) => ({
          ...condition,
          name: await buildScopedConditionName(condition),
        })));

        options.unshift({
          id: 0,
          name: "Ingen"
        });

        return options;
      },
      parse: (id) => {
        return SessionUser.objects.self_serve_conditions.functions.getConditionName(id);
      }
    },
    name: {
      label: "Navn",
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
    description: {
      label: "Beskrivelse",
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
  },
  add: async (departmentOrPayload, lane, product, name, description, condition_id = null, machine_type_id = null) => {
    const payload = typeof departmentOrPayload === "object"
      ? normalizePayload$1(departmentOrPayload)
      : normalizePayload$1({
          department: departmentOrPayload,
          lane,
          product,
          name,
          description,
          condition_id,
          machine_type_id,
        });

    return ObjectsGlobal.add.object(SelfServeConditions.meta.endpoint, payload);
  },
  set: {
    machine_type_id: async (id, machine_type_id) => {
      return ObjectsGlobal.set.column(
        SelfServeConditions.meta.endpoint,
        id,
        "machine_type_id",
        (machine_type_id && parseInt(machine_type_id) !== 0) ? parseInt(machine_type_id) : null
      );
    },
    condition_id: async (id, condition_id) => {
      return ObjectsGlobal.set.column(
        SelfServeConditions.meta.endpoint,
        id,
        "condition_id",
        (condition_id && parseInt(condition_id) !== 0) ? parseInt(condition_id) : null
      );
    },
    name: async (id, name) => {
      return ObjectsGlobal.set.column(SelfServeConditions.meta.endpoint, id, "name", name);
    },
    description: async (id, description) => {
      return ObjectsGlobal.set.column(SelfServeConditions.meta.endpoint, id, "description", description);
    },
    product: async (id, product) => {
      return ObjectsGlobal.set.column(SelfServeConditions.meta.endpoint, id, "product", parseInt(product || 0));
    },
    lane: async (id, lane) => {
      return ObjectsGlobal.set.column(SelfServeConditions.meta.endpoint, id, "lane", parseInt(lane || 0));
    },
    department: async (id, department) => {
      return ObjectsGlobal.set.column(SelfServeConditions.meta.endpoint, id, "department", parseInt(department || 0));
    },
  },
  get: {
    all: async (filters = {}) => {
      return ObjectsGlobal.get.objects(SelfServeConditions.meta.endpoint, filters);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(SelfServeConditions.meta.endpoint, id);
    }
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(SelfServeConditions.meta.endpoint, id);
  },
  functions: {
    getConditionName: getConditionName,
    formatConditionName: async (conditionId) => {
      const conditions = await SessionUser.objects.self_serve_conditions.get.all();
      const condition = conditions.find(c => parseInt(c.id) === parseInt(conditionId));
      if (!condition) return SessionUser.objects.global.language.no_data;

      return buildScopedConditionName(condition);
    },
    getScopeLabel: async (condition) => {
      if (condition.machine_type_id) {
        const machineTypeName = await SessionUser.objects.self_serve_machine_types.functions.getMachineTypeName(condition.machine_type_id);
        return `Maskintype: ${machineTypeName}`;
      }

      if (
        parseInt(condition.department || 0) === 0
        && parseInt(condition.lane || 0) === 0
        && parseInt(condition.product || 0) === 0
      ) {
        return "Fælles";
      }

      return `Afdeling ${condition.department || 0} / Bane ${condition.lane || 0} / Køretøjstype ${condition.product || 0}`;
    },
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(SelfServeConditions, id, onAfterSubmit);
    },
  },
  showCreateObjectForm: (initialData = {}, onAfterSubmit = null) => {
    return showSelfServeConditionForm({
      object: SelfServeConditions,
      initialData,
      onAfterSubmit,
    });
  },
  showEditObjectForm: (record, onAfterSubmit = null) => {
    return showSelfServeConditionForm({
      object: SelfServeConditions,
      record,
      onAfterSubmit,
    });
  },
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null, options = {}) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        SelfServeConditions,
        id,
        column,
        value,
        onAfterSubmit,
        options
    );
  }
};

const _sfc_main$9 = {};
const SelfServeConditions_default = /*#__PURE__*/_export_sfc(_sfc_main$9, [['__file',"SelfServeConditions.vue"]]);

/**
 * Local vehicle conditions cache
 * @type {ref<null>}
 */
const vehicle_conditions_cache = ref(null);

/**
 * The SelfServeVehicleConditions object
 */
const SelfServeVehicleConditions = {
  meta: {
    title: "Køretøjsbetingelser",
    icon: "fas fa-car-side",
    description: "Oversigt over køretøjsbetingelser (Svar på spørgsmål)",
    endpoint: "/department/selfserve/vehicle/conditions",
    labels: {
      single: "køretøjsbetingelse",
      multiple: "køretøjsbetingelser"
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    department: {
      label: "Afdeling",
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
    lane: {
      label: "Bane",
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
    customer_id: {
      label: "Kunde ID",
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
    reg: {
      label: "Registreringsnummer",
      type: "string",
      sortable: true,
      creation: {
        required: true,
        onchange: async (event, helpers) => {
          const reg = event.target.value;
          if (reg && reg.length > 2) {
            try {
              const status = await SessionUser.objects.vehicles.functions.getVehicleStatus(reg);
              if (status && status.customer_id) {
                helpers.setFieldValue('customer_id', status.customer_id);
              }
            } catch (e) {
              console.error("Could not fetch vehicle status", e);
            }
          }
        }
      }
    },
    question: {
      label: "Spørgsmål",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async (lockedValues = {}) => {
        const departmentId = lockedValues.department || lockedValues.department_id;
        const questions = await SessionUser.objects.self_serve_questions.get.all(
            departmentId ? { department: parseInt(departmentId) } : {}
        );

        const [departments, products] = await Promise.all([
          SessionUser.objects.departments.get.all(),
          SessionUser.objects.products.get.all()
        ]);

        return questions.map(q => {
          const departmentName = departments.find(d => parseInt(d.id) === parseInt(q.department))?.name || q.department;
          const productName = products.find(p => parseInt(p.id) === parseInt(q.product))?.name || q.product;
          return {
            ...q,
            name: `${departmentName}-${q.lane}-${productName}: ${q.question}`
          };
        });
      },
      parse: (id) => {
        return SessionUser.objects.self_serve_questions.functions.getQuestionText(id);
      }
    },
    value: {
      label: "Værdi",
      type: "boolean",
      sortable: true,
      creation: {
        required: true
      }
    },
    created_at: {
      label: "Oprettet",
      type: "datetime",
      sortable: true,
      creation: {
        required: false
      }
    }
  },
  add: async (department, lane, customer_id, reg, question, value, options = {}) => {
    const safeOptions = {};
    const normalizedVehicleType = parseInt(options.vehicle_type ?? options.vehicle_type_id);

    if (!Number.isNaN(normalizedVehicleType) && normalizedVehicleType > 0) {
      safeOptions.vehicle_type = normalizedVehicleType;
    }

    return ObjectsGlobal.add.object(SelfServeVehicleConditions.meta.endpoint, {
      department: parseInt(department),
      lane: parseInt(lane),
      customer_id: parseInt(customer_id),
      reg: reg,
      question: parseInt(question),
      value: value === "true" || value === true,
      ...safeOptions,
      activate_machine: false,
      sync_relay_state: false
    });
  },
  set: {
    department: async (id, department) => {
      return ObjectsGlobal.set.column(SelfServeVehicleConditions.meta.endpoint, id, "department", parseInt(department));
    },
    lane: async (id, lane) => {
      return ObjectsGlobal.set.column(SelfServeVehicleConditions.meta.endpoint, id, "lane", parseInt(lane));
    },
    customer_id: async (id, customer_id) => {
      return ObjectsGlobal.set.column(SelfServeVehicleConditions.meta.endpoint, id, "customer_id", parseInt(customer_id));
    },
    reg: async (id, reg) => {
      return ObjectsGlobal.set.column(SelfServeVehicleConditions.meta.endpoint, id, "reg", reg);
    },
    question: async (id, question) => {
      return ObjectsGlobal.set.column(SelfServeVehicleConditions.meta.endpoint, id, "question", parseInt(question));
    },
    value: async (id, value) => {
      return ObjectsGlobal.set.column(SelfServeVehicleConditions.meta.endpoint, id, "value", value === "true" || value === true);
    }
  },
  get: {
    all: async (filters = {}) => {
      return ObjectsGlobal.get.objects(SelfServeVehicleConditions.meta.endpoint, filters);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(SelfServeVehicleConditions.meta.endpoint, id);
    },
    previewAllowed: async (laneId, reg, vehicleTypeId, options = {}) => {
      const params = {
        lane_id: parseInt(laneId),
        reg: reg,
      };

      const normalizedVehicleTypeId = parseInt(vehicleTypeId);
      if (!Number.isNaN(normalizedVehicleTypeId) && normalizedVehicleTypeId > 0) {
        params.vehicle_type = normalizedVehicleTypeId;
      }

      return authenticatedRequest("/department/selfserve/vehicle/allowed", "GET", params, null, null, options)
        .then((response) => response.data.data || response.data);
    },
    washSummary: async (params, options) => {
      return authenticatedRequest("/department/selfserve/washes/summary", "GET", params || {}, null, null, options || {})
        .then((response) => response.data.data || response.data);
    }
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(SelfServeVehicleConditions.meta.endpoint, id);
  },
  functions: {
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(SelfServeVehicleConditions, id, onAfterSubmit);
    },
  },
  /**
   * Show the create object form
   * @param initialData
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showCreateObjectForm: (initialData = {}, onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(SelfServeVehicleConditions, onAfterSubmit, initialData);
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        SelfServeVehicleConditions,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$8 = {};
const SelfServeVehicleConditions_default = /*#__PURE__*/_export_sfc(_sfc_main$8, [['__file',"SelfServeVehicleConditions.vue"]]);

/**
 * Local condition rules cache
 * @type {ref<null>}
 */
const condition_rules_cache = ref(null);

/**
 * Get the condition rule name
 * @param id
 * @param fallback
 * @returns {string}
 */
const getConditionRuleName = (id, fallback = null) => {
  if (condition_rules_cache.value === null) {
    condition_rules_cache.value = [];
    SessionUser.objects.self_serve_condition_rules.get.all().then((rules) => {
      condition_rules_cache.value = rules;
    });
  }
  const rule = condition_rules_cache.value.find((rule) => rule.id === parseInt(id));
  return rule ? rule.name : fallback === null ? SessionUser.objects.global.language.no_data : fallback;
};

const normalizePayload = (payload) => ({
  condition_id: parseInt(payload.condition_id),
  type: payload.type,
  object_type: payload.object_type,
  object_id: parseInt(payload.object_id),
  name: payload.name,
  description: payload.description,
});

/**
 * The SelfServeConditionRules object
 */
const SelfServeConditionRules = {
  meta: {
    title: "Betingelsesregler",
    icon: "fas fa-gavel",
    description: "Oversigt over betingelsesregler",
    endpoint: "/department/selfserve/condition/rules",
    labels: {
      single: "regel",
      multiple: "regler"
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    condition_id: {
      label: "Betingelse (parent)",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async (lockedValues = {}) => {
        let conditions = await SessionUser.objects.self_serve_conditions.get.all();
        const departmentId = lockedValues.department || lockedValues.department_id;
        const productId = lockedValues.product || lockedValues.vehicle_type || lockedValues.product_id;
        const machineTypeId = lockedValues.machine_type_id;

        if (machineTypeId) {
          conditions = conditions.filter(c => parseInt(c.machine_type_id || 0) === parseInt(machineTypeId));
        } else {
          if (departmentId) {
            conditions = conditions.filter(c => parseInt(c.department || 0) === parseInt(departmentId));
          }
          if (productId) {
            conditions = conditions.filter(c => parseInt(c.product || 0) === parseInt(productId));
          }
        }

        return Promise.all(conditions.map(async (condition) => ({
          ...condition,
          name: await SessionUser.objects.self_serve_conditions.functions.formatConditionName(condition.id)
        })));
      },
      parse: (id) => {
        return SessionUser.objects.self_serve_conditions.functions.getConditionName(id);
      }
    },
    type: {
      label: "Type",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return [
          { id: "IS_TRUE", name: "Er sand" },
          { id: "IS_FALSE", name: "Er falsk" },
          { id: "IS_TRUE_OR_NOT_SET", name: "Er sand eller ikke sat" },
          { id: "IS_FALSE_OR_NOT_SET", name: "Er falsk eller ikke sat" },
          { id: "IS_SET", name: "Er sat" },
          { id: "IS_TRUE_OR_ANY_TRUE", name: "Er sand, eller betingelsen indeholder mindst én sand regel" },
        ];
      }
    },
    object_type: {
      label: "Objekt type",
      type: "select",
      sortable: true,
      creation: {
        required: true
      },
      options: async () => {
        return [
          { id: "question", name: "Spørgsmål" },
          { id: "condition", name: "Betingelse" },
        ];
      }
    },
    object_id: {
      label: "Objekt ID",
      type: "select",
      sortable: true,
      creation: {
        required: true,
        onchange: async (event, { setFieldValue, getFieldValue }) => {
          const objectId = parseInt(event.target.value);
          const objectType = getFieldValue("object_type");

          if (objectType === "question") {
            const formattedName = await SessionUser.objects.self_serve_questions.functions.formatQuestionName(objectId);
            const questions = await SessionUser.objects.self_serve_questions.get.all();
            const question = questions.find(q => parseInt(q.id) === parseInt(objectId));
            if (question) {
              setFieldValue("name", formattedName);
              setFieldValue("description", question.description || "");
            }
          } else if (objectType === "condition") {
            const formattedName = await SessionUser.objects.self_serve_conditions.functions.formatConditionName(objectId);
            const conditions = await SessionUser.objects.self_serve_conditions.get.all();
            const condition = conditions.find(c => parseInt(c.id) === parseInt(objectId));
            if (condition) {
              setFieldValue("name", formattedName);
              setFieldValue("description", condition.description || "");
            }
          }
        }
      },
      options: async (lockedValues = {}) => {
        const objectType = lockedValues.object_type;

        if (objectType === "question") {
          const questions = await SessionUser.objects.self_serve_questions.get.all();
          return Promise.all(questions.map(async (question) => ({
            id: question.id,
            name: await SessionUser.objects.self_serve_questions.functions.formatQuestionName(question.id)
          })));
        }

        const conditions = await SessionUser.objects.self_serve_conditions.get.all();
        return Promise.all(conditions.map(async (condition) => ({
          id: condition.id,
          name: await SessionUser.objects.self_serve_conditions.functions.formatConditionName(condition.id)
        })));
      }
    },
    name: {
      label: "Navn",
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
    description: {
      label: "Beskrivelse",
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
  },
  add: async (conditionIdOrPayload, type, object_type, object_id, name, description) => {
    const payload = typeof conditionIdOrPayload === "object"
      ? normalizePayload(conditionIdOrPayload)
      : normalizePayload({
          condition_id: conditionIdOrPayload,
          type,
          object_type,
          object_id,
          name,
          description,
        });

    return ObjectsGlobal.add.object(SelfServeConditionRules.meta.endpoint, payload);
  },
  set: {
    condition_id: async (id, condition_id) => {
      return ObjectsGlobal.set.column(SelfServeConditionRules.meta.endpoint, id, "condition_id", parseInt(condition_id));
    },
    type: async (id, type) => {
      return ObjectsGlobal.set.column(SelfServeConditionRules.meta.endpoint, id, "type", type);
    },
    object_type: async (id, object_type) => {
      return ObjectsGlobal.set.column(SelfServeConditionRules.meta.endpoint, id, "object_type", object_type);
    },
    object_id: async (id, object_id) => {
      return ObjectsGlobal.set.column(SelfServeConditionRules.meta.endpoint, id, "object_id", parseInt(object_id));
    },
    name: async (id, name) => {
      return ObjectsGlobal.set.column(SelfServeConditionRules.meta.endpoint, id, "name", name);
    },
    description: async (id, description) => {
      return ObjectsGlobal.set.column(SelfServeConditionRules.meta.endpoint, id, "description", description);
    },
  },
  get: {
    all: async (filters = {}) => {
      return ObjectsGlobal.get.objects(SelfServeConditionRules.meta.endpoint, filters);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(SelfServeConditionRules.meta.endpoint, id);
    }
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(SelfServeConditionRules.meta.endpoint, id);
  },
  functions: {
    getConditionRuleName: getConditionRuleName,
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(SelfServeConditionRules, id, onAfterSubmit);
    },
  },
  showCreateObjectForm: (initialData = {}, onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(SelfServeConditionRules, onAfterSubmit, initialData);
  },
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null, options = {}) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        SelfServeConditionRules,
        id,
        column,
        value,
        onAfterSubmit,
        options
    );
  }
};

const _sfc_main$7 = {};
const SelfServeConditionRules_default = /*#__PURE__*/_export_sfc(_sfc_main$7, [['__file',"SelfServeConditionRules.vue"]]);

/**
 * The SelfServeMachineTypes object
 */
const SelfServeMachineTypes = {
  meta: {
    title: "Self-serve maskintyper",
    icon: "fas fa-cubes",
    description: "Genbrugelige maskintyper til self-serve",
    endpoint: "/department/selfserve/machine-types",
    labels: {
      single: "maskintype",
      multiple: "maskintyper"
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    name: {
      label: "Navn",
      type: "string",
      sortable: true,
      creation: {
        required: true
      }
    },
    description: {
      label: "Beskrivelse",
      type: "string",
      sortable: true,
      creation: {
        required: false
      }
    },
    created_at: {
      label: "Oprettet",
      type: "datetime",
      sortable: true,
      creation: {
        required: false
      }
    },
    updated_at: {
      label: "Opdateret",
      type: "datetime",
      sortable: true,
      creation: {
        required: false
      }
    },
  },
  add: async (nameOrPayload, description = null) => {
    const payload = typeof nameOrPayload === "object"
      ? nameOrPayload
      : {
          name: nameOrPayload,
          description: description || null,
        };

    return ObjectsGlobal.add.object(SelfServeMachineTypes.meta.endpoint, payload);
  },
  set: {
    name: async (id, name) => {
      return ObjectsGlobal.set.column(SelfServeMachineTypes.meta.endpoint, id, "name", name);
    },
    description: async (id, description) => {
      return ObjectsGlobal.set.column(
        SelfServeMachineTypes.meta.endpoint,
        id,
        "description",
        description || null
      );
    },
  },
  get: {
    all: async (filters = {}) => {
      return ObjectsGlobal.get.objects(SelfServeMachineTypes.meta.endpoint, filters);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(SelfServeMachineTypes.meta.endpoint, id);
    }
  },
  delete: async (id) => {
    return ObjectsGlobal.delete.object(SelfServeMachineTypes.meta.endpoint, id);
  },
  functions: {
    getMachineTypeName: async (id, fallback = null) => {
      if (!id) {
        return fallback ?? ObjectsGlobal.language.none;
      }

      const machineTypes = await SelfServeMachineTypes.get.all();
      const machineType = machineTypes.find((entry) => parseInt(entry.id) === parseInt(id));
      return machineType ? machineType.name : fallback ?? ObjectsGlobal.language.no_data;
    },
    showDeleteObjectForm: (id, onAfterSubmit = null) => {
      return ObjectsGlobal.showDeleteObjectForm(SelfServeMachineTypes, id, onAfterSubmit);
    },
  },
  showCreateObjectForm: (initialData = {}, onAfterSubmit = null) => {
    return ObjectsGlobal.showCreateObjectForm(SelfServeMachineTypes, onAfterSubmit, initialData);
  },
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null, options = {}) => {
    return ObjectsGlobal.showEditObjectFieldForm(
      SelfServeMachineTypes,
      id,
      column,
      value,
      onAfterSubmit,
      options
    );
  }
};

const _sfc_main$6 = {};
const SelfServeMachineTypes_default = /*#__PURE__*/_export_sfc(_sfc_main$6, [['__file',"SelfServeMachineTypes.vue"]]);

const _sfc_main$5 = /* @__PURE__ */ defineComponent({
  __name: "SubuserGrantPermissionNodes",
  props: {
    grant: {
      type: Object,
      default: () => ({ id: 0, permissions: [], name: "", permission_template_key: "custom" }),
      required: true
    },
    permissions: {
      type: Array,
      default: () => [],
      required: true
    },
    templateKey: {
      type: String,
      default: null
    },
    allowAdvanced: {
      type: Boolean,
      default: false
    }
  },
  emits: ["update:permissions", "update:access"],
  setup(__props, { expose: __expose, emit: __emit }) {
    __expose();
    const props = __props;
    const t = (key, values = void 0) => i18n.global.t(key, values);
    const LEGACY_PERMISSION_GROUPS = [
      {
        key: "vehicles",
        capabilities: ["VEHICLES_LIST", "VEHICLES_EDIT", "VEHICLES_DELETE", "VEHICLES_ADD"]
      },
      {
        key: "selfserve",
        capabilities: ["SELFSERVE_LIST", "SELFSERVE_EDIT", "SELFSERVE_DELETE", "SELFSERVE_ADD"]
      },
      {
        key: "bookings",
        capabilities: ["BOOKINGS_LIST", "BOOKINGS_EDIT", "BOOKINGS_DELETE", "BOOKINGS_ADD"]
      },
      {
        key: "orders",
        capabilities: ["ORDERS_LIST", "ORDERS_EDIT"]
      },
      {
        key: "driver_management",
        capabilities: ["SUBUSERS_LIST", "SUBUSERS_EDIT", "SUBUSERS_DELETE", "SUBUSERS_ADD"]
      }
    ];
    const LEGACY_PERMISSION_LABEL_KEYS = {
      VEHICLES_LIST: "view_vehicles",
      VEHICLES_EDIT: "edit_vehicles",
      VEHICLES_DELETE: "delete_vehicles",
      VEHICLES_ADD: "add_vehicles",
      SELFSERVE_LIST: "view_selfserve",
      SELFSERVE_EDIT: "edit_selfserve",
      SELFSERVE_DELETE: "delete_selfserve",
      SELFSERVE_ADD: "start_selfserve",
      BOOKINGS_LIST: "view_bookings",
      BOOKINGS_EDIT: "edit_bookings",
      BOOKINGS_DELETE: "delete_bookings",
      BOOKINGS_ADD: "add_bookings",
      ORDERS_LIST: "view_orders",
      ORDERS_EDIT: "edit_orders",
      SUBUSERS_LIST: "view_drivers",
      SUBUSERS_EDIT: "edit_driver_access",
      SUBUSERS_DELETE: "disable_driver_access",
      SUBUSERS_ADD: "invite_drivers"
    };
    const templates = ref([]);
    const selectedPermissions = ref([]);
    const selectedTemplateKey = ref(props.templateKey || props.grant.permission_template_key || "custom");
    const isLoading = ref(true);
    const emit = __emit;
    const normalizePermissions = (value) => [...new Set((value || []).filter(Boolean).map((item) => String(item).toUpperCase()))];
    const samePermissions = (left, right) => {
      const a = normalizePermissions(left).sort();
      const b = normalizePermissions(right).sort();
      return a.length === b.length && a.every((value, index) => value === b[index]);
    };
    const findTemplate = (key) => templates.value.find((template) => template.key === key) || null;
    const classifyTemplate = (permissions) => {
      if (permissions.length === 0) {
        return "deactivated";
      }
      const match = templates.value.find((template) => template.key !== "deactivated" && samePermissions(template.permissions, permissions));
      return match?.key || "custom";
    };
    const emitAccess = () => {
      emit("update:permissions", [...selectedPermissions.value]);
      emit("update:access", {
        permission_template_key: selectedTemplateKey.value,
        permissions: [...selectedPermissions.value]
      });
    };
    const syncPermissions = (value) => {
      selectedPermissions.value = normalizePermissions(value);
      if (templates.value.length > 0 && (!props.templateKey || props.templateKey === "custom")) {
        selectedTemplateKey.value = classifyTemplate(selectedPermissions.value);
      }
    };
    const selectTemplate = (key) => {
      if (key === "custom") {
        selectedTemplateKey.value = "custom";
        emitAccess();
        return;
      }
      const template = findTemplate(key);
      if (!template) {
        return;
      }
      selectedTemplateKey.value = template.key;
      selectedPermissions.value = normalizePermissions(template.permissions);
      emitAccess();
    };
    const togglePermission = (permissionKey, enabled) => {
      selectedTemplateKey.value = "custom";
      if (enabled) {
        selectedPermissions.value = [.../* @__PURE__ */ new Set([...selectedPermissions.value, permissionKey])];
      } else {
        selectedPermissions.value = selectedPermissions.value.filter((value) => value !== permissionKey);
      }
      emitAccess();
    };
    const visibleTemplates = computed(() => templates.value.filter((template) => template.key !== "custom"));
    const activeTemplate = computed(() => findTemplate(selectedTemplateKey.value));
    const showAdvanced = computed(() => props.allowAdvanced && selectedTemplateKey.value === "custom");
    const templateLabel = (key, _fallback = "") => t(`superuser.driver_access.templates.${key}.label`);
    const templateDescription = (template) => t(`superuser.driver_access.templates.${template.key}.description`);
    const groupLabel = (key) => t(`superuser.driver_access.groups.${key}`);
    const permissionLabel = (permission) => {
      const capabilityKey = LEGACY_PERMISSION_LABEL_KEYS[permission] || permission;
      return t(`superuser.driver_access.capabilities.${capabilityKey}`);
    };
    watch(
      () => props.permissions,
      (newPermissions) => {
        syncPermissions(newPermissions || []);
        emitAccess();
      },
      { immediate: true }
    );
    onMounted(async () => {
      try {
        const accessModel = await SessionUser.objects.subuser_grants.functions.getPermissionTemplates();
        templates.value = Array.isArray(accessModel?.templates) ? accessModel.templates : [];
        selectedTemplateKey.value = props.templateKey || props.grant.permission_template_key || classifyTemplate(selectedPermissions.value);
        if (selectedTemplateKey.value !== "custom") {
          const template = findTemplate(selectedTemplateKey.value);
          if (template) {
            selectedPermissions.value = normalizePermissions(template.permissions);
          }
        }
        emitAccess();
      } catch (error) {
        console.error("Failed to fetch permission templates:", error);
        templates.value = [];
        selectedTemplateKey.value = "custom";
      } finally {
        isLoading.value = false;
      }
    });
    const __returned__ = { props, t, LEGACY_PERMISSION_GROUPS, LEGACY_PERMISSION_LABEL_KEYS, templates, selectedPermissions, selectedTemplateKey, isLoading, emit, normalizePermissions, samePermissions, findTemplate, classifyTemplate, emitAccess, syncPermissions, selectTemplate, togglePermission, visibleTemplates, activeTemplate, showAdvanced, templateLabel, templateDescription, groupLabel, permissionLabel, get BCheckbox() {
      return BCheckbox;
    } };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1$2 = { class: "title is-4" };
const _hoisted_2$1 = { class: "mb-4 has-text-grey" };
const _hoisted_3$1 = {
  key: 0,
  class: "notification is-light"
};
const _hoisted_4$1 = {
  key: 1,
  class: "notification is-warning is-light"
};
const _hoisted_5$1 = {
  key: 2,
  class: "driver-access-editor"
};
const _hoisted_6$1 = ["data-testid", "onClick"];
const _hoisted_7$1 = { class: "driver-access-card__title" };
const _hoisted_8$1 = { class: "driver-access-card__description" };
const _hoisted_9$1 = {
  key: 0,
  class: "tag is-success is-light"
};
const _hoisted_10$1 = { class: "driver-access-card__title" };
const _hoisted_11$1 = { class: "driver-access-card__description" };
const _hoisted_12$1 = {
  key: 0,
  class: "tag is-warning is-light"
};
const _hoisted_13$1 = {
  key: 3,
  class: "notification is-info is-light mt-4"
};
const _hoisted_14$1 = {
  key: 4,
  class: "advanced-access mt-5",
  "data-testid": "permission-template-custom-editor"
};
const _hoisted_15$1 = { class: "title is-6" };
const _hoisted_16$1 = { class: "columns is-multiline" };
function _sfc_render$2(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock("div", null, [
    createBaseVNode(
      "h2",
      _hoisted_1$2,
      toDisplayString($setup.t("superuser.driver_access.editor_title", { name: $setup.props.grant.name })),
      1
      /* TEXT */
    ),
    createBaseVNode(
      "p",
      _hoisted_2$1,
      toDisplayString($setup.t("superuser.driver_access.editor_intro")),
      1
      /* TEXT */
    ),
    $setup.isLoading ? (openBlock(), createElementBlock(
      "div",
      _hoisted_3$1,
      toDisplayString($setup.t("superuser.driver_access.loading")),
      1
      /* TEXT */
    )) : $setup.visibleTemplates.length === 0 ? (openBlock(), createElementBlock(
      "div",
      _hoisted_4$1,
      toDisplayString($setup.t("superuser.driver_access.empty")),
      1
      /* TEXT */
    )) : (openBlock(), createElementBlock("div", _hoisted_5$1, [
      (openBlock(true), createElementBlock(
        Fragment,
        null,
        renderList($setup.visibleTemplates, (template) => {
          return openBlock(), createElementBlock("button", {
            key: template.key,
            type: "button",
            class: normalizeClass(["driver-access-card", { "driver-access-card--selected": $setup.selectedTemplateKey === template.key }]),
            "data-testid": `permission-template-${template.key}`,
            onClick: ($event) => $setup.selectTemplate(template.key)
          }, [
            createBaseVNode(
              "span",
              _hoisted_7$1,
              toDisplayString($setup.templateLabel(template.key, template.label)),
              1
              /* TEXT */
            ),
            createBaseVNode(
              "span",
              _hoisted_8$1,
              toDisplayString($setup.templateDescription(template)),
              1
              /* TEXT */
            ),
            $setup.selectedTemplateKey === template.key ? (openBlock(), createElementBlock(
              "span",
              _hoisted_9$1,
              toDisplayString($setup.t("superuser.driver_access.selected")),
              1
              /* TEXT */
            )) : createCommentVNode("v-if", true)
          ], 10, _hoisted_6$1);
        }),
        128
        /* KEYED_FRAGMENT */
      )),
      $props.allowAdvanced ? (openBlock(), createElementBlock(
        "button",
        {
          key: 0,
          type: "button",
          class: normalizeClass(["driver-access-card", { "driver-access-card--selected": $setup.selectedTemplateKey === "custom" }]),
          "data-testid": "permission-template-custom",
          onClick: _cache[0] || (_cache[0] = ($event) => $setup.selectTemplate("custom"))
        },
        [
          createBaseVNode(
            "span",
            _hoisted_10$1,
            toDisplayString($setup.templateLabel("custom")),
            1
            /* TEXT */
          ),
          createBaseVNode(
            "span",
            _hoisted_11$1,
            toDisplayString($setup.t("superuser.driver_access.custom_description")),
            1
            /* TEXT */
          ),
          $setup.selectedTemplateKey === "custom" ? (openBlock(), createElementBlock(
            "span",
            _hoisted_12$1,
            toDisplayString($setup.t("superuser.driver_access.advanced")),
            1
            /* TEXT */
          )) : createCommentVNode("v-if", true)
        ],
        2
        /* CLASS */
      )) : createCommentVNode("v-if", true)
    ])),
    $setup.activeTemplate && $setup.selectedTemplateKey !== "custom" ? (openBlock(), createElementBlock("div", _hoisted_13$1, [
      createBaseVNode(
        "strong",
        null,
        toDisplayString($setup.templateLabel($setup.activeTemplate.key, $setup.activeTemplate.label)),
        1
        /* TEXT */
      ),
      createBaseVNode(
        "p",
        null,
        toDisplayString($setup.templateDescription($setup.activeTemplate)),
        1
        /* TEXT */
      )
    ])) : createCommentVNode("v-if", true),
    $setup.showAdvanced ? (openBlock(), createElementBlock("div", _hoisted_14$1, [
      (openBlock(), createElementBlock(
        Fragment,
        null,
        renderList($setup.LEGACY_PERMISSION_GROUPS, (group) => {
          return createBaseVNode("div", {
            key: group.key,
            class: "box"
          }, [
            createBaseVNode(
              "h3",
              _hoisted_15$1,
              toDisplayString($setup.groupLabel(group.key)),
              1
              /* TEXT */
            ),
            createBaseVNode("div", _hoisted_16$1, [
              (openBlock(true), createElementBlock(
                Fragment,
                null,
                renderList(group.capabilities, (capability) => {
                  return openBlock(), createElementBlock("div", {
                    key: capability,
                    class: "column is-6"
                  }, [
                    createVNode($setup["BCheckbox"], {
                      "model-value": $setup.selectedPermissions.includes(capability),
                      "data-testid": `permission-node-checkbox-${capability}`,
                      "onUpdate:modelValue": (checked) => $setup.togglePermission(capability, !!checked),
                      onInput: (checked) => $setup.togglePermission(capability, !!checked)
                    }, {
                      default: withCtx(() => [
                        createTextVNode(
                          toDisplayString($setup.permissionLabel(capability)),
                          1
                          /* TEXT */
                        )
                      ]),
                      _: 2
                      /* DYNAMIC */
                    }, 1032, ["model-value", "data-testid", "onUpdate:modelValue", "onInput"])
                  ]);
                }),
                128
                /* KEYED_FRAGMENT */
              ))
            ])
          ]);
        }),
        64
        /* STABLE_FRAGMENT */
      ))
    ])) : createCommentVNode("v-if", true)
  ]);
}
const SubuserGrantPermissionNodes = /* @__PURE__ */ _export_sfc(_sfc_main$5, [["render", _sfc_render$2], ["__scopeId", "data-v-a47396e4"], ["__file", "SubuserGrantPermissionNodes.vue"]]);

/**
 * The SubuserGrants object
 */
const SubuserGrants = {
  meta: {
    title: "Underbrugertilladelser",
    icon: "fas fa-user-shield",
    description: "Oversigt over underbrugertilladelser",
    endpoint: "/subusers/grants",
    labels: {
      single: "underbrugertilladelse",
      multiple: "underbrugertilladelser"
    }
  },
  columns: {
    id: {
      label: "ID",
      type: "number",
      sortable: true,
      creation: {
        required: false
      }
    },
    billing_customer_number: {
      label: "Kundenummer",
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
    subuser: {
      label: "Bruger",
      type: "number",
      sortable: true,
      creation: {
        required: true
      }
    },
    enabled: {
      label: "Aktiveret",
      type: "boolean",
      sortable: true,
      creation: {
        required: false
      }
    },
    note: {
      label: "Note",
      type: "text",
      sortable: true,
      creation: {
        required: false
      }
    },
    permissions: {
      label: "Tilladelser",
      type: "array",
      sortable: false,
      creation: {
        required: false
      }
    },
    created_at: {
      label: "Oprettet",
      type: "datetime",
      sortable: true,
      creation: {
        required: false
      }
    },
    updated_at: {
      label: "Opdateret",
      type: "datetime",
      sortable: true,
      creation: {
        required: false
      }
    },
    deleted_at: {
      label: "Slettet",
      type: "datetime",
      sortable: true,
      creation: {
        required: false
      }
    },
  },
  set: {
    enabled: async (id, enabled) => {
      return ObjectsGlobal.set.column(
          SubuserGrants.meta.endpoint,
          id,
          "enabled",
          enabled
      )
    },
    note: async (id, note) => {
      return ObjectsGlobal.set.column(
          SubuserGrants.meta.endpoint,
          id,
          "note",
          note
      )
    },
    permissions: async (id, permissions) => {
      return ObjectsGlobal.set.column(
          SubuserGrants.meta.endpoint,
          id,
          "permissions",
          permissions
      )
    }
  },
  functions: {
    getPermissionNodes: async () => {
      return ObjectsGlobal.get.objects("/subusers/permission-nodes");
    },
    getPermissionTemplates: async () => {
      return ObjectsGlobal.get.objects("/subusers/permission-templates");
    },
    showPermissionEditForm: async (grant, refreshCallback, options = {}) => {
      const container = document.createElement("div");
      container.id = "permission-edit-container";

      const permissionsRef = ref(grant.permissions || []);
      const accessRef = ref({
        permission_template_key: grant.permission_template_key || "custom",
        permissions: grant.permissions || [],
      });
      const app = createApp({
        render() {
          return h(SubuserGrantPermissionNodes, {
            grant: grant,
            permissions: permissionsRef.value,
            templateKey: accessRef.value.permission_template_key,
            allowAdvanced: Boolean(options.allowAdvanced),
            "onUpdate:permissions": (newPermissions) => {
              permissionsRef.value = newPermissions;
            },
            "onUpdate:access": (newAccess) => {
              accessRef.value = newAccess;
              permissionsRef.value = newAccess.permissions || [];
            }
          });
        }
      });

      const result = await Swal.fire({
        title: "Rediger tilladelser",
        html: container,
        width: "80%",
        showCloseButton: true,
        showConfirmButton: true,
        showCancelButton: true,
        confirmButtonText: "Gem",
        cancelButtonText: "Annuller",
        preConfirm: async () => {
          try {
            const accessPayload = accessRef.value?.permission_template_key
              && accessRef.value.permission_template_key !== "custom"
              ? { permission_template_key: accessRef.value.permission_template_key }
              : { permissions: permissionsRef.value };

            if (typeof options.saveAccess === "function") {
              await options.saveAccess(accessPayload);
            } else if (typeof options.savePermissions === "function") {
              await options.savePermissions(permissionsRef.value);
            } else {
              await authenticatedRequest(
                SubuserGrants.meta.endpoint,
                "PUT",
                { id: grant.id, ...accessPayload },
                ObjectsGlobal.errorHandler.handleError
              );
            }
            grant.permissions = [...permissionsRef.value];
            grant.permission_template_key = accessRef.value?.permission_template_key || "custom";
            return accessPayload;
          } catch (_error) {
            Swal.showValidationMessage("Kunne ikke gemme tilladelserne.");
            return false;
          }
        },
        didOpen: () => {
          app.mount(container);
        },
        willClose: () => {
          app.unmount();
        }
      });

      if (result.isConfirmed && refreshCallback && typeof refreshCallback === "function") {
        refreshCallback();
      }
    }
  },
  get: {
    all: async () => {
      return ObjectsGlobal.get.objects(SubuserGrants.meta.endpoint);
    },
    single: async (id) => {
      return ObjectsGlobal.get.object(SubuserGrants.meta.endpoint, parseInt(id));
    }
  },
  /**
   * Show the edit object field form
   * @param id
   * @param column
   * @param value
   * @param onAfterSubmit
   * @returns {Promise<SweetAlertResult<Awaited<any>>>}
   */
  showEditObjectFieldForm: (id, column, value, onAfterSubmit = null) => {
    return ObjectsGlobal.showEditObjectFieldForm(
        SubuserGrants,
        id,
        column,
        value,
        onAfterSubmit
    );
  }
};

const _sfc_main$4 = {};
const SubuserGrants_default = /*#__PURE__*/_export_sfc(_sfc_main$4, [['__file',"SubuserGrants.vue"]]);

const SUBUSER_PASSWORD_MIN_LENGTH = 8;
const SUBUSER_PASSWORD_MAX_LENGTH = 255;
const SUBUSER_PASSWORD_COMPLEXITY_MESSAGE =
  "Password must contain at least one uppercase letter, one lowercase letter, and one number.";
const SUBUSER_PASSWORD_HELP_TEXT =
  "Your password must be at least 8 characters and include uppercase, lowercase, and a number.";

const SUBUSER_PASSWORD_PATTERN = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/;

const getSubuserPasswordPolicyError = (password) => {
  const value = String(password || "");

  if (value.length < SUBUSER_PASSWORD_MIN_LENGTH) {
    return "Password must be at least 8 characters long.";
  }

  if (value.length > SUBUSER_PASSWORD_MAX_LENGTH) {
    return "Password must be at most 255 characters long.";
  }

  if (!SUBUSER_PASSWORD_PATTERN.test(value)) {
    return SUBUSER_PASSWORD_COMPLEXITY_MESSAGE;
  }

  return null;
};

const t = (key, values = undefined) => i18n.global.t(key, values);
let qrCodeModulePromise;

const loadQRCodeModule = () => {
  if (!qrCodeModulePromise) {
    qrCodeModulePromise = __vitePreload(() => import('./browser-CIlJ6MKH.js').then(n => n.b),true              ?[]:void 0);
  }

  return qrCodeModulePromise;
};

const escapeHtml = (value) => String(value ?? "")
  .replace(/&/g, "&amp;")
  .replace(/</g, "&lt;")
  .replace(/>/g, "&gt;")
  .replace(/"/g, "&quot;")
  .replace(/'/g, "&#039;");

const apiErrorMessage = (error, fallback) =>
  error?.response?.data?.data?.message || error?.response?.data?.message || error?.message || fallback;

const absoluteLoginLink = (path) => {
  try {
    return new URL(path, window.location.origin).toString();
  } catch (_error) {
    return String(path || "");
  }
};

const directLoginPayload = (context = {}) => ({
  ...(context.customer_number ? { customer_number: context.customer_number } : {}),
  ...(context.grant_id ? { grant_id: context.grant_id } : {}),
});

const driverContactText = (key, values = undefined) =>
  t(`templates.generated.compat.superuser.driver_contact.${key}`, values);

const showDeliveryFeedback = async (response, options = {}) => {
  const payload = response?.data?.data || response?.data || {};
  const delivery = payload.delivery || {};
  const sent = delivery.status === "sent";

  await Swal.fire({
    title: sent
      ? (options.sentTitle || driverContactText("link_sent_title"))
      : (options.notSentTitle || driverContactText("link_not_sent_title")),
    text: delivery.message || (sent
      ? driverContactText("link_sent_default")
      : driverContactText("link_not_sent_default")),
    icon: sent ? "success" : "warning",
    confirmButtonText: driverContactText("close"),
  });
};

const copyText = async (text) => {
  if (navigator.clipboard?.writeText) {
    try {
      await navigator.clipboard.writeText(text);
      return;
    } catch (_error) {
      // Fall back below when clipboard permission is denied.
    }
  }

  const textarea = document.createElement("textarea");
  textarea.value = text;
  textarea.setAttribute("readonly", "");
  textarea.style.position = "fixed";
  textarea.style.opacity = "0";
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  textarea.remove();
};

const buildAdminContactFormHtml = (subuser = {}) => `
  <div class="subuser-form">
    <div class="field">
      <label class="label" for="subuser-admin-email">E-mail</label>
      <div class="control">
        <input id="subuser-admin-email" class="input" type="email" value="${escapeHtml(subuser.email || "")}" placeholder="chauffor@example.com" />
      </div>
    </div>
    <div class="columns">
      <div class="column is-4">
        <div class="field">
          <label class="label" for="subuser-admin-phone-country-code">Landekode</label>
          <div class="control">
            <input id="subuser-admin-phone-country-code" class="input" type="number" inputmode="numeric" value="${escapeHtml(subuser.phone_country_code || 45)}" />
          </div>
        </div>
      </div>
      <div class="column">
        <div class="field">
          <label class="label" for="subuser-admin-phone">Telefon</label>
          <div class="control">
            <input id="subuser-admin-phone" class="input" type="number" inputmode="numeric" value="${escapeHtml(subuser.phone || "")}" />
          </div>
        </div>
      </div>
    </div>
  </div>
`;

const readAdminContactFormValues = () => {
  const email = document.getElementById("subuser-admin-email")?.value?.trim() || "";
  const phoneCountryCode = document.getElementById("subuser-admin-phone-country-code")?.value?.trim() || "";
  const phone = document.getElementById("subuser-admin-phone")?.value?.trim() || "";

  if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    Swal.showValidationMessage("E-mail er ugyldig.");
    return null;
  }

  if (!/^\d{1,3}$/.test(phoneCountryCode)) {
    Swal.showValidationMessage("Landekode skal være 1-3 cifre.");
    return null;
  }

  if (!/^\d{4,15}$/.test(phone)) {
    Swal.showValidationMessage("Telefon skal være 4-15 cifre.");
    return null;
  }

  return {
    email: email || null,
    phone_country_code: Number.parseInt(phoneCountryCode, 10),
    phone: Number.parseInt(phone, 10),
  };
};

const buildPasswordFormHtml = () => `
  <div class="subuser-form">
    <div class="field">
      <label class="label" for="subuser-admin-password">Ny adgangskode</label>
      <div class="control">
        <input id="subuser-admin-password" class="input" type="password" autocomplete="new-password" />
      </div>
      <p class="help">Minimum 8 tegn med store bogstaver, små bogstaver og tal.</p>
    </div>
    <div class="field">
      <label class="label" for="subuser-admin-password-confirm">Gentag adgangskode</label>
      <div class="control">
        <input id="subuser-admin-password-confirm" class="input" type="password" autocomplete="new-password" />
      </div>
    </div>
  </div>
`;

const buildAccessTemplateOptions = (templates = [], selectedKey = "driver") => templates
  .filter((template) => template?.key && template.key !== "custom")
  .map((template) => `
    <option value="${escapeHtml(template.key)}" ${template.key === selectedKey ? "selected" : ""}>
      ${escapeHtml(template.label || template.key)}
    </option>
  `)
  .join("");

const buildInviteFormHtml = (defaults = {}, options = {}) => `
  <div class="subuser-form">
    ${options.includeCustomerNumber ? `
      <div class="field">
        <label class="label">Kundenummer</label>
        <div class="control">
          <input id="subuser-form-customer-number" class="input" type="number" inputmode="numeric" value="${escapeHtml(defaults.customer_number || defaults.customerNumber || "")}" placeholder="Kundens kundenummer" />
        </div>
      </div>
    ` : ""}
    <div class="field">
      <label class="label">Navn</label>
      <div class="control">
        <input id="subuser-form-name" class="input" type="text" value="${escapeHtml(defaults.name || "")}" placeholder="Chaufførens navn" />
      </div>
    </div>
    <div class="columns">
      <div class="column is-4">
        <div class="field">
          <label class="label">Landekode</label>
          <div class="control">
            <input id="subuser-form-phone-country-code" class="input" type="number" inputmode="numeric" value="${escapeHtml(defaults.phone_country_code || defaults.phoneCountryCode || 45)}" />
          </div>
        </div>
      </div>
      <div class="column">
        <div class="field">
          <label class="label">Telefon</label>
          <div class="control">
            <input id="subuser-form-phone" class="input" type="number" inputmode="numeric" value="${escapeHtml(defaults.phone || "")}" placeholder="Telefonnummer" />
          </div>
        </div>
      </div>
    </div>
    <p class="help">
      Chaufføren ejer selv sin konto. E-mail, brugernavn og øvrige profiloplysninger udfyldes af chaufføren ved accept.
    </p>
    <div class="field mt-4">
      <label class="label">${escapeHtml(t("superuser.driver_access.form_label"))}</label>
      <div class="control">
        <div class="select is-fullwidth">
          <select id="subuser-form-permission-template">
            ${buildAccessTemplateOptions(options.permissionTemplates || [], defaults.permission_template_key || "driver")}
          </select>
        </div>
      </div>
      <p class="help">${escapeHtml(t("superuser.driver_access.form_help"))}</p>
    </div>
  </div>
`;

const readInviteFormValues = (options = {}) => {
  const customerNumberRaw = document.getElementById("subuser-form-customer-number")?.value?.trim() || "";
  const name = document.getElementById("subuser-form-name")?.value?.trim() || "";
  const phoneCountryCodeRaw = document.getElementById("subuser-form-phone-country-code")?.value?.trim() || "";
  const phoneRaw = document.getElementById("subuser-form-phone")?.value?.trim() || "";
  const permissionTemplateKey = document.getElementById("subuser-form-permission-template")?.value?.trim() || "driver";

  if (options.includeCustomerNumber && !/^\d+$/.test(customerNumberRaw)) {
    Swal.showValidationMessage("Kundenummer skal udfyldes.");
    return null;
  }

  if (name.length < 3) {
    Swal.showValidationMessage("Navn skal være mindst 3 tegn.");
    return null;
  }

  if (!/^\d{1,3}$/.test(phoneCountryCodeRaw)) {
    Swal.showValidationMessage("Landekode skal være 1-3 cifre.");
    return null;
  }

  if (!/^\d{4,15}$/.test(phoneRaw)) {
    Swal.showValidationMessage("Telefon skal være 4-15 cifre.");
    return null;
  }

  return {
    ...(options.includeCustomerNumber ? { customer_number: Number.parseInt(customerNumberRaw, 10) } : {}),
    name,
    phone_country_code: Number.parseInt(phoneCountryCodeRaw, 10),
    phone: Number.parseInt(phoneRaw, 10),
    permission_template_key: permissionTemplateKey,
  };
};

const showInviteFeedback = async (response) => {
  const invite = response?.data?.data?.invite || response?.data?.invite || {};
  const delivery = invite.delivery || {};
  const setupLink = invite.setup_link;
  const statusText = delivery.status === "sent"
    ? "Invitationen blev sendt på SMS."
    : delivery.status === "not_required"
      ? (delivery.message || "Chaufførkontoen er allerede accepteret. Kun adgangen blev opdateret.")
      : (delivery.message || "SMS blev ikke sendt. Brug opsætningslinket nedenfor.");

  const html = `
    <p>${escapeHtml(statusText)}</p>
    ${setupLink ? `<p class="mt-4"><a href="${escapeHtml(setupLink)}" target="_blank" rel="noopener noreferrer">${escapeHtml(setupLink)}</a></p>` : ""}
  `;

  await Swal.fire({
    title: "Chauffør oprettet",
    icon: "success",
    html,
    confirmButtonText: "Luk",
  });
};

const submitInviteForm = async ({ title, confirmButtonText, defaults = {}, endpoint, method, payloadBuilder, includeCustomerNumber = false, permissionTemplates = [] }) => {
  const result = await Swal.fire({
    title,
    html: buildInviteFormHtml(defaults, { includeCustomerNumber, permissionTemplates }),
    width: 640,
    focusConfirm: false,
    showCancelButton: true,
    confirmButtonText,
    cancelButtonText: "Annuller",
    preConfirm: async () => {
      const values = readInviteFormValues({ includeCustomerNumber });
      if (!values) {
        return false;
      }

      Swal.showLoading();

      try {
        const payload = payloadBuilder(values);
        const response = await authenticatedRequest(endpoint, method, payload);
        return response;
      } catch (error) {
        Swal.showValidationMessage(error?.response?.data?.data?.message || error?.response?.data?.message || "Kunne ikke gemme chaufføren.");
        return false;
      }
    },
  });

  return result.isConfirmed ? result.value : null;
};

const Subusers = {
  meta: {
    title: "Chauffører",
    icon: "fas fa-id-card",
    description: "Administrer chauffører og deres adgang",
    endpoint: "/subusers",
  },
  functions: {
    permissionSummary(permissions = [], templateKey = null, permissionGroups = []) {
      const templateLabel = (key) => t(`superuser.driver_access.templates.${key}.label`);
      const customSummary = (summary) => t("superuser.driver_access.summary.custom_summary", { summary });

      if (templateKey && templateKey !== "custom") {
        return templateLabel(templateKey);
      }

      if (Array.isArray(permissionGroups) && permissionGroups.length > 0) {
        const labels = permissionGroups
          .map((group) => t(`superuser.driver_access.groups.${group.key}`))
          .filter(Boolean);
        return customSummary(labels.join(", "));
      }

      if (!Array.isArray(permissions) || permissions.length === 0) {
        return t("superuser.driver_access.summary.no_permissions");
      }

      const normalized = permissions.filter(Boolean);
      return customSummary(t("superuser.driver_access.summary.permission_count", { count: normalized.length }));
    },
    async updateAdminProfile(subuserId, payload) {
      return authenticatedRequest(`/superuser/subusers/${encodeURIComponent(subuserId)}`, "PATCH", payload);
    },
    async setAdminPassword(subuserId, password) {
      return authenticatedRequest(`/superuser/subusers/${encodeURIComponent(subuserId)}/password`, "POST", { password });
    },
    async generateAdminLoginLink(subuserId, context = {}) {
      return authenticatedRequest(
        `/superuser/subusers/${encodeURIComponent(subuserId)}/login-link`,
        "POST",
        directLoginPayload(context)
      );
    },
    async setAdminVerificationState(subuserId, channel, verified) {
      try {
        return await authenticatedRequest(
          `/superuser/subusers/${encodeURIComponent(subuserId)}/verification/${encodeURIComponent(channel)}`,
          "PATCH",
          { verified: Boolean(verified) }
        );
      } catch (error) {
        await Swal.fire({
          title: driverContactText("verification_update_failed_title"),
          text: apiErrorMessage(error, driverContactText("verification_update_failed")),
          icon: "error",
          confirmButtonText: driverContactText("close"),
        });
        throw error;
      }
    },
    async sendAdminPasswordGuideLink(subuserId, channel, context = {}) {
      try {
        const response = await authenticatedRequest(
          `/superuser/subusers/${encodeURIComponent(subuserId)}/password-guide/${encodeURIComponent(channel)}/send`,
          "POST",
          directLoginPayload(context)
        );
        await showDeliveryFeedback(response, {
          sentTitle: driverContactText("password_guide_sent_title"),
          notSentTitle: driverContactText("password_guide_not_sent_title"),
        });
        return response;
      } catch (error) {
        await Swal.fire({
          title: driverContactText("password_guide_failed_title"),
          text: apiErrorMessage(error, driverContactText("link_send_failed")),
          icon: "error",
          confirmButtonText: driverContactText("close"),
        });
        throw error;
      }
    },
    async sendAdminLoginLink(subuserId, channel, context = {}) {
      try {
        const response = await authenticatedRequest(
          `/superuser/subusers/${encodeURIComponent(subuserId)}/login-link/${encodeURIComponent(channel)}/send`,
          "POST",
          directLoginPayload(context)
        );
        await showDeliveryFeedback(response, {
          sentTitle: driverContactText("login_link_sent_title"),
          notSentTitle: driverContactText("login_link_not_sent_title"),
        });
        return response;
      } catch (error) {
        await Swal.fire({
          title: driverContactText("login_link_failed_title"),
          text: apiErrorMessage(error, driverContactText("link_send_failed")),
          icon: "error",
          confirmButtonText: driverContactText("close"),
        });
        throw error;
      }
    },
    async resendVerificationCode(subuser, channel, refreshCallback = null, options = {}) {
      const superuser = Boolean(options.superuser);
      const endpoint = superuser
        ? `/superuser/subusers/${encodeURIComponent(subuser.id)}/verification/${encodeURIComponent(channel)}/send`
        : `/subusers/${encodeURIComponent(subuser.id)}/verification/${encodeURIComponent(channel)}/send`;

      try {
        const response = await authenticatedRequest(endpoint, "POST");
        const payload = response?.data?.data || response?.data || {};
        const delivery = payload.delivery || {};
        const channelLabel = channel === "email" ? "e-mail" : "telefon";

        await Swal.fire({
          title: delivery.status === "sent" ? "Kode sendt" : "Kode kunne ikke sendes",
          text: delivery.message || (delivery.status === "sent"
            ? `Verifikationskode er sendt til chaufførens ${channelLabel}.`
            : `Verifikationskode kunne ikke sendes til chaufførens ${channelLabel}.`),
          icon: delivery.status === "sent" ? "success" : "warning",
          confirmButtonText: "Luk",
        });

        if (typeof refreshCallback === "function") {
          await refreshCallback();
        }

        return response;
      } catch (error) {
        await Swal.fire({
          title: "Kode kunne ikke sendes",
          text: apiErrorMessage(error, "Der opstod en fejl."),
          icon: "error",
          confirmButtonText: "Luk",
        });
        throw error;
      }
    },
    async showEditNameForm(subuser, refreshCallback = null) {
      const result = await Swal.fire({
        title: "Redigér chaufførnavn",
        input: "text",
        inputLabel: "Navn",
        inputValue: subuser?.name || "",
        showCancelButton: true,
        confirmButtonText: "Gem",
        cancelButtonText: "Annuller",
        inputValidator: (value) => {
          const name = String(value || "").trim();
          if (name.length < 3) {
            return "Navn skal være mindst 3 tegn.";
          }
          if (name.length > 255) {
            return "Navn må højst være 255 tegn.";
          }
          return null;
        },
        preConfirm: async (value) => {
          try {
            return await this.updateAdminProfile(subuser.id, { name: String(value || "").trim() });
          } catch (error) {
            Swal.showValidationMessage(apiErrorMessage(error, "Kunne ikke gemme navnet."));
            return false;
          }
        },
      });

      if (result.isConfirmed && typeof refreshCallback === "function") {
        await refreshCallback();
      }

      return result.value || null;
    },
    async showEditContactForm(subuser, refreshCallback = null) {
      const result = await Swal.fire({
        title: "Redigér kontaktoplysninger",
        html: buildAdminContactFormHtml(subuser),
        width: 640,
        focusConfirm: false,
        showCancelButton: true,
        confirmButtonText: "Gem",
        cancelButtonText: "Annuller",
        preConfirm: async () => {
          const values = readAdminContactFormValues();
          if (!values) {
            return false;
          }

          try {
            return await this.updateAdminProfile(subuser.id, values);
          } catch (error) {
            Swal.showValidationMessage(apiErrorMessage(error, "Kunne ikke gemme kontaktoplysningerne."));
            return false;
          }
        },
      });

      if (result.isConfirmed && typeof refreshCallback === "function") {
        await refreshCallback();
      }

      return result.value || null;
    },
    async showSetPasswordForm(subuser, refreshCallback = null) {
      const result = await Swal.fire({
        title: "Sæt adgangskode",
        html: buildPasswordFormHtml(),
        width: 560,
        focusConfirm: false,
        showCancelButton: true,
        confirmButtonText: "Gem",
        cancelButtonText: "Annuller",
        preConfirm: async () => {
          const password = document.getElementById("subuser-admin-password")?.value || "";
          const passwordConfirm = document.getElementById("subuser-admin-password-confirm")?.value || "";
          const policyError = getSubuserPasswordPolicyError(password);

          if (policyError) {
            Swal.showValidationMessage(policyError);
            return false;
          }

          if (password !== passwordConfirm) {
            Swal.showValidationMessage("Adgangskoderne matcher ikke.");
            return false;
          }

          try {
            return await this.setAdminPassword(subuser.id, password);
          } catch (error) {
            Swal.showValidationMessage(apiErrorMessage(error, "Kunne ikke gemme adgangskoden."));
            return false;
          }
        },
      });

      if (result.isConfirmed && typeof refreshCallback === "function") {
        await refreshCallback();
      }

      return result.value || null;
    },
    async showDirectLoginQrCode(subuser, context = {}) {
      try {
        const response = await this.generateAdminLoginLink(subuser.id, context);
        const payload = response?.data?.data || response?.data || {};
        const loginPath = String(payload.login_path || "");
        if (!loginPath) {
          throw new Error("Loginlink mangler i API-svaret.");
        }

        const loginUrl = absoluteLoginLink(loginPath);
        const { toDataURL } = await loadQRCodeModule();
        const qrSrc = await toDataURL(loginUrl, { margin: 2, width: 240 });

        return Swal.fire({
          title: "Direkte login",
          html: `
            <div class="has-text-centered">
              <img src="${escapeHtml(qrSrc)}" alt="Direkte login QR-kode" width="240" height="240" />
              <input id="subuser-direct-login-link" class="input mt-4" type="text" readonly value="${escapeHtml(loginUrl)}" />
            </div>
          `,
          showCancelButton: true,
          confirmButtonText: "Kopiér link",
          cancelButtonText: "Luk",
          preConfirm: async () => {
            await copyText(loginUrl);
            return loginUrl;
          },
        });
      } catch (error) {
        await Swal.fire({
          title: "Kunne ikke oprette loginlink",
          text: apiErrorMessage(error, "Der opstod en fejl."),
          icon: "error",
          confirmButtonText: "Luk",
        });
        return null;
      }
    },
    async showInviteForm(refreshCallback = null, options = {}) {
      const superuser = Boolean(options.superuser);
      const userId = options.userId || null;
      let permissionTemplates = [];
      try {
        const accessResponse = await authenticatedRequest("/subusers/permission-templates", "GET");
        const accessModel = accessResponse?.data?.data || accessResponse?.data || {};
        permissionTemplates = Array.isArray(accessModel?.templates) ? accessModel.templates : [];
      } catch (_error) {
        permissionTemplates = [];
      }
      const response = await submitInviteForm({
        title: "Invitér chauffør",
        confirmButtonText: "Send invitation",
        endpoint: userId
          ? `/superuser/users/${encodeURIComponent(userId)}/subusers/invite`
          : superuser
            ? "/superuser/subusers/invite"
            : "/subusers/invite",
        method: "POST",
        payloadBuilder: (values) => values,
        includeCustomerNumber: superuser && !userId,
        permissionTemplates,
      });

      if (!response) {
        return null;
      }

      await showInviteFeedback(response);
      if (typeof refreshCallback === "function") {
        await refreshCallback();
      }

      return response;
    },
    async resendInvite(subuser, refreshCallback = null, options = {}) {
      const superuser = Boolean(options.superuser);
      const userId = options.userId || null;
      try {
        const endpoint = userId
          ? `/superuser/users/${encodeURIComponent(userId)}/subusers/${encodeURIComponent(subuser.id)}/invite/resend`
          : superuser ? "/superuser/subusers/invite/resend" : "/subusers/invite/resend";
        const response = await authenticatedRequest(
          endpoint,
          "POST",
          userId
            ? {}
            : {
                id: subuser.id,
                ...(subuser.grant_id ? { grant_id: subuser.grant_id } : {}),
                ...(superuser && subuser.customer_number ? { customer_number: subuser.customer_number } : {}),
              }
        );
        await showInviteFeedback(response);
        if (typeof refreshCallback === "function") {
          await refreshCallback();
        }
        return response;
      } catch (error) {
        await Swal.fire({
          title: "Kunne ikke gensende invitation",
          text: error?.response?.data?.data?.message || error?.response?.data?.message || "Der opstod en fejl.",
          icon: "error",
          confirmButtonText: "Luk",
        });
        throw error;
      }
    },
  },
};

const _sfc_main$3 = {};
const Subusers_default = /*#__PURE__*/_export_sfc(_sfc_main$3, [['__file',"Subusers.vue"]]);

const RELEASE_RUNTIME_GLOBAL_KEY = "__TRUCKWASH_RELEASE_RUNTIME__";
const RELEASE_CHANNEL_SELECTION_STORAGE_KEY$1 = "release_channel_selected_slug";
const RELEASE_SOURCE_OVERRIDE_STORAGE_KEY = "release_source_override";
const RELEASE_BOOTSTRAP_REVISION = "2026-06-08-regular-frontend-dynamic-api";
const RELEASE_SOURCE_MODES = Object.freeze({
  LOCAL: "local",
  DEPLOYMENT: "deployment",
  AUTO: "auto",
});

const normalizeReleaseChannelSlug$1 = (value) =>
  String(value || "")
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9_-]/g, "-")
    .replace(/-+/g, "-")
    .replace(/^-|-$/g, "")
    .slice(0, 64);

const normalizeBaseUrl = (value) =>
  String(value || "")
    .trim()
    .replace(/\/+$/, "");

const normalizeReleaseSourceValue = (value) => {
  const normalized = String(value || "")
    .trim()
    .toLowerCase();
  return Object.values(RELEASE_SOURCE_MODES).includes(normalized) ? normalized : "";
};

const normalizeReleaseSourceMode = (value, fallback = RELEASE_SOURCE) =>
  normalizeReleaseSourceValue(value) || normalizeReleaseSourceValue(fallback) || RELEASE_SOURCE_MODES.DEPLOYMENT;

const browserOrigin = () => {
  if (typeof window !== "undefined" && window.location?.origin) {
    return window.location.origin;
  }
  return "http://localhost";
};

const resolveRuntimeBaseUrl = (value) => {
  const baseUrl = normalizeBaseUrl(value);
  if (!baseUrl) {
    return "";
  }
  if (/^https?:\/\//i.test(baseUrl)) {
    return baseUrl;
  }
  return new URL(`${baseUrl.replace(/^\/+/, "")}/`, `${browserOrigin()}/`).href.replace(/\/+$/, "");
};

const browserStorage = () => {
  if (typeof window === "undefined") {
    return null;
  }
  try {
    return window.localStorage || null;
  } catch {
    return null;
  }
};

const readSelectedReleaseChannel = () =>
  normalizeReleaseChannelSlug$1(browserStorage()?.getItem(RELEASE_CHANNEL_SELECTION_STORAGE_KEY$1) || "");

const readReleaseSourceOverride = () => {
  const override = normalizeReleaseSourceValue(browserStorage()?.getItem(RELEASE_SOURCE_OVERRIDE_STORAGE_KEY) || "");
  return override === RELEASE_SOURCE_MODES.AUTO ? "" : override;
};

const isReleaseSourceOverrideAvailable = ({ isDev = IS_DEV, releaseSourceEnv = RELEASE_SOURCE_ENV } = {}) =>
  Boolean(isDev) && !normalizeReleaseSourceValue(releaseSourceEnv);

const setReleaseSourceOverride = (value) => {
  const source = normalizeReleaseSourceValue(value);
  if (!source) {
    return "";
  }

  try {
    browserStorage()?.setItem(RELEASE_SOURCE_OVERRIDE_STORAGE_KEY, source);
  } catch {
    // Storage is optional; callers can still fall back to the current runtime.
  }
  return source;
};

const resolveReleaseSourceMode = (configuredSource = RELEASE_SOURCE, { allowStorageOverride = false } = {}) => {
  const sourceMode = normalizeReleaseSourceMode(configuredSource);
  if (sourceMode !== RELEASE_SOURCE_MODES.AUTO) {
    return allowStorageOverride ? readReleaseSourceOverride() || sourceMode : sourceMode;
  }
  return readReleaseSourceOverride() || RELEASE_SOURCE_MODES.AUTO;
};

const selectedReleaseChannelSlug$1 = (selectedChannel) => {
  if (selectedChannel !== undefined && selectedChannel !== null) {
    return normalizeReleaseChannelSlug$1(selectedChannel);
  }
  return readSelectedReleaseChannel();
};

const buildRuntimeHeaders = (selectedChannel) => {
  const storage = browserStorage();
  const headers = {
    Accept: "application/json",
    ...buildReleaseHeaders({ channelSlug: selectedReleaseChannelSlug$1(selectedChannel) }),
  };
  const token = storage?.getItem("token");
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }
  const selectedCustomerNumber = storage?.getItem("selected_customer_number");
  if (storage?.getItem("is_subuser") === "true" && selectedCustomerNumber) {
    headers["X-Customer-Number"] = selectedCustomerNumber;
  }
  return headers;
};

const runtimeApiUrl = (apiBaseUrl = RELEASE_MANAGER_CONTROL_API_URL || API_URL, options = {}) => {
  const selectedChannel = selectedReleaseChannelSlug$1(options?.selectedChannel);
  const runtimeBaseUrl = resolveRuntimeBaseUrl(apiBaseUrl || API_URL);
  const url = new URL("release/runtime", `${runtimeBaseUrl}/`);
  if (selectedChannel) {
    url.searchParams.set("release_channel", selectedChannel);
  }
  return url.href;
};

const parseJsonResponse = async (response, label) => {
  if (typeof response?.text === "function") {
    const body = await response.text();
    try {
      return JSON.parse(body);
    } catch (error) {
      const prefix = body.trim().slice(0, 120);
      const details = prefix ? ` Body starts with: ${prefix}` : "";
      throw new Error(`${label} returned invalid JSON.${details}`, { cause: error });
    }
  }

  return response?.json?.();
};

const fetchReleaseRuntime = async ({
  fetchFn = globalThis.fetch,
  apiBaseUrl = RELEASE_MANAGER_CONTROL_API_URL || API_URL,
  selectedChannel,
} = {}) => {
  if (typeof fetchFn !== "function") {
    return null;
  }

  const response = await fetchFn(runtimeApiUrl(apiBaseUrl, { selectedChannel }), {
    method: "GET",
    headers: buildRuntimeHeaders(selectedChannel),
    credentials: "omit",
    cache: "no-store",
  });
  if (!response?.ok) {
    throw new Error(`Release runtime request failed with HTTP ${response?.status || 0}.`);
  }
  const payload = await parseJsonResponse(response, "Release runtime");
  return payload?.data || payload || null;
};

const shouldLoadRemoteRelease = () => false;

const unavailableRuntime = (runtime, missing) => ({
  ...(runtime || {}),
  availability: {
    ...(runtime?.availability || {}),
    configured: false,
    missing: Array.from(new Set([...(runtime?.availability?.missing || []), missing])),
    status: "unconfigured",
  },
});

const runtimeWithSource = (runtime, source, requestedSource = source) => ({
  ...(runtime || {}),
  source,
  requested_source: requestedSource,
});

const localReleaseRuntime = ({ requestedSource = RELEASE_SOURCE_MODES.LOCAL, missing = [] } = {}) => {
  const missingValues = Array.from(new Set((Array.isArray(missing) ? missing : []).filter(Boolean)));
  const apiBaseUrl = normalizeBaseUrl(API_URL || "/api") || "/api";
  const frontendBaseUrl = normalizeBaseUrl(browserOrigin());
  return {
    source: RELEASE_SOURCE_MODES.LOCAL,
    requested_source: requestedSource,
    bootstrap_revision: RELEASE_BOOTSTRAP_REVISION,
    generated_at: new Date().toISOString(),
    channel: {
      slug: "stable",
      name: "Local",
      default_channel: true,
      route_slug: "master",
    },
    available_channels: [],
    versions: {
      frontend: null,
      api: null,
      service_set: null,
      bundle_id: null,
      bundle: null,
    },
    frontend_base_url: frontendBaseUrl,
    api_base_url: apiBaseUrl,
    urls: {
      frontend_base_url: frontendBaseUrl,
      api_base_url: apiBaseUrl,
    },
    availability: {
      configured: missingValues.length === 0,
      missing: missingValues,
      status: missingValues.length === 0 ? "ready" : "unconfigured",
      explicit: true,
    },
  };
};

const unavailableSelectedRuntime = (
  missing,
  { source = RELEASE_SOURCE_MODES.LOCAL, requestedSource = source } = {}
) => {
  const selectedChannel = readSelectedReleaseChannel();
  if (!selectedChannel || selectedChannel === "stable") {
    return null;
  }

  return runtimeWithSource(
    unavailableRuntime(
      {
        channel: {
          slug: selectedChannel,
          name: selectedChannel,
          default_channel: false,
        },
        availability: {
          explicit: true,
        },
      },
      missing
    ),
    source,
    requestedSource
  );
};

const setReleaseRuntimeGlobal = (runtime) => {
  if (typeof window !== "undefined") {
    window[RELEASE_RUNTIME_GLOBAL_KEY] = runtime || null;
  }
  return runtime;
};

const bootstrapReleaseApp = async ({ loadLocalApp, fetchFn = globalThis.fetch, sourceMode } = {}) => {
  if (typeof loadLocalApp !== "function") {
    throw new Error("Release bootstrap requires a local app loader.");
  }

  const hasExplicitSourceMode = sourceMode !== undefined && sourceMode !== null && String(sourceMode).trim() !== "";
  const resolvedSourceMode = resolveReleaseSourceMode(sourceMode || RELEASE_SOURCE, {
    allowStorageOverride: isReleaseSourceOverrideAvailable() && !hasExplicitSourceMode,
  });

  let runtime = null;
  try {
    runtime = runtimeWithSource(
      await fetchReleaseRuntime({ fetchFn }),
      RELEASE_SOURCE_MODES.DEPLOYMENT,
      resolvedSourceMode
    );
    setReleaseRuntimeGlobal(runtime);
  } catch (error) {
    console.warn("Could not resolve release runtime before app bootstrap.", error);
    const unavailable =
      unavailableSelectedRuntime("release_runtime", {
        source: RELEASE_SOURCE_MODES.LOCAL,
        requestedSource: resolvedSourceMode,
      }) || localReleaseRuntime({ requestedSource: resolvedSourceMode, missing: ["release_runtime"] });
    if (unavailable) {
      setReleaseRuntimeGlobal(unavailable);
    }
  }

  return loadLocalApp();
};

const isPlainObject = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value));

const objectOrEmpty = (value) => (isPlainObject(value) ? value : {});

const arrayOrEmpty = (value) => (Array.isArray(value) ? value : []);

const normalizeEconomicCustomer = (value) => {
  if (Array.isArray(value)) {
    return value.find(isPlainObject) || null;
  }

  if (!isPlainObject(value) || Object.keys(value).length === 0) {
    return null;
  }

  return value;
};

const normalizeSessionPayload = (payload = {}) => {
  const data = objectOrEmpty(payload);
  const phone = objectOrEmpty(data.phone);
  const notifications = objectOrEmpty(data.notifications);
  const runtimeConfig = objectOrEmpty(data.runtime_config);
  const economicConfig = objectOrEmpty(runtimeConfig.economic);

  return {
    id: data.id ?? null,
    customer_number: data.customer_number ?? null,
    group_id: data.group_id ?? null,
    email: data.email ?? null,
    phone: {
      number: phone.number ?? null,
      country_code: phone.country_code ?? null,
    },
    notifications: {
      wash_certificate_email: notifications.wash_certificate_email ?? null,
      email_notifications_enabled: notifications.email_notifications_enabled ?? null,
      sms_notifications_enabled: notifications.sms_notifications_enabled ?? null,
      superuser_new_customer_email_notifications_enabled:
        notifications.superuser_new_customer_email_notifications_enabled ?? null,
    },
    created_at: data.created_at ?? null,
    updated_at: data.updated_at ?? null,
    display_name: data.display_name ?? null,
    permissions: arrayOrEmpty(data.permissions),
    economic_customer: normalizeEconomicCustomer(data.economic_customer),
    runtime_config: {
      economic: {
        transaction_draft_customer_number: economicConfig.transaction_draft_customer_number ?? null,
        default_distribution_department_id: economicConfig.default_distribution_department_id ?? null,
      },
      release: objectOrEmpty(runtimeConfig.release),
    },
  };
};

const RELEASE_CHANNEL_IGNORE_STORAGE_KEY = "release_channel_unavailable_ignore_until";
const RELEASE_CHANNEL_SWITCH_NOTICE_STORAGE_KEY = "release_channel_switch_notice_seen";
const RELEASE_CHANNEL_SELECTION_STORAGE_KEY = "release_channel_selected_slug";
const RELEASE_CHANNEL_IGNORE_MS = 5 * 60 * 1000;
const RELEASE_CHANNEL_CHECK_INTERVAL_MS = 10 * 1000;

const readIgnoreMap = () => {
  if (typeof window === "undefined") {
    return {};
  }

  try {
    const parsed = JSON.parse(window.localStorage.getItem(RELEASE_CHANNEL_IGNORE_STORAGE_KEY) || "{}");
    return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
  } catch {
    return {};
  }
};

const writeIgnoreMap = (map) => {
  if (typeof window === "undefined") {
    return;
  }

  try {
    window.localStorage.setItem(RELEASE_CHANNEL_IGNORE_STORAGE_KEY, JSON.stringify(map));
  } catch {
    // Ignore storage failures; the guard will simply remain active.
  }
};

const readSwitchNoticeMap = () => {
  if (typeof window === "undefined") {
    return {};
  }

  try {
    const parsed = JSON.parse(window.localStorage.getItem(RELEASE_CHANNEL_SWITCH_NOTICE_STORAGE_KEY) || "{}");
    return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
  } catch {
    return {};
  }
};

const writeSwitchNoticeMap = (map) => {
  if (typeof window === "undefined") {
    return;
  }

  try {
    window.localStorage.setItem(RELEASE_CHANNEL_SWITCH_NOTICE_STORAGE_KEY, JSON.stringify(map));
  } catch {
    // Ignore storage failures; the notice can be shown again on the next load.
  }
};

const normalizeReleaseChannelSlug = (value) => {
  const slug = String(value || "")
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9_-]/g, "-")
    .replace(/-+/g, "-")
    .replace(/^-|-$/g, "");
  return slug.slice(0, 64);
};

const readSelectedChannelSlug = () => {
  if (typeof window === "undefined") {
    return "";
  }

  try {
    return normalizeReleaseChannelSlug(window.localStorage.getItem(RELEASE_CHANNEL_SELECTION_STORAGE_KEY) || "");
  } catch {
    return "";
  }
};

const writeSelectedChannelSlug = (slug) => {
  if (typeof window === "undefined") {
    return;
  }

  try {
    if (slug) {
      window.localStorage.setItem(RELEASE_CHANNEL_SELECTION_STORAGE_KEY, slug);
    } else {
      window.localStorage.removeItem(RELEASE_CHANNEL_SELECTION_STORAGE_KEY);
    }
  } catch {
    // Storage is optional; the runtime endpoint will fall back to the assigned channel.
  }
};

const state = reactive({
  now: Date.now(),
  ignoredUntilByChannel: readIgnoreMap(),
  switchNoticeSeenByKey: readSwitchNoticeMap(),
  switchNoticePrincipalKey: "",
  selectedChannelSlug: readSelectedChannelSlug(),
});

let clockTimer = null;

const releaseChannelAvailabilityClock = readonly(state);

const setReleaseChannelSwitchNoticePrincipal = (principalKey) => {
  state.switchNoticePrincipalKey = String(principalKey || "").trim();
};

const releaseChannelKey = (channel) => {
  const slug = normalizeReleaseChannelSlug(channel?.slug || "");
  if (slug) {
    return slug;
  }
  const id = String(channel?.id || "").trim();
  return id ? `id:${id}` : "";
};

const hasOwn = (value, key) => Boolean(value && Object.prototype.hasOwnProperty.call(value, key));

const normalizeReadinessMissingValues = (missing = []) =>
  Array.from(
    new Set(
      (Array.isArray(missing) ? missing : [])
        .map((value) => String(value || "").trim())
        .filter(
          (value) =>
            value && !["release_bundle", "frontend_version", "frontend_base_url", "frontend_entry"].includes(value)
        )
    )
  );

const hasExplicitReleaseRuntime = (runtime) => {
  return (
    Boolean(
      runtime?.availability && typeof runtime.availability === "object" && runtime.availability.explicit !== false
    ) || hasOwn(runtime, "versions")
  );
};

const runtimeAvailability = (runtime, channel) => {
  if (runtime?.availability && typeof runtime.availability === "object") {
    const missing = normalizeReadinessMissingValues(runtime.availability.missing);
    let configured = missing.length === 0;
    if (!configured) {
      configured =
        typeof runtime.availability.configured === "boolean"
          ? runtime.availability.configured
          : runtime.availability.status !== "unconfigured";
    }
    const status =
      configured && ["", "unconfigured", "missing_target"].includes(String(runtime.availability.status || ""))
        ? "ready"
        : runtime.availability.status || (configured ? "ready" : "unconfigured");
    return {
      configured,
      missing,
      status,
    };
  }

  if (!hasOwn(runtime, "versions")) {
    return {
      configured: true,
      missing: [],
      status: "ready",
    };
  }

  const isDefaultChannel =
    channel?.default_channel === true || channel?.default_channel === 1 || String(channel?.slug || "") === "stable";
  if (isDefaultChannel) {
    return {
      configured: true,
      missing: [],
      status: "ready",
    };
  }

  const versions = runtime?.versions || {};
  const missing = [];
  if (!versions.api) {
    missing.push("api_version");
  } else if (!(runtime?.api_base_url || runtime?.urls?.api_base_url || runtime?.apiBaseUrl)) {
    missing.push("api_base_url");
  }

  return {
    configured: missing.length === 0,
    missing,
    status: missing.length === 0 ? "ready" : "unconfigured",
  };
};

const channelDisplayName = (channel, fallback = "Release channel") => {
  const slug = String(channel?.slug || "").trim();
  return String(channel?.name || slug || fallback).trim();
};

const normalizeReleaseChannelOption = (entry = {}, runtime = {}) => {
  const channel = entry?.channel && typeof entry.channel === "object" ? entry.channel : entry;
  const channelSlug = normalizeReleaseChannelSlug(channel?.slug || "");
  const channelName = channelDisplayName(channel);
  const defaultChannel =
    channel?.default_channel === true || channel?.default_channel === 1 || channelSlug === "stable";
  const versions =
    entry?.versions ||
    (releaseChannelKey(channel) === releaseChannelKey(runtime?.channel) ? runtime?.versions || {} : {});
  const availability =
    entry?.availability && typeof entry.availability === "object"
      ? runtimeAvailability({ availability: entry.availability }, channel)
      : runtimeAvailability({ channel, versions }, channel);

  return {
    channel,
    channelSlug,
    channelName,
    defaultChannel,
    description: channel?.description || "",
    versions,
    availability,
    configured: availability.configured !== false,
    missing: normalizeReadinessMissingValues(availability.missing),
    status: availability.status || (availability.configured === false ? "unconfigured" : "ready"),
  };
};

const getReleaseChannelOptions = (runtime = {}) => {
  const source = Array.isArray(runtime?.availableChannels)
    ? runtime.availableChannels
    : Array.isArray(runtime?.available_channels)
    ? runtime.available_channels
    : [];
  const entries = source.length > 0 ? source : runtime?.channel ? [{ channel: runtime.channel }] : [];
  const optionsByKey = new Map();

  entries.forEach((entry) => {
    const option = normalizeReleaseChannelOption(entry, runtime);
    const key = releaseChannelKey(option.channel);
    if (key && !optionsByKey.has(key)) {
      optionsByKey.set(key, option);
    }
  });

  if (runtime?.channel) {
    const currentOption = normalizeReleaseChannelOption(
      {
        channel: runtime.channel,
        versions: runtime.versions || {},
        availability: runtime.availability || null,
      },
      runtime
    );
    const key = releaseChannelKey(currentOption.channel);
    if (key && !optionsByKey.has(key)) {
      optionsByKey.set(key, currentOption);
    }
  }

  return [...optionsByKey.values()];
};

const hasSelectableReleaseChannels = (runtime = {}) => {
  const options = getReleaseChannelOptions(runtime);
  const hasOnlyDefaultStable =
    options.length === 1 && options[0].defaultChannel === true && options[0].channelSlug === "stable";
  return options.length > 1 && !hasOnlyDefaultStable;
};

const getReleaseChannelUnavailableStatus = (runtime = {}, now = Date.now(), ignoredUntil = 0) => {
  const channel = runtime?.channel || null;
  const channelSlug = normalizeReleaseChannelSlug(channel?.slug || "");
  const channelName = channelDisplayName(channel);
  const isDefaultChannel =
    channel?.default_channel === true || channel?.default_channel === 1 || channelSlug === "stable";
  const explicitAvailability = hasExplicitReleaseRuntime(runtime);
  const availability = runtimeAvailability(runtime, channel);
  const ignored = Number(ignoredUntil || 0) > now;
  const unavailable = Boolean(channelSlug) && !isDefaultChannel && availability.configured === false;

  return {
    channel,
    channelSlug,
    channelName,
    defaultChannel: isDefaultChannel,
    explicitAvailability,
    description: channel?.description || "",
    missing: availability.missing,
    configured: availability.configured,
    unavailable,
    ignored,
    ignoredUntil: Number(ignoredUntil || 0),
    shouldBlock: unavailable && !ignored,
    status: availability.status,
    versions: runtime?.versions || {},
  };
};

const releaseChannelUnavailableStatus = computed(() => {
  const key = releaseChannelKey(releaseRuntimeState.channel);
  const ignoredUntil = key ? Number(state.ignoredUntilByChannel[key] || 0) : 0;
  return getReleaseChannelUnavailableStatus(releaseRuntimeState, state.now, ignoredUntil);
});

const releaseChannelOptions = computed(() => getReleaseChannelOptions(releaseRuntimeState));

const releaseChannelSelectorVisible = computed(() => hasSelectableReleaseChannels(releaseRuntimeState));

const selectedReleaseChannelSlug = computed(() => state.selectedChannelSlug);

const getSelectedReleaseChannelSlug = () => state.selectedChannelSlug || readSelectedChannelSlug();

const releaseChannelRuntimeRequestParams = () => {
  const slug = getSelectedReleaseChannelSlug();
  return slug ? { release_channel: slug } : {};
};

const RELEASE_CHANNEL_API_FAILURE_STATUSES = new Set([404, 502, 503, 504]);

const releaseRuntimeApiBaseUrl = (runtime = {}) =>
  String(runtime?.apiBaseUrl || runtime?.api_base_url || runtime?.urls?.api_base_url || "")
    .trim()
    .replace(/\/+$/, "");

const releaseRuntimeFrontendBaseUrl = (runtime = {}) =>
  String(runtime?.frontendBaseUrl || runtime?.frontend_base_url || runtime?.urls?.frontend_base_url || "")
    .trim()
    .replace(/\/+$/, "");

const isReleaseChannelApiAvailabilityError = (error, runtime = releaseRuntimeState) => {
  const status = Number(error?.response?.status || 0);
  if (!RELEASE_CHANNEL_API_FAILURE_STATUSES.has(status)) {
    return false;
  }

  const channelSlug = normalizeReleaseChannelSlug(runtime?.channel?.slug || getSelectedReleaseChannelSlug());
  const isDefaultChannel =
    runtime?.channel?.default_channel === true || runtime?.channel?.default_channel === 1 || channelSlug === "stable";
  if (!channelSlug || isDefaultChannel) {
    return false;
  }

  const requestUrl = String(error?.config?.url || error?.request?.responseURL || "");
  if (!requestUrl.includes("/auth/session")) {
    return false;
  }

  const apiBaseUrl = releaseRuntimeApiBaseUrl(runtime);
  return !apiBaseUrl || requestUrl.startsWith(apiBaseUrl);
};

const markReleaseChannelApiUnavailable = (runtime = releaseRuntimeState, missingKey = "api_base_url") => {
  const channelSlug = normalizeReleaseChannelSlug(runtime?.channel?.slug || getSelectedReleaseChannelSlug());
  const isDefaultChannel =
    runtime?.channel?.default_channel === true || runtime?.channel?.default_channel === 1 || channelSlug === "stable";
  if (!channelSlug || isDefaultChannel) {
    return null;
  }

  const availability = runtime?.availability && typeof runtime.availability === "object" ? runtime.availability : {};
  const missing = normalizeReadinessMissingValues([
    ...(Array.isArray(availability.missing) ? availability.missing : []),
    missingKey,
  ]);
  const nextRuntime = {
    trace_id: runtime?.traceId || runtime?.trace_id || null,
    channel: runtime?.channel || {
      slug: channelSlug,
      name: channelSlug,
      default_channel: false,
    },
    available_channels: runtime?.availableChannels || runtime?.available_channels || [],
    versions: runtime?.versions || {},
    frontend_base_url: releaseRuntimeFrontendBaseUrl(runtime) || null,
    api_base_url: releaseRuntimeApiBaseUrl(runtime) || null,
    urls: {
      frontend_base_url: releaseRuntimeFrontendBaseUrl(runtime) || null,
      api_base_url: releaseRuntimeApiBaseUrl(runtime) || null,
    },
    availability: {
      ...availability,
      configured: false,
      explicit: true,
      missing,
      status: "unconfigured",
    },
    capture_policy: runtime?.capturePolicy || runtime?.capture_policy || {},
  };
  configureReleaseRuntime(nextRuntime);
  return nextRuntime;
};

const selectReleaseChannel = (channelOrSlug) => {
  const slug = normalizeReleaseChannelSlug(
    typeof channelOrSlug === "string" ? channelOrSlug : channelOrSlug?.slug || channelOrSlug?.channelSlug || ""
  );
  state.selectedChannelSlug = slug;
  writeSelectedChannelSlug(slug);
  return slug;
};

const switchSelectedReleaseChannel = async (channelOrSlug, refreshRuntime) => {
  if (typeof refreshRuntime !== "function") {
    throw new Error("Release runtime refresh is not available.");
  }

  const previousSlug = getSelectedReleaseChannelSlug();
  const targetSlug = selectReleaseChannel(channelOrSlug);
  if (!targetSlug) {
    return "";
  }

  try {
    const runtime = (await refreshRuntime({ throwOnError: true })) || releaseRuntimeState;
    const confirmedSlug = releaseChannelKey(runtime?.channel || releaseRuntimeState.channel);
    if (confirmedSlug !== targetSlug) {
      throw new Error(`Release runtime switched to ${confirmedSlug || "unknown"} instead of ${targetSlug}.`);
    }
    return targetSlug;
  } catch (error) {
    selectReleaseChannel(previousSlug);
    try {
      await refreshRuntime({ throwOnError: true });
    } catch (restoreError) {
      console.warn("Could not restore the previous release runtime after a failed switch.", restoreError);
    }
    throw error;
  }
};

const clearSelectedReleaseChannel = () => {
  state.selectedChannelSlug = "";
  writeSelectedChannelSlug("");
};

const reconcileSelectedReleaseChannel = (runtime = releaseRuntimeState) => {
  const hasExplicitOptions = Array.isArray(runtime?.availableChannels) || Array.isArray(runtime?.available_channels);
  const selected = getSelectedReleaseChannelSlug();
  if (!hasExplicitOptions || !selected) {
    return selected;
  }

  const hasSelectedOption = getReleaseChannelOptions(runtime).some((option) => option.channelSlug === selected);
  if (!hasSelectedOption) {
    clearSelectedReleaseChannel();
    return "";
  }

  return selected;
};

const releaseChannelSwitchNoticeKey = (channel, principalKey = state.switchNoticePrincipalKey) => {
  const channelKey = releaseChannelKey(channel);
  const principal = String(principalKey || "").trim();
  return channelKey && principal ? `${principal}:${channelKey}` : "";
};

const getReleaseChannelSwitchedStatus = (
  runtime = {},
  principalKey = state.switchNoticePrincipalKey,
  seenMap = state.switchNoticeSeenByKey
) => {
  const unavailableStatus = getReleaseChannelUnavailableStatus(runtime, state.now, 0);
  const noticeKey = releaseChannelSwitchNoticeKey(unavailableStatus.channel, principalKey);
  const seen = noticeKey ? Boolean(seenMap[noticeKey]) : false;
  const shouldShow =
    Boolean(noticeKey) &&
    Boolean(unavailableStatus.channelSlug) &&
    unavailableStatus.defaultChannel === false &&
    unavailableStatus.explicitAvailability === true &&
    unavailableStatus.configured === true &&
    unavailableStatus.unavailable === false &&
    unavailableStatus.channelSlug !== "stable" &&
    seen === false;

  return {
    ...unavailableStatus,
    noticeKey,
    principalKey: String(principalKey || "").trim(),
    seen,
    shouldShow,
  };
};

const releaseChannelSwitchedStatus = computed(() => {
  return getReleaseChannelSwitchedStatus(
    releaseRuntimeState,
    state.switchNoticePrincipalKey,
    state.switchNoticeSeenByKey
  );
});

const acknowledgeReleaseChannelSwitch = (
  channel = releaseChannelSwitchedStatus.value.channel,
  principalKey = state.switchNoticePrincipalKey
) => {
  const noticeKey = releaseChannelSwitchNoticeKey(channel, principalKey);
  if (!noticeKey) {
    return "";
  }

  const nextMap = {
    ...state.switchNoticeSeenByKey,
    [noticeKey]: new Date().toISOString(),
  };
  state.switchNoticeSeenByKey = nextMap;
  writeSwitchNoticeMap(nextMap);
  return noticeKey;
};

const ignoreUnavailableReleaseChannel = (
  channel = releaseChannelUnavailableStatus.value.channel,
  durationMs = RELEASE_CHANNEL_IGNORE_MS
) => {
  const key = releaseChannelKey(channel);
  if (!key) {
    return 0;
  }

  const ignoredUntil = Date.now() + durationMs;
  const nextMap = {
    ...state.ignoredUntilByChannel,
    [key]: ignoredUntil,
  };
  state.ignoredUntilByChannel = nextMap;
  state.now = Date.now();
  writeIgnoreMap(nextMap);
  return ignoredUntil;
};

const clearUnavailableReleaseChannelIgnore = (channel = releaseChannelUnavailableStatus.value.channel) => {
  const key = releaseChannelKey(channel);
  if (!key) {
    return;
  }

  const nextMap = { ...state.ignoredUntilByChannel };
  delete nextMap[key];
  state.ignoredUntilByChannel = nextMap;
  state.now = Date.now();
  writeIgnoreMap(nextMap);
};

const startReleaseChannelAvailabilityClock = () => {
  if (typeof window === "undefined" || clockTimer !== null) {
    return () => {};
  }

  clockTimer = window.setInterval(() => {
    state.now = Date.now();
  }, 1000);

  return stopReleaseChannelAvailabilityClock;
};

const stopReleaseChannelAvailabilityClock = () => {
  if (typeof window === "undefined" || clockTimer === null) {
    return;
  }

  window.clearInterval(clockTimer);
  clockTimer = null;
};

const buildReleaseFrontendRedirectUrl = () => null;

const redirectToConfiguredReleaseFrontend = () => false;

const __resetReleaseChannelAvailabilityForTests = () => {
  state.now = Date.now();
  state.ignoredUntilByChannel = {};
  state.switchNoticeSeenByKey = {};
  state.switchNoticePrincipalKey = "";
  state.selectedChannelSlug = "";
  stopReleaseChannelAvailabilityClock();
  if (typeof window !== "undefined") {
    window.localStorage.removeItem(RELEASE_CHANNEL_IGNORE_STORAGE_KEY);
    window.localStorage.removeItem(RELEASE_CHANNEL_SWITCH_NOTICE_STORAGE_KEY);
    window.localStorage.removeItem(RELEASE_CHANNEL_SELECTION_STORAGE_KEY);
  }
};

const normalizePositiveInteger = (value) => {
  const parsedValue = Number.parseInt(String(value ?? ""), 10);
  return Number.isInteger(parsedValue) && parsedValue > 0 ? parsedValue : null;
};

const SUBUSER_MANAGEMENT_PERMISSIONS = {
  list: {
    customer: "list_own_subusers",
    subuser: "SUBUSERS_LIST",
  },
  add: {
    customer: "add_own_subusers",
    subuser: "SUBUSERS_ADD",
  },
  edit: {
    customer: "edit_own_subusers",
    subuser: "SUBUSERS_EDIT",
  },
  delete: {
    customer: "delete_own_subusers",
    subuser: "SUBUSERS_DELETE",
  },
};

const CUSTOMER_FEATURE_PERMISSIONS = {
  vehicles: {
    list: {
      customer: ["user", "list_own_vehicles"],
      subuser: ["VEHICLES_LIST"],
    },
    add: {
      customer: ["user", "add_vehicle"],
      subuser: ["VEHICLES_ADD"],
    },
    edit: {
      customer: ["edit_vehicle", "add_vehicle"],
      subuser: ["VEHICLES_EDIT"],
    },
    delete: {
      customer: ["delete_vehicle"],
      subuser: ["VEHICLES_DELETE"],
    },
  },
  bookings: {
    list: {
      customer: ["user", "list_own_bookings"],
      subuser: ["BOOKINGS_LIST"],
    },
    add: {
      customer: ["user"],
      subuser: ["BOOKINGS_ADD"],
    },
    edit: {
      customer: ["edit_own_bookings"],
      subuser: ["BOOKINGS_EDIT"],
    },
    delete: {
      customer: ["delete_own_bookings"],
      subuser: ["BOOKINGS_DELETE"],
    },
  },
  orders: {
    list: {
      customer: ["user", "list_own_orders"],
      subuser: ["ORDERS_LIST"],
    },
    edit: {
      customer: ["edit_own_orders"],
      subuser: ["ORDERS_EDIT"],
    },
  },
  selfserve: {
    list: {
      customer: ["user", "list_own_department_selfserve_vehicle_conditions"],
      subuser: ["SELFSERVE_LIST"],
    },
    add: {
      customer: ["add_own_department_selfserve_vehicle_conditions"],
      subuser: ["SELFSERVE_ADD"],
    },
  },
  subusers: SUBUSER_MANAGEMENT_PERMISSIONS,
};

const getStoredSessionSnapshot = () => {
  if (typeof window === "undefined") {
    return null;
  }

  try {
    const token = window.localStorage.getItem("token");
    if (token === null) {
      return null;
    }

    return {
      token,
      isSubuser: window.localStorage.getItem("is_subuser") === "true",
      selectedCustomerNumber: normalizePositiveInteger(window.localStorage.getItem("selected_customer_number")),
    };
  } catch {
    return null;
  }
};

const hydrateSessionFromStorage = () => {
  const snapshot = getStoredSessionSnapshot();
  if (!snapshot) {
    return false;
  }

  SessionUser.token.value = snapshot.token;
  SessionUser.authenticated.value = true;
  SessionUser.isSubuser.value = snapshot.isSubuser;
  SessionUser.subuser.selectedGrantCustomerNumber.value = snapshot.selectedCustomerNumber;
  return true;
};

const clearPrivilegedSessionCaches = () => {
  clearPeriodCache();
  clearSelfWashCountsCache();
  clearCachedXlvaskUsageAmount();
  clearEdgeGatewayWorkspaceCache();
};

const clearStoredSession = () => {
  clearPrivilegedSessionCaches();

  if (typeof window === "undefined") {
    return;
  }

  try {
    window.localStorage.removeItem("token");
    window.localStorage.removeItem("is_subuser");
    window.localStorage.removeItem("selected_customer_number");
  } catch {
    // Storage can be unavailable in test or private browsing contexts.
  }
};

const applyReleaseRuntimeConfig = (runtime) => {
  const normalizedRuntime = runtime || {};
  configureReleaseRuntime(normalizedRuntime);
  reconcileSelectedReleaseChannel(normalizedRuntime);
  const runtimeUrls =
    normalizedRuntime.urls && typeof normalizedRuntime.urls === "object" ? normalizedRuntime.urls : {};
  SessionUser.runtimeConfig.release.traceId.value = normalizedRuntime.trace_id || null;
  SessionUser.runtimeConfig.release.channel.value = normalizedRuntime.channel || null;
  SessionUser.runtimeConfig.release.availableChannels.value =
    normalizedRuntime.available_channels || normalizedRuntime.availableChannels || [];
  SessionUser.runtimeConfig.release.versions.value = normalizedRuntime.versions || {
    frontend: null,
    api: null,
    bundle_id: null,
  };
  SessionUser.runtimeConfig.release.frontendBaseUrl.value =
    normalizedRuntime.frontend_base_url || runtimeUrls.frontend_base_url || null;
  SessionUser.runtimeConfig.release.apiBaseUrl.value =
    normalizedRuntime.api_base_url || runtimeUrls.api_base_url || null;
  SessionUser.runtimeConfig.release.availability.value = normalizedRuntime.availability || {
    configured: true,
    missing: [],
    status: "ready",
    explicit: false,
  };
  SessionUser.runtimeConfig.release.capturePolicy.value = normalizedRuntime.capture_policy || {
    enabled: false,
    capture_level: "metadata",
    all_failure_metadata: true,
    retention_days: 14,
  };
};

const refreshReleaseRuntime = async ({ throwOnError = false } = {}) => {
  try {
    const runtime = await fetchReleaseRuntime();
    applyReleaseRuntimeConfig(runtime || {});
    return runtime || {};
  } catch (error) {
    console.warn("Could not refresh release runtime", error);
    if (throwOnError) {
      throw error;
    }
    return null;
  }
};

const resetSessionState = () => {
  SessionUser.user.id.value = null;
  SessionUser.user.customer_number.value = null;
  SessionUser.user.display_name.value = null;
  SessionUser.user.group_id.value = null;
  SessionUser.user.email.value = null;
  SessionUser.user.phone.number.value = null;
  SessionUser.user.phone.country_code.value = null;
  SessionUser.user.notifications.wash_certificate_email.value = null;
  SessionUser.user.notifications.email_notifications_enabled.value = null;
  SessionUser.user.notifications.sms_notifications_enabled.value = null;
  SessionUser.user.notifications.superuser_new_customer_email_notifications_enabled.value = null;
  SessionUser.user.created_at.value = null;
  SessionUser.user.updated_at.value = null;
  SessionUser.user.cached_at.value = null;
  SessionUser.permissions.value = [];
  SessionUser.token.value = null;
  SessionUser.authenticated.value = false;
  SessionUser.isSubuser.value = false;
  SessionUser.initiated.value = false;

  SessionUser.subuser.id.value = null;
  SessionUser.subuser.username.value = null;
  SessionUser.subuser.name.value = null;
  SessionUser.subuser.email.value = null;
  SessionUser.subuser.email_verified.value = false;
  SessionUser.subuser.email_verified_at.value = null;
  SessionUser.subuser.phone.country_code.value = null;
  SessionUser.subuser.phone.number.value = null;
  SessionUser.subuser.phone.verified.value = false;
  SessionUser.subuser.phone.verified_at.value = null;
  SessionUser.subuser.verification_state.value = null;
  SessionUser.subuser.verification.value = null;
  SessionUser.subuser.grants.value = [];
  SessionUser.subuser.created_at.value = null;
  SessionUser.subuser.updated_at.value = null;
  SessionUser.subuser.suspended_at.value = null;
  SessionUser.subuser.cached_at.value = null;
  SessionUser.subuser.selectedGrantCustomerNumber.value = null;

  if (typeof window !== "undefined") {
    try {
      window.localStorage.removeItem("selected_customer_number");
    } catch {
      // Storage is optional for the in-memory reset.
    }
  }

  SessionUser.economicData.customerNumber.value = null;
  SessionUser.economicData.name.value = null;
  SessionUser.economicData.address.value = null;
  SessionUser.economicData.zip.value = null;
  SessionUser.economicData.city.value = null;
  SessionUser.economicData.mobilePhone.value = null;
  SessionUser.economicData.email.value = null;
  SessionUser.economicData.cvr.value = null;
  SessionUser.economicData.currency.value = null;
  SessionUser.economicData.country.value = null;
  SessionUser.economicData.cached_at.value = null;

  SessionUser.runtimeConfig.economic.transactionDraftCustomerNumber.value = null;
  SessionUser.runtimeConfig.economic.defaultDistributionDepartmentId.value = null;
  SessionUser.runtimeConfig.release.traceId.value = null;
  SessionUser.runtimeConfig.release.channel.value = null;
  SessionUser.runtimeConfig.release.availableChannels.value = [];
  SessionUser.runtimeConfig.release.versions.value = { frontend: null, api: null, bundle_id: null };
  SessionUser.runtimeConfig.release.frontendBaseUrl.value = null;
  SessionUser.runtimeConfig.release.apiBaseUrl.value = null;
  SessionUser.runtimeConfig.release.availability.value = {
    configured: true,
    missing: [],
    status: "ready",
    explicit: false,
  };
  SessionUser.runtimeConfig.release.capturePolicy.value = {
    enabled: false,
    capture_level: "metadata",
    all_failure_metadata: true,
    retention_days: 14,
  };
  setReleaseChannelSwitchNoticePrincipal("");
  configureReleaseRuntime({});
};

const reconcileSelectedSubuserGrant = (grants) => {
  const grantList = Array.isArray(grants) ? grants : [];
  const currentSelection = normalizePositiveInteger(SessionUser.subuser.selectedGrantCustomerNumber.value);
  const validCustomerNumbers = grantList
    .map((grant) => normalizePositiveInteger(grant?.billing_customer_number))
    .filter((customerNumber) => customerNumber !== null);

  if (currentSelection && validCustomerNumbers.includes(currentSelection)) {
    SessionUser.subuser.selectGrant(currentSelection);
    return;
  }

  if (validCustomerNumbers.length === 1) {
    SessionUser.subuser.selectGrant(validCustomerNumbers[0]);
    return;
  }

  SessionUser.subuser.selectGrant(null);
};

let sessionBootstrapPromise = null;

const extractErrorMessage = (error) => {
  if (typeof error === "string") {
    return error;
  }

  if (error?.response?.data?.data?.message) {
    return error.response.data.data.message;
  }

  if (error?.response?.data?.message) {
    return error.response.data.message;
  }

  if (typeof error?.response?.data === "string") {
    return error.response.data;
  }

  if (error?.message) {
    return error.message;
  }

  return "";
};

const isInvalidSessionError = (error) => {
  const status = Number.parseInt(String(error?.response?.status ?? ""), 10);
  const message = extractErrorMessage(error).toLowerCase();

  if (status === 401 || status === 419) {
    return true;
  }

  if (![400, 403].includes(status)) {
    return false;
  }

  return (
    message.includes("invalid session") ||
    message.includes("invalid token") ||
    message.includes("unauthenticated") ||
    message.includes("unauthorized")
  );
};

const redirectToConnectivityIssue = () => {
  if (typeof window === "undefined" || window.location.pathname === "/connectivity-issue") {
    return false;
  }

  window.location.href = "/connectivity-issue";
  return true;
};

const handleSessionBootstrapFailure = async (error, { title, text } = {}) => {
  if (isInvalidSessionError(error)) {
    const wasSubuserSession = SessionUser.isSubuser.value || getStoredSessionSnapshot()?.isSubuser === true;
    const pingResult = await pingApiServer();
    if (!pingResult.ok) {
      console.warn("Preserving stored session because API ping failed during invalid-session handling.", pingResult);
      const redirected = redirectToConnectivityIssue();
      return {
        cleared: false,
        apiReachable: false,
        ping: pingResult,
        redirectedTo: redirected ? "/connectivity-issue" : null,
      };
    }

    forceClearSession();
    if (wasSubuserSession) {
      SessionUser.functions.redirectTo.pages.subuserLogin();
      return { cleared: true, apiReachable: true, ping: pingResult, redirectedTo: "/login/driver" };
    }
    SessionUser.functions.redirectTo.pages.login();
    return { cleared: true, apiReachable: true, ping: pingResult, redirectedTo: "/login" };
  }

  parseError(error, "auth");
  console.error(error);
  await Swal.fire({
    title,
    text,
    icon: "error",
    confirmButtonText: "Ok",
  });

  return { cleared: false, apiReachable: null, ping: null, redirectedTo: null };
};

const refreshSessionData = async () => {
  if (!hydrateSessionFromStorage()) {
    resetSessionState();
    return null;
  }

  if (SessionUser.isSubuser.value) {
    return await getSubuserSessionData();
  }

  return await getSessionData();
};

/**
 * Initiate the user session on app start
 * @returns {Promise<void>}
 */
const initiateOnAppStart = async ({ force = false } = {}) => {
  if (sessionBootstrapPromise && !force) {
    return await sessionBootstrapPromise;
  }

  const bootstrapPromise = (async () => {
    if (!hydrateSessionFromStorage()) {
      return null;
    }

    if (SessionUser.isSubuser.value) {
      return await getSubuserSessionData();
    }

    return await getSessionData();
  })();

  sessionBootstrapPromise = bootstrapPromise;

  try {
    return await bootstrapPromise;
  } finally {
    if (sessionBootstrapPromise === bootstrapPromise) {
      sessionBootstrapPromise = null;
    }
  }
};

/**
 * Authenticate the user
 * @param {string} customer_number
 * @param {string} password
 * @returns {Promise<void>}
 */
const authenticateUser = async (customer_number, password) => {
  return await authenticatedRequest("/auth/login", "POST", {
    customer_number,
    password,
  })
    .then((response) => {
      clearPrivilegedSessionCaches();
      SessionUser.token.value = response.data.token;
      SessionUser.authenticated.value = true;
      localStorage.setItem("token", response.data.token);
      localStorage.removeItem("is_subuser");
      // Reload the window to make sure the user's session is initiated
      window.location.reload();
    })
    .catch((error) => {
      parseError(error, "auth");
      console.error(error);
    });
};

/**
 * Authenticate a subuser with password
 * Supports three authentication methods:
 * - phone_country_code + phone + password
 * - subuser_id + password
 * - username + password
 * @param {Object} credentials - The authentication credentials
 * @param {number} [credentials.phone_country_code] - Phone country code (1-3 digits)
 * @param {number} [credentials.phone] - Phone number (4-15 digits)
 * @param {number} [credentials.subuser_id] - Subuser ID
 * @param {string} [credentials.username] - Username
 * @param {string} credentials.password - Password (8-255 characters, uppercase, lowercase, and number)
 * @returns {Promise<void>}
 */
const authenticateSubuser = async (credentials) => {
  const { phone_country_code, phone, subuser_id, username, password } = credentials;

  // Build the request body based on provided credentials
  let requestBody = { password };

  if (phone_country_code !== undefined && phone !== undefined) {
    requestBody.phone_country_code = phone_country_code;
    requestBody.phone = phone;
  } else if (subuser_id !== undefined) {
    requestBody.subuser_id = subuser_id;
  } else if (username !== undefined) {
    requestBody.username = username;
  } else {
    throw new Error("Invalid credentials: must provide phone_country_code+phone, subuser_id, or username");
  }

  return await authenticatedRequest("/subusers/auth/password", "POST", requestBody)
    .then((response) => {
      clearPrivilegedSessionCaches();
      SessionUser.token.value = response.data.data.session;
      SessionUser.authenticated.value = true;
      SessionUser.isSubuser.value = true;
      console.warn("Subuser session initiated", response);
      // Make sure the subuser's session is valid before setting the token and reloading
      if (!response.data.data.session) {
        throw new Error("No session token received for subuser authentication");
      }
      localStorage.setItem("token", response.data.data.session);
      localStorage.setItem("is_subuser", "true");
      // Reload the window to make sure the subuser's session is initiated
      window.location.reload();
    })
    .catch((error) => {
      parseError(error, "auth");
      console.error(error);
      throw error;
    });
};

/**
 * Get the subuser's session data from /subusers/me
 * @returns {Promise<void>}
 */
const getSubuserSessionData = async () => {
  return await authenticatedRequest("/subusers/me", "GET")
    .then(async (response) => {
      const data = response.data.data || response.data;
      SessionUser.subuser.id.value = data.id;
      SessionUser.subuser.username.value = data.username;
      SessionUser.subuser.name.value = data.name;
      SessionUser.subuser.email.value = data.email;
      SessionUser.subuser.email_verified.value = Boolean(data.email_verified);
      SessionUser.subuser.email_verified_at.value = data.email_verified_at || null;
      SessionUser.subuser.phone.country_code.value = data.phone_country_code;
      SessionUser.subuser.phone.number.value = data.phone;
      SessionUser.subuser.phone.verified.value = Boolean(data.phone_verified);
      SessionUser.subuser.phone.verified_at.value = data.phone_verified_at || null;
      SessionUser.subuser.verification_state.value = data.verification_state || data.verification?.state || null;
      SessionUser.subuser.verification.value = data.verification || null;
      SessionUser.subuser.grants.value = data.grants || [];
      reconcileSelectedSubuserGrant(SessionUser.subuser.grants.value);
      SessionUser.subuser.created_at.value = data.created_at;
      SessionUser.subuser.updated_at.value = data.updated_at;
      SessionUser.subuser.suspended_at.value = data.suspended_at;
      SessionUser.subuser.cached_at.value = new Date();
      setReleaseChannelSwitchNoticePrincipal(`subuser:${data.id || data.username || data.email || "unknown"}`);

      // Build permissions from grants
      const allPermissions = [];
      if (data.grants && Array.isArray(data.grants)) {
        data.grants.forEach((grant) => {
          if (grant.permissions && Array.isArray(grant.permissions)) {
            allPermissions.push(...grant.permissions);
          }
        });
      }
      SessionUser.permissions.value = [...new Set(allPermissions)];
      await refreshReleaseRuntime();
      SessionUser.initiated.value = true;
    })
    .catch(async (error) => {
      if (isReleaseChannelApiAvailabilityError(error)) {
        console.warn("Selected release channel API is unavailable during session bootstrap.", error);
        markReleaseChannelApiUnavailable();
        return;
      }

      return await handleSessionBootstrapFailure(error, {
        title: "Fejl ved hentning af subbrugerdata",
        text: "Der opstod en fejl ved hentning af dine brugerdata. Prøv at logge ind igen.",
      });
    });
};

/**
 * Get the user's session data
 * @returns {Promise<void>}
 */
const getSessionData = async () => {
  return await authenticatedRequest("/auth/session", "GET", releaseChannelRuntimeRequestParams())
    .then((response) => {
      const session = normalizeSessionPayload(response?.data?.data);

      SessionUser.user.id.value = session.id;
      SessionUser.user.customer_number.value = session.customer_number;
      SessionUser.user.group_id.value = session.group_id;
      SessionUser.user.email.value = session.email;
      SessionUser.user.phone.number.value = session.phone.number;
      SessionUser.user.phone.country_code.value = session.phone.country_code;
      SessionUser.user.notifications.wash_certificate_email.value = session.notifications.wash_certificate_email;
      SessionUser.user.notifications.email_notifications_enabled.value =
        session.notifications.email_notifications_enabled;
      SessionUser.user.notifications.sms_notifications_enabled.value = session.notifications.sms_notifications_enabled;
      SessionUser.user.notifications.superuser_new_customer_email_notifications_enabled.value =
        session.notifications.superuser_new_customer_email_notifications_enabled;
      SessionUser.user.created_at.value = session.created_at;
      SessionUser.user.updated_at.value = session.updated_at;
      SessionUser.user.display_name.value = session.display_name;
      setReleaseChannelSwitchNoticePrincipal(
        `user:${session.id || session.customer_number || session.email || "unknown"}`
      );
      // Set the last cached time to now, this is used to determine if the user's data is outdated
      SessionUser.user.cached_at.value = new Date();
      SessionUser.permissions.value = session.permissions;
      SessionUser.runtimeConfig.economic.transactionDraftCustomerNumber.value = normalizePositiveInteger(
        session.runtime_config.economic.transaction_draft_customer_number
      );
      SessionUser.runtimeConfig.economic.defaultDistributionDepartmentId.value = normalizePositiveInteger(
        session.runtime_config.economic.default_distribution_department_id
      );
      applyReleaseRuntimeConfig(session.runtime_config.release);
      // E-conomic data is only fetched if the array isn't empty
      if (session.economic_customer) {
        SessionUser.economicData.customerNumber.value = session.economic_customer.customerNumber;
        SessionUser.economicData.name.value = session.economic_customer.name;
        // Set the display name to the e-conomic name if it's empty
        if (SessionUser.user.display_name.value === null || SessionUser.user.display_name.value === "Unnamed") {
          SessionUser.user.display_name.value = session.economic_customer.name;
        }
        SessionUser.economicData.address.value = session.economic_customer.address;
        SessionUser.economicData.zip.value = session.economic_customer.zip;
        SessionUser.economicData.city.value = session.economic_customer.city;
        SessionUser.economicData.mobilePhone.value = session.economic_customer.mobilePhone;
        SessionUser.economicData.email.value = session.economic_customer.email;
        SessionUser.economicData.cvr.value = session.economic_customer.corporateIdentificationNumber;
        SessionUser.economicData.currency.value = session.economic_customer.currency;
        SessionUser.economicData.country.value = session.economic_customer.country;
        SessionUser.economicData.cached_at.value = new Date();
      }
      SessionUser.initiated.value = true;
    })
    .catch(async (error) => {
      if (isReleaseChannelApiAvailabilityError(error)) {
        console.warn("Selected release channel API is unavailable during session bootstrap.", error);
        markReleaseChannelApiUnavailable();
        return;
      }

      return await handleSessionBootstrapFailure(error, {
        title: "Fejl ved hentning af brugerdata",
        text: "Der opstod en fejl ved hentning af dine brugerdata. Prøv at logge ind igen.",
      });
    });
};

const LOGOUT_REQUEST_TIMEOUT_MS = 2500;

const waitForLogoutRequest = async (request, timeoutMs = LOGOUT_REQUEST_TIMEOUT_MS) => {
  const safeTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : LOGOUT_REQUEST_TIMEOUT_MS;
  let timeoutId = null;
  let didTimeout = false;

  const timeoutPromise = new Promise((resolve) => {
    timeoutId = globalThis.setTimeout(() => {
      didTimeout = true;
      resolve({ timedOut: true });
    }, safeTimeoutMs);
  });

  const requestPromise = Promise.resolve(request)
    .catch((error) => {
      if (!didTimeout) {
        parseError(error, "auth");
        console.error(error);
      }
      return { timedOut: false };
    })
    .finally(() => {
      if (timeoutId !== null) {
        globalThis.clearTimeout(timeoutId);
      }
    });

  return await Promise.race([requestPromise, timeoutPromise]);
};

/**
 * Destroy the user's session
 * @returns {Promise<void>}
 */
const destroySession = async ({ timeoutMs = LOGOUT_REQUEST_TIMEOUT_MS } = {}) => {
  try {
    if (localStorage.getItem("token")) {
      await waitForLogoutRequest(authenticatedRequest("/auth/logout", "GET"), timeoutMs);
    }
  } finally {
    clearStoredSession();
    resetSessionState();
  }
};

/**
 * Force sign out the user
 */
const forceClearSession = () => {
  clearStoredSession();
  resetSessionState();
};

/**
 * Define the user session variables
 */
const SessionUser = {
  user: {
    id: ref(null),
    customer_number: ref(null),
    display_name: ref(null),
    group_id: ref(null),
    email: ref(null),
    phone: {
      number: ref(null),
      country_code: ref(null),
    },
    created_at: ref(null),
    updated_at: ref(null),
    cached_at: ref(null),
    notifications: {
      wash_certificate_email: ref(null),
      email_notifications_enabled: ref(null),
      sms_notifications_enabled: ref(null),
      superuser_new_customer_email_notifications_enabled: ref(null),
      setEmailNotificationsEnabled: (enabled) => {
        return SessionUser.request("/account/notifications", "PUT", {
          email_notifications_enabled: enabled,
        })
          .then(() => {
            SessionUser.user.notifications.email_notifications_enabled.value = enabled;
          })
          .catch((error) => {
            parseError(error, "user_notifications");
            console.error(error);
          });
      },
      setSmsNotificationsEnabled: (enabled) => {
        return SessionUser.request("/account/notifications", "PUT", {
          sms_notifications_enabled: enabled,
        })
          .then(() => {
            SessionUser.user.notifications.sms_notifications_enabled.value = enabled;
          })
          .catch((error) => {
            parseError(error, "user_notifications");
            console.error(error);
          });
      },
      setSuperuserNewCustomerEmailNotificationsEnabled: (enabled) => {
        return SessionUser.request("/account/notifications", "PUT", {
          superuser_new_customer_email_notifications_enabled: enabled,
        })
          .then(() => {
            SessionUser.user.notifications.superuser_new_customer_email_notifications_enabled.value = enabled;
          })
          .catch((error) => {
            parseError(error, "user_notifications");
            console.error(error);
          });
      },
      setWashCertificateEmail: (email) => {
        return SessionUser.request("/account/notifications", "PUT", {
          wash_certificate_email: email,
        })
          .then(() => {
            SessionUser.user.notifications.wash_certificate_email.value = email;
          })
          .catch((error) => {
            parseError(error, "user_notifications");
            console.error(error);
          });
      },
    },
  },
  /** Subuser profile data (populated when authenticated as subuser) */
  subuser: {
    id: ref(null),
    username: ref(null),
    name: ref(null),
    email: ref(null),
    email_verified: ref(false),
    email_verified_at: ref(null),
    phone: {
      country_code: ref(null),
      number: ref(null),
      verified: ref(false),
      verified_at: ref(null),
    },
    verification_state: ref(null),
    verification: ref(null),
    grants: ref([]),
    created_at: ref(null),
    updated_at: ref(null),
    suspended_at: ref(null),
    cached_at: ref(null),
    /** Currently selected grant (billing_customer_number) for X-Customer-Number header */
    selectedGrantCustomerNumber: ref(normalizePositiveInteger(localStorage.getItem("selected_customer_number"))),
    /**
     * Select a grant by billing_customer_number
     * @param {number|null} customerNumber - The billing_customer_number to select, or null to clear
     */
    selectGrant: (customerNumber) => {
      clearEdgeGatewayWorkspaceCache();
      const normalizedCustomerNumber = normalizePositiveInteger(customerNumber);
      if (normalizedCustomerNumber === null) {
        localStorage.removeItem("selected_customer_number");
        SessionUser.subuser.selectedGrantCustomerNumber.value = null;
      } else {
        localStorage.setItem("selected_customer_number", normalizedCustomerNumber.toString());
        SessionUser.subuser.selectedGrantCustomerNumber.value = normalizedCustomerNumber;
      }
    },
    /**
     * Get the currently selected grant object
     * @returns {Object|null} The selected grant object or null
     */
    getSelectedGrant: () => {
      const selectedNum = SessionUser.subuser.selectedGrantCustomerNumber.value;
      if (!selectedNum || !SessionUser.subuser.grants.value) return null;
      return SessionUser.subuser.grants.value.find((g) => g.billing_customer_number === selectedNum) || null;
    },
  },
  /** Whether the current session is a subuser session */
  isSubuser: ref(false),
  /** The user's permissions */
  permissions: ref([]),
  availableVirtualPermissions: ["has_superuser_token"],
  runtimeConfig: {
    economic: {
      transactionDraftCustomerNumber: ref(null),
      defaultDistributionDepartmentId: ref(null),
    },
    release: {
      traceId: ref(null),
      channel: ref(null),
      availableChannels: ref([]),
      versions: ref({ frontend: null, api: null }),
      frontendBaseUrl: ref(null),
      apiBaseUrl: ref(null),
      availability: ref({
        configured: true,
        missing: [],
        status: "ready",
      }),
      capturePolicy: ref({
        enabled: false,
        capture_level: "metadata",
        all_failure_metadata: true,
        retention_days: 14,
      }),
    },
  },
  virtualPermissions: computed(() => {
    /** These permissions are NOT set by default for superusers, this should ONLY be used for superusers */
    let virtualPermissions = [];
    // Super user token
    // Check if the user has a superuser token in the local storage
    if (localStorage.getItem("superuser_token") !== null) {
      // Validate the superuser token
      if (localStorage.getItem("superuser_token") !== SessionUser.token.value) {
        virtualPermissions.push("has_superuser_token");
      }
    }
    return virtualPermissions;
  }),
  permissions_computed: computed(() => {
    return [...SessionUser.permissions.value];
  }),
  hasPermission: (permission) => {
    //console.log('Checking permission: ' + permission + ' - ' + hasPermission);
    // Check if the permission is virtual
    if (SessionUser.availableVirtualPermissions.values().toArray().includes(permission)) {
      console.warn("Virtual permission detected: " + permission);
      return SessionUser.virtualPermissions.value.values().toArray().includes(permission);
    }
    // For subusers, check permissions from the selected grant only
    if (SessionUser.isSubuser.value) {
      const selectedGrant = SessionUser.subuser.getSelectedGrant();
      if (selectedGrant && selectedGrant.permissions) {
        return selectedGrant.permissions.includes(permission);
      }
      return false;
    }
    return SessionUser.permissions.value.includes(permission) || SessionUser.permissions.value.includes("superuser");
  },
  hasAnyPermission: (permissions = []) => {
    const permissionList = Array.isArray(permissions) ? permissions : [permissions].filter(Boolean);
    if (permissionList.length === 0) {
      return true;
    }
    return permissionList.some((permission) => SessionUser.hasPermission(permission));
  },
  /** Can access shortcuts */
  canAccessAdmin: () => {
    return SessionUser.hasPermission("admin") || SessionUser.hasPermission("superuser");
  },
  canAccessSuperUser: () => {
    return SessionUser.hasPermission("superuser");
  },
  canAccessUser: () => {
    return SessionUser.hasPermission("user");
  },
  canManageSubusers: (action) => {
    const permissions = SUBUSER_MANAGEMENT_PERMISSIONS[action];
    if (!permissions) {
      return false;
    }
    return SessionUser.isSubuser.value
      ? SessionUser.hasPermission(permissions.subuser)
      : SessionUser.hasPermission(permissions.customer);
  },
  canAccessCustomerFeature: (feature, action = "list") => {
    const permissions = CUSTOMER_FEATURE_PERMISSIONS[feature]?.[action];
    if (!permissions) {
      return false;
    }

    const permissionList = SessionUser.isSubuser.value ? permissions.subuser : permissions.customer;
    return SessionUser.hasAnyPermission(permissionList);
  },
  canAccessDepartment: (id = 0) => {
    return SessionUser.hasPermission("department_access_" + parseInt(id)) || SessionUser.canAccessSuperUser();
  },
  canAccessAssignedDepartment: (id = 0) => {
    const departmentId = parseInt(id, 10);
    if (!Number.isInteger(departmentId)) {
      return false;
    }

    const permission = "department_access_" + departmentId;
    if (SessionUser.isSubuser.value) {
      const selectedGrant = SessionUser.subuser.getSelectedGrant();
      if (selectedGrant && selectedGrant.permissions) {
        return selectedGrant.permissions.includes(permission);
      }
    }

    return SessionUser.permissions.value.includes(permission);
  },
  canAccessDeveloper: () => {
    // If the url is localhost, we can assume that the user is a developer
    return window.location.hostname === "localhost";
  },
  canAccessGuest: () => {
    return true; // All users can access guest features
  },
  hasToken: () => {
    return SessionUser.token.value !== null || hydrateSessionFromStorage();
  },
  /** Shortcuts for the user's group */
  superUser: SuperUserObject,
  adminUser: AdminUserObject,

  /** Objects */
  objects: {
    categories: Categories,
    products: Products,
    product_options: ProductOptions,
    departments: Departments,
    department_categories: DepartmentCategories,
    economic_departments: EconomicDepartments,
    economic_products: EconomicProducts,
    roles: Roles,
    permissions: Permissions,
    collectedOrderInvoices: CollectedOrderInvoices,
    department_daily_reports: DepartmentDailyReports,
    department_daily_report_complaints: DepartmentDailyReportComplaints,
    goals: Goals,
    notifications: Notifications,
    orders: Orders,
    forms: Forms,
    bookings: Bookings,
    Branding: Branding,
    vehicles: Vehicles,
    department_notification_sms: DepartmentNotificationSms,
    department_time_bookings_opening_hours: DepartmentTimeBookingsOpeningHours,
    department_time_bookings_types: DepartmentTimeBookingsTypes,
    department_time_bookings_entries: DepartmentTimeBookingsEntries,
    department_variables: DepartmentVariables,
    xlvask_vehicle_types: XLVaskVehicleTypes,
    openai: OpenAI,
    department_lanes: DepartmentLanes,
    department_gates: DepartmentGates,
    department_relays: DepartmentRelays,
    order_bookings: OrderBookings,
    module_action_logs: ModuleActionLogs,
    self_serve_questions: SelfServeQuestions,
    self_serve_tasks: SelfServeTasks,
    self_serve_conditions: SelfServeConditions,
    self_serve_vehicle_conditions: SelfServeVehicleConditions,
    self_serve_condition_rules: SelfServeConditionRules,
    self_serve_machine_types: SelfServeMachineTypes,
    subusers: Subusers,
    subuser_grants: SubuserGrants,
    global: ObjectsGlobal,
  },
  /** The user's token and authentication status */
  token: ref(null),
  authenticated: ref(false),
  /** The user's e-conomic data */
  economicData: {
    customerNumber: ref(null),
    name: ref(null),
    address: ref(null),
    zip: ref(null),
    city: ref(null),
    mobilePhone: ref(null),
    email: ref(null),
    cvr: ref(null),
    currency: ref(null),
    country: ref(null),
    cached_at: ref(null),
  },
  /** Check if the user's data is outdated (Older than 24 hours) */
  isDataOutdated: () => {
    return new Date() - SessionUser.user.cached_at.value > 1000 * 60 * 60 * 24;
  },
  /** Check if the user's e-conomic data is outdated (Older than 24 hours) */
  isEconomicDataOutdated: () => {
    return new Date() - SessionUser.economicData.cached_at.value > 1000 * 60 * 60 * 24;
  },
  /** Check if the user has e-conomic data */
  hasEconomicData: () => {
    return SessionUser.economicData.customerNumber.value !== null;
  },
  getCustomerNumber: () => {
    return SessionUser.user.customer_number.value;
  },
  /** Is the object fully initiated */
  initiated: ref(false),
  isInitiated: () => {
    return SessionUser.initiated.value;
  },
  /**
   * Check if the user has a superuser token stored (This is used when the superuser is impersonating a user)
   * @returns {boolean}
   */
  hasSuperUserToken: () => {
    return localStorage.getItem("superuser_token") !== null;
  },
  /**
   * Set the user's token
   * @param {string} token
   */
  setToken: (token) => {
    clearPrivilegedSessionCaches();
    SessionUser.token.value = token;
    localStorage.setItem("token", token);
    // Reload the window to make sure the user's session is initiated
    window.location.reload();
  },
  /**
   * Does the user have a specific attribute (Basically just a link to check if the user has permission`has_attribute_{{attribute}}`) // E.g. hasAttribute('admin') would check if the user has the 'has_attribute_key_admin' permission
   * @param {string} attribute
   * @returns {boolean}
   */
  hasAttribute: (attribute) => {
    return SessionUser.hasPermission("has_attribute_" + attribute);
  },
  /**
   * Get the user's display name
   */
  getName: () => {
    // If the user is a subuser, return the subuser's name
    if (SessionUser.isSubuser.value) {
      return SessionUser.subuser.name.value || SessionUser.subuser.username.value || "Unnamed";
    }
    return SessionUser.user.display_name.value || "Unnamed";
  },
  /** Reset the user's session data (Cache) */
  forceRefresh: () => {
    resetSessionState();
  },
  auth: {
    /** Authenticate the user */
    authenticate: authenticateUser,
    /** Authenticate a subuser with password */
    authenticateSubuser: authenticateSubuser,
    /** Logout the user */
    logout: destroySession,
    /** Force clear the user's local session state and stored token */
    forceClearSession: forceClearSession,
    /** reCAPTCHA */
    reCAPTCHA: reCAPTCHA,
  },
  functions: {
    /** Contact functions */
    contact: {
      onClickCallPhoneNumber: () => {
        // Call the phone number
        window.location.href = "tel:+4543717886";
      },
    },
    /** Device type checks */
    device: {
      dimensions: {
        // Using breakpoints in accordance with Bulma CSS framework
        // https://bulma.io/documentation/start/responsiveness/#breakpoints
        mobileMaxWidth: 768,
        tabletMinWidth: 769,
        tabletMaxWidth: 1023,
        desktopMinWidth: 1024,
        desktopMaxWidth: 1215,
        widescreenMinWidth: 1216,
        widescreenMaxWidth: 1407,
        fullhdMinWidth: 1408,
        // Custom additions
        fullhdMaxWidth: 1919,
        ultrawideMinWidth: 1920,
        ultrawideMaxWidth: 3840,
      },
      isMobile: () => {
        return windowInnerWidth.value < SessionUser.functions.device.dimensions.tabletMinWidth;
        //return /Mobi|Android/i.test(navigator.userAgent);
      },
      isDesktop: () => {
        return windowInnerWidth.value >= SessionUser.functions.device.dimensions.desktopMinWidth;
        //return !/Mobi|Android/i.test(navigator.userAgent);
      },
      isTablet: () => {
        return (
          windowInnerWidth.value >= SessionUser.functions.device.dimensions.tabletMinWidth &&
          windowInnerWidth.value <= SessionUser.functions.device.dimensions.tabletMaxWidth
        );
        //return /Tablet|iPad/i.test(navigator.userAgent);
      },
      isWidescreen: () => {
        return (
          windowInnerWidth.value >= SessionUser.functions.device.dimensions.widescreenMinWidth &&
          windowInnerWidth.value <= SessionUser.functions.device.dimensions.widescreenMaxWidth
        );
      },
      isFullHD: () => {
        return windowInnerWidth.value >= SessionUser.functions.device.dimensions.fullhdMinWidth;
      },
      isUltraWideScreen: () => {
        return windowInnerWidth.value >= SessionUser.functions.device.dimensions.ultrawideMinWidth;
      },
    },
    /** Check if the user has a token */
    hasToken: () => {
      return SessionUser.token.value !== null || hydrateSessionFromStorage();
    },
    ucFirst: (str) => {
      return str.charAt(0).toUpperCase() + str.slice(1);
    },
    /** Select department */
    selectDepartment: (departmentId) => {
      // Check if the department id is valid
      if (isNaN(departmentId) || departmentId <= 0) {
        console.error("Invalid department id: " + departmentId);
        return;
      }
      if (departmentId === "default") {
        // Redirect to the default department page
        SessionUser.functions.redirectTo.department("");
        return;
      }
      // Check if the user has access to the department
      if (!SessionUser.canAccessDepartment(departmentId)) {
        console.error("User does not have access to department: " + departmentId);
        return;
      }
      // Check if the current path is within the /admin/:departmentId route
      if (!window.location.pathname.startsWith("/admin/")) {
        // Redirect to the department page
        SessionUser.functions.redirectTo.department(departmentId);
        return;
      }
      // Get the router instance
      // Change the department in the url (while keeping the current path)
      const currentPath = window.location.pathname;
      // If
      // If the current path is not an admin path, redirect to the department page
      const newPath = currentPath
        .replace(/\/admin\/\d+/, "")
        .replace(/^\/admin\/?/, "")
        .replace(/^\//, "");
      const shouldPreserveCurrentQuery = newPath === "modules/pos" || newPath.startsWith("modules/pos/");
      const queryString = shouldPreserveCurrentQuery ? window.location.search : "";
      // Redirect to the department page
      SessionUser.functions.redirectTo.department(departmentId, newPath + queryString);
    },
    /** Show confirm logout dialog */
    showConfirmLogoutDialog: () => {
      return Swal.fire({
        title: "Er du sikker?",
        text: "Du vil blive logget ud af systemet",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Ja, log mig ud",
        cancelButtonText: "Annuller",
      }).then(async (result) => {
        if (result.isConfirmed) {
          const wasSubuserSession = SessionUser.isSubuser.value || getStoredSessionSnapshot()?.isSubuser === true;
          try {
            await SessionUser.auth.logout();
          } finally {
            SessionUser.auth.forceClearSession();
            if (wasSubuserSession) {
              SessionUser.functions.redirectTo.pages.subuserLogin();
              return;
            }
            SessionUser.functions.redirectTo.pages.login();
          }
        }
      });
    },
    /** Get the department id from the url */
    getDepartmentIdFromUrl: () => {
      // Avoid router import cycles by parsing the current pathname directly.
      const path = window.location.pathname || "";
      const match = path.match(/^\/admin\/(\d+)(?:\/|$)/);
      if (!match) {
        return undefined;
      }
      const departmentId = Number.parseInt(match[1], 10);
      return Number.isInteger(departmentId) && departmentId > 0 ? departmentId : undefined;
    },
    /** Get the department ids the user has access to */
    getAccessibleDepartments: () => {
      return SessionUser.permissions.value
        .filter((permission) => permission.includes("department_access_"))
        .map((permission) => parseInt(permission.split("_").pop()));
    },
    currency: {
      toLocal: (value) => {
        return new Intl.NumberFormat("da-DK", { style: "currency", currency: "DKK" }).format(value);
      },
    },
    text: {
      truncate: (text, length = 25) => {
        return text.length > length ? text.substring(0, length) + "..." : text;
      },
    },
    date: {
      // Format to 2023-01-01 12:00:00
      format: (date) => {
        return new Date(date).toISOString().slice(0, 19).replace("T", " ");
      },
      toWords: (date) => {
        const options = { weekday: "long", year: "numeric", month: "long", day: "numeric" };
        return new Date(date).toLocaleDateString("da-DK", options);
      },
      toLocal: (date) => {
        return new Date(date).toLocaleString("da-DK");
      },
      toWordsWithTime: (date) => {
        const options = {
          weekday: "long",
          year: "numeric",
          month: "long",
          day: "numeric",
          hour: "2-digit",
          minute: "2-digit",
        };
        return new Date(date).toLocaleDateString("da-DK", options);
      },
      isToday(date) {
        const created_at_val = new Date(date);
        const today = new Date();
        return created_at_val.toDateString() === today.toDateString();
      },
      toLocalTimeHours: (date) => {
        return new Date(date).toLocaleTimeString("da-DK", { hour: "2-digit", minute: "2-digit" });
      },
      getDateWeekdayNumber: (date) => {
        const created_at_val = new Date(date);
        const weekday = created_at_val.getDay();
        return weekday === 0 ? 7 : weekday;
      },
      timeAgo: (date) => {
        // Returns e.g. "5 minutter siden"
        const now = new Date();
        const past = new Date(date);
        const secondsAgo = Math.floor((now - past) / 1000);
        const intervals = {
          year: 31536000,
          month: 2592000,
          week: 604800,
          day: 86400,
          hour: 3600,
          minute: 60,
          second: 1,
        };
        for (const [unit, secondsInUnit] of Object.entries(intervals)) {
          const interval = Math.floor(secondsAgo / secondsInUnit);
          if (interval >= 1) {
            // If the unit is singular or plural in danish
            if (interval === 1) {
              const unitSingularMap = {
                year: "år",
                month: "måned",
                week: "uge",
                day: "dag",
                hour: "time",
                minute: "minut",
                second: "sekund",
              };
              return interval + " " + unitSingularMap[unit] + " siden";
            } else {
              const unitPluralMap = {
                year: "år",
                month: "måneder",
                week: "uger",
                day: "dage",
                hour: "timer",
                minute: "minutter",
                second: "sekunder",
              };
              return interval + " " + unitPluralMap[unit] + " siden";
            }
          }
        }
        return "lige nu";
      },
      weekdayNumbers: {
        monday: 1,
        tuesday: 2,
        wednesday: 3,
        thursday: 4,
        friday: 5,
        saturday: 6,
        sunday: 7,
      },
      getDateMonthStart() {
        return new Date(new Date().getFullYear(), new Date().getMonth(), 1);
      },
      getDateMonthEnd() {
        return new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0);
      },
      getDateMonthName(date) {
        console.log(date);
        return new Date(date).toLocaleString("da-DK", { month: "long" });
      },
      getDateYear(date) {
        return new Date(date).getFullYear();
      },
      getDateAtTime(date, hours, minutes, seconds) {
        const newDate = new Date(date);
        newDate.setHours(hours);
        newDate.setMinutes(minutes);
        newDate.setSeconds(seconds);
        return newDate;
      },
      getWeekdayNameToLocal(date) {
        return new Date(date).toLocaleString("da-DK", { weekday: "long" });
      },
    },
    /** Redirect to */
    redirectTo: {
      /**
       * Pages to redirect to
       */
      pages: {
        login: () => {
          window.location.href = "/login";
        },
        subuserLogin: () => {
          window.location.href = "/login/driver";
        },
        redirect: () => {
          window.location.href = "/redirect";
        },
      },
      /**
       * Redirect to a department
       * @note This will redirect the user to '/admin/:department(/:path)'
       * @param department The department id
       * @param path The path to redirect to (Optional)
       * @param new_tab Open the url in a new tab
       */
      department: (department, path = null, new_tab = false) => {
        if (!!new_tab) {
          SessionUser.functions.redirectTo.external("/admin/" + department + (path !== null ? "/" + path : ""), true);
        } else {
          window.location.href = "/admin/" + department + (path !== null ? "/" + path : "");
        }
      },
      /**
       * Redirect to a superuser page
       * @note This will redirect the user to '/superuser(/:path)'
       * @param path The path to redirect to (Optional)
       * @param new_tab Open the url in a new tab
       */
      superUser: (path = null, new_tab = false) => {
        if (new_tab) {
          window.open("/superuser" + (path !== null ? path : ""), "_blank");
          return;
        }
        window.location.href = "/superuser" + (path !== null ? path : "");
      },
      /**
       * Redirect to a user page
       * @note This will redirect the user to '/user(/:path)'
       * @param path The path to redirect to (Optional)
       * @param new_tab Open the url in a new tab
       */
      user: (path = null, new_tab = false) => {
        if (new_tab) {
          window.open("/user" + (path !== null ? path : ""), "_blank");
          return;
        }
        window.location.href = "/user" + (path !== null ? path : "");
      },
      /**
       * External redirect
       * @param url The url to redirect to
       * @param newTab Open the url in a new tab
       */
      external: (url, newTab = false) => {
        if (newTab) {
          window.open(url, "_blank");
        } else {
          window.location.href = url;
        }
      },
    },
    parseErrorMessage(error) {
      console.log("Parsing error message: ", error);
      // Check if the error is a string
      if (typeof error === "string") {
        return error;
      }
      // check if the response.data.data.message exists
      if (error.response && error.response.data && error.response.data.data && error.response.data.data.message) {
        return error.response.data.data.message;
      }
      // check if the response.data.message exists
      if (error.response && error.response.data && error.response.data.message) {
        return error.response.data.message;
      }
      // check if the response.data exists
      if (error.response && error.response.data) {
        return error.response.data;
      }
      // check if the response exists
      if (error.response) {
        return error.response;
      }
    },
    getBusinessDaysBetweenDates(start, end, weekdays = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"]) {
      let count = 0;
      const curDate = new Date(start);
      while (curDate <= end) {
        const dayOfWeek = curDate.toLocaleString("en-US", { weekday: "long" }).toUpperCase();
        if (weekdays.includes(dayOfWeek)) {
          count++;
        }
        curDate.setDate(curDate.getDate() + 1);
      }
      return count;
    },
  },
  request: authenticatedRequest,
  editField: EditFieldForm,
  getSessionData: getSessionData,
  getSubuserSessionData: getSubuserSessionData,
  refreshSessionData: refreshSessionData,
  refreshReleaseRuntime: refreshReleaseRuntime,
  initiateOnAppStart: initiateOnAppStart,
  checkForUpdates() {
    // Check if this is the latest version of the PWA
  },
};

const windowInnerWidth = ref(window.innerWidth);
const updateWindowInnerWidth = () => {
  windowInnerWidth.value = window.innerWidth;
};
window.addEventListener("resize", updateWindowInnerWidth);

const _sfc_main$2 = SessionUser;
const SessionUser_default = /*#__PURE__*/_export_sfc(_sfc_main$2, [['__file',"SessionUser.vue"]]);

const today = () => new Date();

const cloneDate = (value) => new Date(value.getTime());

const shiftDays = (value, days) => {
  const date = cloneDate(value);
  date.setDate(date.getDate() + days);
  return date;
};

const startOfWeek = (value) => {
  const date = cloneDate(value);
  const day = date.getDay();
  const offset = day === 0 ? -6 : 1 - day;
  date.setDate(date.getDate() + offset);
  return startOfLocalDate(date);
};

const endOfWeek = (value) => {
  const start = startOfWeek(value);
  const end = shiftDays(start, 6);
  return endOfLocalDate(end);
};

const startOfMonth = (value) => startOfLocalDate(new Date(value.getFullYear(), value.getMonth(), 1));

const endOfMonth = (value) => endOfLocalDate(new Date(value.getFullYear(), value.getMonth() + 1, 0));

const relativeDayRange = (offsetDays = 0) => {
  const date = shiftDays(today(), offsetDays);
  return {
    startDate: startOfLocalDate(date),
    endDate: endOfLocalDate(date),
  };
};

const relativeWeekRange = (offsetWeeks = 0) => {
  const weekStart = shiftDays(startOfWeek(today()), offsetWeeks * 7);
  return {
    startDate: startOfLocalDate(weekStart),
    endDate: endOfWeek(weekStart),
  };
};

const relativeMonthRange = (offsetMonths = 0) => {
  const date = today();
  date.setMonth(date.getMonth() + offsetMonths);
  return {
    startDate: startOfMonth(date),
    endDate: endOfMonth(date),
  };
};

const lastSevenDaysRange = () => {
  const endDate = endOfLocalDate(today());
  const startDate = startOfLocalDate(shiftDays(endDate, -6));
  return { startDate, endDate };
};

const buildRelativeDateShortcuts = () => [
  {
    key: "anytime",
    label: SessionUser.objects.global.language.text.anytime,
    getRange: () => ({
      startDate: null,
      endDate: null,
    }),
  },
  {
    key: "today",
    label: SessionUser.objects.global.language.text.today,
    getRange: () => relativeDayRange(0),
  },
  {
    key: "yesterday",
    label: SessionUser.objects.global.language.text.yesterday,
    getRange: () => relativeDayRange(-1),
  },
  {
    key: "last_seven_days",
    label: SessionUser.objects.global.language.text.last_7_days,
    getRange: () => lastSevenDaysRange(),
  },
  {
    key: "this_week",
    label: SessionUser.objects.global.language.text.this_week,
    getRange: () => relativeWeekRange(0),
  },
  {
    key: "last_week",
    label: SessionUser.objects.global.language.text.last_week,
    getRange: () => relativeWeekRange(-1),
  },
  {
    key: "this_month",
    label: SessionUser.objects.global.language.text.this_month,
    getRange: () => relativeMonthRange(0),
  },
  {
    key: "last_month",
    label: SessionUser.objects.global.language.text.last_month,
    getRange: () => relativeMonthRange(-1),
  },
  {
    key: "same_week_last_year",
    label: SessionUser.objects.global.language.text.same_week_last_year,
    getRange: () => {
      const thisWeekStart = startOfWeek(today());
      thisWeekStart.setFullYear(thisWeekStart.getFullYear() - 1);
      const thisWeekEnd = shiftDays(thisWeekStart, 6);
      return {
        startDate: startOfLocalDate(thisWeekStart),
        endDate: endOfLocalDate(thisWeekEnd),
      };
    },
  },
  {
    key: "same_month_last_year",
    label: SessionUser.objects.global.language.text.same_month_last_year,
    getRange: () => relativeMonthRange(-12),
  },
];

const splitRelativeDateShortcuts = (shortcuts, primaryKeys = []) => {
  const primary = [];
  const other = [];
  const primaryKeySet = new Set(primaryKeys);

  shortcuts.forEach((shortcut) => {
    if (primaryKeySet.has(shortcut.key)) {
      primary.push(shortcut);
      return;
    }

    other.push(shortcut);
  });

  return { primary, other };
};

const _sfc_main$1 = /*@__PURE__*/Object.assign({
  inheritAttrs: false,
}, {
  __name: 'BuefyMonthField',
  props: {
  modelValue: {
    type: [String, Date],
    default: "",
  },
  valueType: {
    type: String,
    default: "string",
    validator: (value) => ["string", "date", "nullable-string"].includes(value),
  },
  placeholder: {
    type: String,
    default: "",
  },
  disabled: Boolean,
  readonly: Boolean,
  expanded: {
    type: Boolean,
    default: true,
  },
  appendToBody: {
    type: Boolean,
    default: true,
  },
  position: {
    type: String,
    default: "is-bottom-left",
  },
  openOnFocus: {
    type: Boolean,
    default: true,
  },
  inline: Boolean,
  clearable: Boolean,
  minDate: {
    type: Date,
    default: null,
  },
  maxDate: {
    type: Date,
    default: null,
  },
  unselectableDates: {
    type: [Array, Function],
    default: null,
  },
  selectableDates: {
    type: [Array, Function],
    default: null,
  },
  events: {
    type: Array,
    default: () => [],
  },
  indicators: {
    type: String,
    default: "dots",
  },
  dataTestid: {
    type: String,
    default: "",
  },
},
  emits: ["update:modelValue", "change"],
  setup(__props, { expose: __expose, emit: __emit }) {
  __expose();



const props = __props;

const emit = __emit;
const { locale } = useI18n({ useScope: "global" });
const attrs = useAttrs();
const datepickerTestId = computed(() => props.dataTestid || attrs["data-testid"] || undefined);

const selectedMonth = computed({
  get: () => normalizeDatepickerMonth(props.modelValue),
  set: (value) => {
    const normalized = normalizeDatepickerMonth(value);
    let nextValue = "";

    if (props.valueType === "date") {
      nextValue = normalized;
    } else if (props.valueType === "nullable-string") {
      nextValue = normalized ? formatDatepickerMonthForApi(normalized) : null;
    } else {
      nextValue = normalized ? formatDatepickerMonthForApi(normalized) : "";
    }

    emit("update:modelValue", nextValue);
    emit("change", nextValue);
  },
});

const showClearIcon = computed(() => (
  props.clearable
  && selectedMonth.value !== null
  && !props.disabled
  && !props.readonly
));

const clearSelectedMonth = (event) => {
  event?.preventDefault?.();
  event?.stopPropagation?.();
  selectedMonth.value = null;
};

const formatter = (value) => formatDatepickerMonthForLocale(value, locale.value);
const parser = (value) => parseMonthpickerInput(value, locale.value);

const __returned__ = { props, emit, locale, attrs, datepickerTestId, selectedMonth, showClearIcon, clearSelectedMonth, formatter, parser, computed, useAttrs, get useI18n() { return useI18n }, get BDatepicker() { return BDatepicker }, get formatDatepickerMonthForApi() { return formatDatepickerMonthForApi }, get formatDatepickerMonthForLocale() { return formatDatepickerMonthForLocale }, get normalizeDatepickerMonth() { return normalizeDatepickerMonth }, get parseMonthpickerInput() { return parseMonthpickerInput } };
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true });
return __returned__
}

});

const _hoisted_1$1 = ["data-testid"];

function _sfc_render$1(_ctx, _cache, $props, $setup, $data, $options) {
  return (openBlock(), createElementBlock("div", { "data-testid": $setup.datepickerTestId }, [
    createVNode($setup["BDatepicker"], mergeProps($setup.attrs, {
      modelValue: $setup.selectedMonth,
      "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (($setup.selectedMonth) = $event)),
      type: "month",
      "icon-pack": "fas",
      icon: "calendar",
      locale: $setup.locale,
      placeholder: $props.placeholder,
      position: $props.position,
      "open-on-focus": $props.openOnFocus,
      inline: $props.inline,
      disabled: $props.disabled,
      readonly: $props.readonly,
      expanded: $props.expanded,
      "append-to-body": $props.appendToBody,
      "min-date": $props.minDate,
      "max-date": $props.maxDate,
      "unselectable-dates": $props.unselectableDates,
      "selectable-dates": $props.selectableDates,
      events: $props.events,
      indicators: $props.indicators,
      "icon-right": $setup.showClearIcon ? 'times-circle' : undefined,
      "icon-right-clickable": $setup.showClearIcon,
      "mobile-native": false,
      editable: true,
      "date-formatter": $setup.formatter,
      "date-parser": $setup.parser,
      onIconRightClick: $setup.clearSelectedMonth
    }), null, 16 /* FULL_PROPS */, ["modelValue", "locale", "placeholder", "position", "open-on-focus", "inline", "disabled", "readonly", "expanded", "append-to-body", "min-date", "max-date", "unselectable-dates", "selectable-dates", "events", "indicators", "icon-right", "icon-right-clickable"])
  ], 8 /* PROPS */, _hoisted_1$1))
}
const BuefyMonthField = /*#__PURE__*/_export_sfc(_sfc_main$1, [['render',_sfc_render$1],['__file',"BuefyMonthField.vue"]]);

const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "DatePeriodSelector",
  props: {
    selection: {
      type: Object,
      required: true,
      default: () => ({
        startDate: new Date((/* @__PURE__ */ new Date()).setHours(0, 0, 0, 0)),
        endDate: new Date((/* @__PURE__ */ new Date()).setHours(23, 59, 59, 999))
      })
    },
    onSelectionChange: {
      type: Function,
      required: true,
      default: (startDate, endDate) => {
        if (IS_DEV) {
          console.warn("onSelectionChange not provided", "startDate:", startDate, "endDate:", endDate);
        }
      }
    },
    visibility: {
      type: Object,
      required: false,
      default: () => ({
        showStartDate: true,
        showEndDate: true,
        showToLabel: true,
        showSelectionValidity: true,
        showUpdateButton: true
      })
    },
    reverseLevelOrder: {
      type: Boolean,
      default: false
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    isReadonly: {
      type: Boolean,
      default: false
    },
    restrictions: {
      type: Object,
      default: () => ({
        minDate: null,
        maxDate: null
      })
    },
    autoEmitChange: {
      type: Boolean,
      default: true
    },
    allowEmptySelection: {
      type: Boolean,
      default: false
    },
    shortcutIds: {
      type: Array,
      default: () => buildRelativeDateShortcuts().map((shortcut) => shortcut.key)
    },
    primaryShortcutIds: {
      type: Array,
      default: () => ["anytime", "today", "yesterday", "this_week", "last_week"]
    },
    unselectableDates: {
      type: [Array, Function],
      default: null
    },
    selectableDates: {
      type: [Array, Function],
      default: null
    },
    events: {
      type: Array,
      default: () => []
    },
    indicators: {
      type: String,
      default: "dots"
    }
  },
  emits: ["update:selection"],
  setup(__props, { expose: __expose, emit: __emit }) {
    __expose();
    const props = __props;
    const slots = useSlots();
    const visibility = computed(() => ({
      showStartDate: true,
      showEndDate: true,
      showToLabel: true,
      showSelectionValidity: true,
      showUpdateButton: true,
      showMonthSelector: true,
      showMultipleMonthWarning: true,
      showYearSelector: true,
      showDailySelector: false,
      showWeeklySelector: false,
      showShortCuts: true,
      ...props.visibility
    }));
    const emits = __emit;
    const { width } = useWindowSize();
    const { t } = useI18n({ useScope: "global" });
    const startDate = ref(props.selection.startDate);
    const endDate = ref(props.selection.endDate);
    const currentMonthSelection = ref((startDate.value || /* @__PURE__ */ new Date()).getMonth() + 1);
    const monthFieldRef = ref(null);
    const isPendingEmit = ref(false);
    const isMobileLayout = computed(() => width.value <= 768 || SessionUser.functions.device.isMobile());
    const showMobileAdvancedControls = computed(() => visibility.value.showMonthSelector || visibility.value.showYearSelector);
    const showDesktopSelectionControls = computed(() => Boolean(visibility.value.showStartDate) || Boolean(visibility.value.showEndDate) || Boolean(!visibility.value.showStartDate && !visibility.value.showEndDate && visibility.value.showToLabel) || Boolean(visibility.value.showMonthSelector) || Boolean(visibility.value.showYearSelector) || Boolean(visibility.value.showSelectionValidity) || Boolean(slots.left) || Boolean(slots.right));
    const isMobileAdvancedExpanded = ref(false);
    const isMobileOtherExpanded = ref(false);
    const isOtherMonthModalOpen = ref(false);
    const formatDateInputValue = (date) => date ? formatLocalDateOnly(date) : "";
    const isSameDateInputValue = (left, right) => formatDateInputValue(left) === formatDateInputValue(right);
    const updateSelection = () => {
      emits("update:selection", { startDate: startDate.value, endDate: endDate.value });
      props.onSelectionChange(startDate.value, endDate.value);
      isPendingEmit.value = false;
    };
    const applyDateRange = (newStartDate, newEndDate) => {
      startDate.value = newStartDate;
      endDate.value = newEndDate;
      currentMonthSelection.value = (newStartDate || /* @__PURE__ */ new Date()).getMonth() + 1;
      isPendingEmit.value = true;
      if (props.autoEmitChange) {
        updateSelection();
      }
    };
    watch(() => props.selection, (newSelection) => {
      startDate.value = newSelection.startDate;
      endDate.value = newSelection.endDate;
      currentMonthSelection.value = (newSelection.startDate || /* @__PURE__ */ new Date()).getMonth() + 1;
    }, { immediate: true });
    watch(isMobileLayout, (isMobile) => {
      if (!isMobile) {
        isMobileAdvancedExpanded.value = false;
        isMobileOtherExpanded.value = false;
        return;
      }
      isMobileAdvancedExpanded.value = false;
      isMobileOtherExpanded.value = false;
    }, { immediate: true });
    const isStartDateValid = computed(() => !startDate.value || !props.restrictions.minDate || startDate.value >= props.restrictions.minDate);
    const isEndDateValid = computed(() => !endDate.value || !props.restrictions.maxDate || endDate.value <= props.restrictions.maxDate);
    const isSelectionValid = computed(() => isStartDateValid.value && isEndDateValid.value && (!startDate.value || !endDate.value || startDate.value <= endDate.value));
    const handleStartDateChange = (newDate) => {
      if (isSameDateInputValue(newDate, startDate.value)) {
        return;
      }
      applyDateRange(newDate, endDate.value);
    };
    const handleEndDateChange = (newDate) => {
      if (isSameDateInputValue(newDate, endDate.value)) {
        return;
      }
      applyDateRange(startDate.value, newDate);
    };
    const getFullMonthRange = (year, month) => ({
      startDate: new Date(year, month - 1, 1, 0, 0, 0, 0),
      endDate: new Date(year, month, 0, 23, 59, 59, 999)
    });
    const setMonth = (month) => {
      if (month < 1 || month > 12) {
        console.warn("Invalid month selection:", month);
        return;
      }
      const year = (startDate.value || /* @__PURE__ */ new Date()).getFullYear();
      const range = getFullMonthRange(year, month);
      applyDateRange(range.startDate, range.endDate);
    };
    const setCurrentSelectionEntireMonth = () => {
      setMonth(currentMonthSelection.value);
    };
    const selectedMonthDate = computed({
      get: () => {
        const baseDate = startDate.value || /* @__PURE__ */ new Date();
        return new Date(baseDate.getFullYear(), currentMonthSelection.value - 1, 1);
      },
      set: (value) => {
        if (!value) {
          return;
        }
        const range = getFullMonthRange(value.getFullYear(), value.getMonth() + 1);
        applyDateRange(range.startDate, range.endDate);
      }
    });
    const handleMonthPickerChange = (value) => {
      if (!value) {
        return;
      }
      selectedMonthDate.value = value;
    };
    const isCurrentSelectionEntireMonth = computed(() => startDate.value && endDate.value && startDate.value.getDate() === 1 && endDate.value.getDate() === new Date(endDate.value.getFullYear(), endDate.value.getMonth() + 1, 0).getDate());
    const isMultiMonthSelection = computed(() => startDate.value && endDate.value && (startDate.value.getMonth() !== endDate.value.getMonth() || startDate.value.getFullYear() !== endDate.value.getFullYear()));
    const enabledShortcutIds = computed(() => props.allowEmptySelection ? props.shortcutIds : props.shortcutIds.filter((shortcutId) => shortcutId !== "anytime"));
    const shortcuts = computed(() => buildRelativeDateShortcuts().filter((shortcut) => enabledShortcutIds.value.includes(shortcut.key)).map((shortcut) => ({
      id: shortcut.key,
      label: shortcut.label,
      getRange: shortcut.getRange
    })));
    const relativeShortcutBuckets = computed(() => {
      const allShortcuts = buildRelativeDateShortcuts().filter((shortcut) => enabledShortcutIds.value.includes(shortcut.key));
      const mapShortcut = (shortcut) => ({
        id: shortcut.key,
        label: shortcut.label,
        getRange: shortcut.getRange
      });
      const { primary, other } = splitRelativeDateShortcuts(allShortcuts, props.primaryShortcutIds);
      return {
        primary: primary.map(mapShortcut),
        other: other.map(mapShortcut)
      };
    });
    const primaryShortcuts = computed(() => relativeShortcutBuckets.value.primary);
    const otherShortcuts = computed(() => relativeShortcutBuckets.value.other);
    const selectedShortcutId = computed(() => shortcuts.value.find((shortcut) => {
      const range = shortcut.getRange();
      return formatDateInputValue(range.startDate) === formatDateInputValue(startDate.value) && formatDateInputValue(range.endDate) === formatDateInputValue(endDate.value);
    })?.id || "");
    const isOtherShortcutSelected = computed(() => otherShortcuts.value.some((shortcut) => shortcut.id === selectedShortcutId.value));
    const selectedPrimaryShortcutId = computed(() => primaryShortcuts.value.some((shortcut) => shortcut.id === selectedShortcutId.value) ? selectedShortcutId.value : "");
    const applyShortcut = (shortcut) => {
      const range = shortcut.getRange();
      applyDateRange(range.startDate, range.endDate);
    };
    const openOtherMonthModal = async () => {
      isOtherMonthModalOpen.value = true;
    };
    const closeOtherMonthModal = () => {
      isOtherMonthModalOpen.value = false;
    };
    const handleOtherMonthPickerChange = (value) => {
      handleMonthPickerChange(value);
      if (value) {
        closeOtherMonthModal();
      }
    };
    const otherDropdownActions = computed(() => {
      const actions = otherShortcuts.value.map((shortcut) => ({
        id: shortcut.id,
        label: shortcut.label,
        onClick: () => applyShortcut(shortcut)
      }));
      if (visibility.value.showShortCuts !== false && shortcuts.value.length > 0) {
        actions.unshift({
          id: "other_month",
          label: t("global.text.other_month"),
          onClick: openOtherMonthModal
        });
      }
      return actions;
    });
    const handleOtherAction = async (action) => {
      await action.onClick();
      isMobileOtherExpanded.value = false;
    };
    const handleShortcutSelection = (event) => {
      const selectedId = String(event.target.value || "");
      const selectedShortcut = shortcuts.value.find((shortcut) => shortcut.id === selectedId);
      if (!selectedShortcut) {
        return;
      }
      applyShortcut(selectedShortcut);
    };
    const __returned__ = { props, slots, visibility, emits, width, t, startDate, endDate, currentMonthSelection, monthFieldRef, isPendingEmit, isMobileLayout, showMobileAdvancedControls, showDesktopSelectionControls, isMobileAdvancedExpanded, isMobileOtherExpanded, isOtherMonthModalOpen, formatDateInputValue, isSameDateInputValue, updateSelection, applyDateRange, isStartDateValid, isEndDateValid, isSelectionValid, handleStartDateChange, handleEndDateChange, getFullMonthRange, setMonth, setCurrentSelectionEntireMonth, selectedMonthDate, handleMonthPickerChange, isCurrentSelectionEntireMonth, isMultiMonthSelection, enabledShortcutIds, shortcuts, relativeShortcutBuckets, primaryShortcuts, otherShortcuts, selectedShortcutId, isOtherShortcutSelected, selectedPrimaryShortcutId, applyShortcut, openOtherMonthModal, closeOtherMonthModal, handleOtherMonthPickerChange, otherDropdownActions, handleOtherAction, handleShortcutSelection, get BTooltip() {
      return Tooltip$1;
    }, SessionUser, BuefyDateField, BuefyMonthField };
    Object.defineProperty(__returned__, "__isScriptSetup", { enumerable: false, value: true });
    return __returned__;
  }
});

const _hoisted_1 = { class: "date-period-selector" };
const _hoisted_2 = {
  key: 0,
  class: "date-period-selector__mobile",
  "data-testid": "date-period-mobile-layout"
};
const _hoisted_3 = {
  key: 0,
  class: "field"
};
const _hoisted_4 = { class: "label is-small" };
const _hoisted_5 = { class: "control" };
const _hoisted_6 = { class: "date-period-selector__mobile-shortcuts" };
const _hoisted_7 = {
  key: 0,
  class: "select is-fullwidth"
};
const _hoisted_8 = ["value", "disabled"];
const _hoisted_9 = {
  value: "",
  disabled: ""
};
const _hoisted_10 = ["value"];
const _hoisted_11 = {
  key: 1,
  class: "date-period-selector__mobile-other"
};
const _hoisted_12 = ["aria-expanded", "disabled"];
const _hoisted_13 = { class: "date-period-selector__other-label" };
const _hoisted_14 = { class: "icon is-small" };
const _hoisted_15 = {
  key: 0,
  class: "date-period-selector__mobile-other-menu",
  "data-testid": "date-period-other-menu"
};
const _hoisted_16 = ["data-testid", "onClick"];
const _hoisted_17 = {
  key: 1,
  class: "field"
};
const _hoisted_18 = { class: "label is-small" };
const _hoisted_19 = { class: "control" };
const _hoisted_20 = {
  key: 2,
  class: "field"
};
const _hoisted_21 = { class: "label is-small" };
const _hoisted_22 = { class: "control" };
const _hoisted_23 = {
  key: 3,
  class: "field"
};
const _hoisted_24 = { class: "control" };
const _hoisted_25 = { class: "icon" };
const _hoisted_26 = {
  key: 4,
  class: "date-period-selector__advanced-panel"
};
const _hoisted_27 = {
  key: 0,
  class: "field"
};
const _hoisted_28 = { class: "label is-small" };
const _hoisted_29 = { class: "control" };
const _hoisted_30 = { class: "date-period-selector__mobile-actions" };
const _hoisted_31 = ["disabled"];
const _hoisted_32 = {
  key: 0,
  class: "level is-align-items-center"
};
const _hoisted_33 = { class: "level-left" };
const _hoisted_34 = {
  key: 0,
  class: "level-item"
};
const _hoisted_35 = {
  key: 1,
  class: "level-item"
};
const _hoisted_36 = { class: "label" };
const _hoisted_37 = {
  key: 2,
  class: "level-item"
};
const _hoisted_38 = {
  key: 3,
  class: "level-item"
};
const _hoisted_39 = { class: "label" };
const _hoisted_40 = {
  key: 4,
  class: "level-item"
};
const _hoisted_41 = {
  key: 0,
  class: "level-right"
};
const _hoisted_42 = {
  key: 0,
  class: "level-item"
};
const _hoisted_43 = ["disabled"];
const _hoisted_44 = {
  key: 1,
  class: "navbar is-white"
};
const _hoisted_45 = { class: "navbar-menu" };
const _hoisted_46 = { class: "navbar-start" };
const _hoisted_47 = { class: "navbar-item" };
const _hoisted_48 = { class: "buttons date-period-selector__shortcut-buttons" };
const _hoisted_49 = ["disabled", "data-testid", "onClick"];
const _hoisted_50 = { class: "date-period-selector__shortcut-label" };
const _hoisted_51 = ["disabled"];
const _hoisted_52 = { class: "date-period-selector__other-label" };
const _hoisted_53 = ["data-testid"];
const _hoisted_54 = {
  class: "modal-card date-period-selector__other-month-modal",
  "data-testid": "date-period-other-month-modal"
};
const _hoisted_55 = { class: "modal-card-head" };
const _hoisted_56 = { class: "modal-card-title" };
const _hoisted_57 = ["aria-label"];
const _hoisted_58 = { class: "modal-card-body date-period-selector__other-month-modal-body" };
const _hoisted_59 = { class: "field mb-0 date-period-selector__other-month-field" };
const _hoisted_60 = { class: "label is-small" };
const _hoisted_61 = { class: "control" };
const _hoisted_62 = { class: "modal-card-foot is-justify-content-flex-end" };
const _hoisted_63 = {
  key: 2,
  class: "date-period-selector__messages"
};
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_b_dropdown_item = resolveComponent("b-dropdown-item");
  const _component_b_dropdown = resolveComponent("b-dropdown");
  const _component_b_modal = resolveComponent("b-modal");
  const _component_b_message = resolveComponent("b-message");
  return openBlock(), createElementBlock("div", _hoisted_1, [
    $setup.isMobileLayout ? (openBlock(), createElementBlock("div", _hoisted_2, [
      $setup.primaryShortcuts.length > 0 || $setup.otherDropdownActions.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_3, [
        createBaseVNode(
          "label",
          _hoisted_4,
          toDisplayString($setup.t("date_period.labels.period")),
          1
          /* TEXT */
        ),
        createBaseVNode("div", _hoisted_5, [
          createBaseVNode("div", _hoisted_6, [
            $setup.primaryShortcuts.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_7, [
              createBaseVNode("select", {
                "data-testid": "date-period-shortcuts",
                value: $setup.selectedPrimaryShortcutId,
                disabled: $setup.props.isDisabled || $setup.props.isReadonly,
                onChange: $setup.handleShortcutSelection
              }, [
                createBaseVNode(
                  "option",
                  _hoisted_9,
                  toDisplayString($setup.t("date_period.labels.select_period")),
                  1
                  /* TEXT */
                ),
                (openBlock(true), createElementBlock(
                  Fragment,
                  null,
                  renderList($setup.primaryShortcuts, (shortcut) => {
                    return openBlock(), createElementBlock("option", {
                      key: shortcut.id,
                      value: shortcut.id
                    }, toDisplayString(shortcut.label), 9, _hoisted_10);
                  }),
                  128
                  /* KEYED_FRAGMENT */
                ))
              ], 40, _hoisted_8)
            ])) : createCommentVNode("v-if", true),
            $setup.otherDropdownActions.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_11, [
              createBaseVNode("button", {
                class: normalizeClass(["button is-light is-fullwidth date-period-selector__other-trigger", { "is-info": $setup.isOtherShortcutSelected || $setup.isMobileOtherExpanded }]),
                type: "button",
                "data-testid": "date-period-other-dropdown-trigger",
                "aria-expanded": $setup.isMobileOtherExpanded ? "true" : "false",
                disabled: $setup.props.isDisabled || $setup.props.isReadonly,
                onClick: _cache[0] || (_cache[0] = ($event) => $setup.isMobileOtherExpanded = !$setup.isMobileOtherExpanded)
              }, [
                createBaseVNode(
                  "span",
                  _hoisted_13,
                  toDisplayString($setup.t("global.other")),
                  1
                  /* TEXT */
                ),
                createBaseVNode("span", _hoisted_14, [
                  createBaseVNode(
                    "i",
                    {
                      class: normalizeClass($setup.isMobileOtherExpanded ? "fas fa-chevron-up" : "fas fa-chevron-down"),
                      "aria-hidden": "true"
                    },
                    null,
                    2
                    /* CLASS */
                  )
                ])
              ], 10, _hoisted_12),
              $setup.isMobileOtherExpanded ? (openBlock(), createElementBlock("div", _hoisted_15, [
                (openBlock(true), createElementBlock(
                  Fragment,
                  null,
                  renderList($setup.otherDropdownActions, (action) => {
                    return openBlock(), createElementBlock("button", {
                      key: action.id,
                      class: "button is-light is-fullwidth date-period-selector__mobile-other-item",
                      type: "button",
                      "data-testid": `date-period-other-${action.id}`,
                      onClick: ($event) => $setup.handleOtherAction(action)
                    }, toDisplayString(action.label), 9, _hoisted_16);
                  }),
                  128
                  /* KEYED_FRAGMENT */
                ))
              ])) : createCommentVNode("v-if", true)
            ])) : createCommentVNode("v-if", true)
          ])
        ])
      ])) : createCommentVNode("v-if", true),
      $setup.visibility.showStartDate ? (openBlock(), createElementBlock("div", _hoisted_17, [
        createBaseVNode(
          "label",
          _hoisted_18,
          toDisplayString($setup.SessionUser.objects.global.language.text.date_from),
          1
          /* TEXT */
        ),
        createBaseVNode("div", _hoisted_19, [
          createVNode($setup["BuefyDateField"], {
            "model-value": $setup.startDate,
            "value-type": "date",
            "data-testid": "date-period-start",
            disabled: $setup.props.isDisabled || $setup.props.isReadonly,
            "min-date": $setup.props.restrictions.minDate,
            "max-date": $setup.props.restrictions.maxDate,
            "unselectable-dates": $setup.props.unselectableDates,
            "selectable-dates": $setup.props.selectableDates,
            events: $setup.props.events,
            indicators: $setup.props.indicators,
            clearable: $setup.props.allowEmptySelection,
            "onUpdate:modelValue": $setup.handleStartDateChange
          }, null, 8, ["model-value", "disabled", "min-date", "max-date", "unselectable-dates", "selectable-dates", "events", "indicators", "clearable"])
        ])
      ])) : createCommentVNode("v-if", true),
      $setup.visibility.showEndDate ? (openBlock(), createElementBlock("div", _hoisted_20, [
        createBaseVNode(
          "label",
          _hoisted_21,
          toDisplayString($setup.SessionUser.objects.global.language.text.date_to),
          1
          /* TEXT */
        ),
        createBaseVNode("div", _hoisted_22, [
          createVNode($setup["BuefyDateField"], {
            "model-value": $setup.endDate,
            "value-type": "date",
            "data-testid": "date-period-end",
            disabled: $setup.props.isDisabled || $setup.props.isReadonly,
            "min-date": $setup.props.restrictions.minDate,
            "max-date": $setup.props.restrictions.maxDate,
            "unselectable-dates": $setup.props.unselectableDates,
            "selectable-dates": $setup.props.selectableDates,
            events: $setup.props.events,
            indicators: $setup.props.indicators,
            clearable: $setup.props.allowEmptySelection,
            "onUpdate:modelValue": $setup.handleEndDateChange
          }, null, 8, ["model-value", "disabled", "min-date", "max-date", "unselectable-dates", "selectable-dates", "events", "indicators", "clearable"])
        ])
      ])) : createCommentVNode("v-if", true),
      $setup.showMobileAdvancedControls ? (openBlock(), createElementBlock("div", _hoisted_23, [
        createBaseVNode("div", _hoisted_24, [
          createBaseVNode("button", {
            class: "button is-light is-fullwidth date-period-selector__advanced-toggle",
            type: "button",
            "data-testid": "date-period-advanced-toggle",
            onClick: _cache[1] || (_cache[1] = ($event) => $setup.isMobileAdvancedExpanded = !$setup.isMobileAdvancedExpanded)
          }, [
            createBaseVNode(
              "span",
              null,
              toDisplayString($setup.t("date_period.labels.advanced_period")),
              1
              /* TEXT */
            ),
            createBaseVNode("span", _hoisted_25, [
              createBaseVNode(
                "i",
                {
                  class: normalizeClass($setup.isMobileAdvancedExpanded ? "fas fa-chevron-up" : "fas fa-chevron-down")
                },
                null,
                2
                /* CLASS */
              )
            ])
          ])
        ])
      ])) : createCommentVNode("v-if", true),
      $setup.showMobileAdvancedControls && $setup.isMobileAdvancedExpanded ? (openBlock(), createElementBlock("div", _hoisted_26, [
        $setup.visibility.showMonthSelector || $setup.visibility.showYearSelector ? (openBlock(), createElementBlock("div", _hoisted_27, [
          createBaseVNode(
            "label",
            _hoisted_28,
            toDisplayString($setup.SessionUser.objects.global.language.text.month),
            1
            /* TEXT */
          ),
          createBaseVNode("div", _hoisted_29, [
            createVNode($setup["BuefyMonthField"], {
              ref: "monthFieldRef",
              "model-value": $setup.selectedMonthDate,
              "value-type": "date",
              "data-testid": "date-period-month",
              placeholder: $setup.t("date_period.labels.select_month"),
              disabled: $setup.props.isDisabled || $setup.props.isReadonly,
              "min-date": $setup.props.restrictions.minDate,
              "max-date": $setup.props.restrictions.maxDate,
              events: $setup.props.events,
              indicators: $setup.props.indicators,
              "onUpdate:modelValue": $setup.handleMonthPickerChange
            }, null, 8, ["model-value", "placeholder", "disabled", "min-date", "max-date", "events", "indicators"])
          ])
        ])) : createCommentVNode("v-if", true)
      ])) : createCommentVNode("v-if", true),
      createBaseVNode("div", _hoisted_30, [
        renderSlot(_ctx.$slots, "right", {}, void 0, true),
        $setup.visibility.showUpdateButton ? (openBlock(), createElementBlock("button", {
          key: 0,
          class: "button is-primary is-fullwidth",
          type: "button",
          onClick: $setup.updateSelection,
          disabled: $setup.props.isDisabled || $setup.props.isReadonly || !$setup.isSelectionValid || !$setup.isPendingEmit
        }, toDisplayString($setup.t("date_period.labels.update_selection")), 9, _hoisted_31)) : createCommentVNode("v-if", true)
      ])
    ])) : (openBlock(), createElementBlock(
      Fragment,
      { key: 1 },
      [
        $setup.showDesktopSelectionControls ? (openBlock(), createElementBlock("div", _hoisted_32, [
          createBaseVNode("div", _hoisted_33, [
            $setup.visibility.showStartDate ? (openBlock(), createElementBlock("div", _hoisted_34, [
              createVNode($setup["BuefyDateField"], {
                "model-value": $setup.startDate,
                "value-type": "date",
                "data-testid": "date-period-start",
                disabled: $setup.props.isDisabled || $setup.props.isReadonly,
                "min-date": $setup.props.restrictions.minDate,
                "max-date": $setup.props.restrictions.maxDate,
                "unselectable-dates": $setup.props.unselectableDates,
                "selectable-dates": $setup.props.selectableDates,
                events: $setup.props.events,
                indicators: $setup.props.indicators,
                clearable: $setup.props.allowEmptySelection,
                "onUpdate:modelValue": $setup.handleStartDateChange
              }, null, 8, ["model-value", "disabled", "min-date", "max-date", "unselectable-dates", "selectable-dates", "events", "indicators", "clearable"])
            ])) : createCommentVNode("v-if", true),
            $setup.visibility.showStartDate && $setup.visibility.showEndDate && $setup.visibility.showToLabel ? (openBlock(), createElementBlock("div", _hoisted_35, [
              createBaseVNode(
                "span",
                _hoisted_36,
                toDisplayString($setup.t("date_period.labels.to")),
                1
                /* TEXT */
              )
            ])) : createCommentVNode("v-if", true),
            $setup.visibility.showEndDate ? (openBlock(), createElementBlock("div", _hoisted_37, [
              createVNode($setup["BuefyDateField"], {
                "model-value": $setup.endDate,
                "value-type": "date",
                "data-testid": "date-period-end",
                disabled: $setup.props.isDisabled || $setup.props.isReadonly,
                "min-date": $setup.props.restrictions.minDate,
                "max-date": $setup.props.restrictions.maxDate,
                "unselectable-dates": $setup.props.unselectableDates,
                "selectable-dates": $setup.props.selectableDates,
                events: $setup.props.events,
                indicators: $setup.props.indicators,
                clearable: $setup.props.allowEmptySelection,
                "onUpdate:modelValue": $setup.handleEndDateChange
              }, null, 8, ["model-value", "disabled", "min-date", "max-date", "unselectable-dates", "selectable-dates", "events", "indicators", "clearable"])
            ])) : createCommentVNode("v-if", true),
            !$setup.visibility.showStartDate && !$setup.visibility.showEndDate && $setup.visibility.showToLabel ? (openBlock(), createElementBlock("div", _hoisted_38, [
              createBaseVNode(
                "span",
                _hoisted_39,
                toDisplayString($setup.t("date_period.labels.no_date_selection")),
                1
                /* TEXT */
              )
            ])) : createCommentVNode("v-if", true),
            $setup.visibility.showMonthSelector || $setup.visibility.showYearSelector ? (openBlock(), createElementBlock("div", _hoisted_40, [
              createVNode($setup["BuefyMonthField"], {
                ref: "monthFieldRef",
                "model-value": $setup.selectedMonthDate,
                "value-type": "date",
                "data-testid": "date-period-month",
                placeholder: $setup.t("date_period.labels.select_month"),
                disabled: $setup.props.isDisabled || $setup.props.isReadonly,
                "min-date": $setup.props.restrictions.minDate,
                "max-date": $setup.props.restrictions.maxDate,
                events: $setup.props.events,
                indicators: $setup.props.indicators,
                "onUpdate:modelValue": $setup.handleMonthPickerChange
              }, null, 8, ["model-value", "placeholder", "disabled", "min-date", "max-date", "events", "indicators"])
            ])) : createCommentVNode("v-if", true),
            renderSlot(_ctx.$slots, "left", {}, void 0, true)
          ]),
          $setup.visibility.showSelectionValidity ? (openBlock(), createElementBlock("div", _hoisted_41, [
            renderSlot(_ctx.$slots, "right", {}, void 0, true),
            $setup.visibility.showUpdateButton ? (openBlock(), createElementBlock("div", _hoisted_42, [
              createBaseVNode("button", {
                class: "button is-primary",
                onClick: $setup.updateSelection,
                disabled: $setup.props.isDisabled || $setup.props.isReadonly || !$setup.isSelectionValid || !$setup.isPendingEmit
              }, toDisplayString($setup.t("date_period.labels.update_selection")), 9, _hoisted_43)
            ])) : createCommentVNode("v-if", true)
          ])) : createCommentVNode("v-if", true)
        ])) : createCommentVNode("v-if", true),
        $setup.primaryShortcuts.length > 0 || $setup.otherShortcuts.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_44, [
          createBaseVNode("div", _hoisted_45, [
            createBaseVNode("div", _hoisted_46, [
              createBaseVNode("div", _hoisted_47, [
                createBaseVNode("div", _hoisted_48, [
                  (openBlock(true), createElementBlock(
                    Fragment,
                    null,
                    renderList($setup.primaryShortcuts, (shortcut) => {
                      return openBlock(), createElementBlock("button", {
                        key: shortcut.id,
                        disabled: $setup.props.isDisabled || $setup.props.isReadonly,
                        class: normalizeClass(["button is-light date-period-selector__shortcut-button", { "is-info": $setup.selectedShortcutId === shortcut.id }]),
                        "data-testid": `date-period-shortcut-${shortcut.id}`,
                        onClick: ($event) => $setup.applyShortcut(shortcut)
                      }, [
                        createBaseVNode(
                          "span",
                          _hoisted_50,
                          toDisplayString(shortcut.label),
                          1
                          /* TEXT */
                        )
                      ], 10, _hoisted_49);
                    }),
                    128
                    /* KEYED_FRAGMENT */
                  )),
                  $setup.otherDropdownActions.length > 0 ? (openBlock(), createBlock(_component_b_dropdown, {
                    key: 0,
                    "aria-role": "list",
                    position: "is-bottom-left",
                    class: "date-period-selector__other-dropdown"
                  }, {
                    trigger: withCtx(() => [
                      createBaseVNode("button", {
                        class: normalizeClass(["button is-light date-period-selector__other-trigger", { "is-info": $setup.isOtherShortcutSelected }]),
                        type: "button",
                        "data-testid": "date-period-other-dropdown-trigger",
                        disabled: $setup.props.isDisabled || $setup.props.isReadonly
                      }, [
                        createBaseVNode(
                          "span",
                          _hoisted_52,
                          toDisplayString($setup.t("global.other")),
                          1
                          /* TEXT */
                        ),
                        _cache[3] || (_cache[3] = createBaseVNode(
                          "span",
                          { class: "icon" },
                          [
                            createBaseVNode("i", {
                              class: "fas fa-chevron-down",
                              "aria-hidden": "true"
                            })
                          ],
                          -1
                          /* CACHED */
                        ))
                      ], 10, _hoisted_51)
                    ]),
                    default: withCtx(() => [
                      (openBlock(true), createElementBlock(
                        Fragment,
                        null,
                        renderList($setup.otherDropdownActions, (action) => {
                          return openBlock(), createBlock(_component_b_dropdown_item, {
                            key: action.id,
                            value: action.id,
                            "aria-role": "listitem",
                            class: "date-period-selector__dropdown-item",
                            onClick: ($event) => $setup.handleOtherAction(action)
                          }, {
                            default: withCtx(() => [
                              createBaseVNode("span", {
                                class: "date-period-selector__dropdown-label",
                                "data-testid": `date-period-other-${action.id}`
                              }, toDisplayString(action.label), 9, _hoisted_53)
                            ]),
                            _: 2
                            /* DYNAMIC */
                          }, 1032, ["value", "onClick"]);
                        }),
                        128
                        /* KEYED_FRAGMENT */
                      ))
                    ]),
                    _: 1
                    /* STABLE */
                  })) : createCommentVNode("v-if", true)
                ])
              ])
            ])
          ])
        ])) : createCommentVNode("v-if", true)
      ],
      64
      /* STABLE_FRAGMENT */
    )),
    createVNode(_component_b_modal, {
      modelValue: $setup.isOtherMonthModalOpen,
      "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => $setup.isOtherMonthModalOpen = $event),
      width: 460,
      "can-cancel": ["escape", "x", "outside"],
      "trap-focus": "",
      "aria-role": "dialog",
      "aria-modal": ""
    }, {
      default: withCtx(() => [
        createBaseVNode("div", _hoisted_54, [
          createBaseVNode("header", _hoisted_55, [
            createBaseVNode(
              "p",
              _hoisted_56,
              toDisplayString($setup.t("global.text.other_month")),
              1
              /* TEXT */
            ),
            createBaseVNode("button", {
              type: "button",
              class: "delete",
              "aria-label": $setup.t("common.cancel"),
              "data-testid": "date-period-other-month-close",
              onClick: $setup.closeOtherMonthModal
            }, null, 8, _hoisted_57)
          ]),
          createBaseVNode("section", _hoisted_58, [
            createBaseVNode("div", _hoisted_59, [
              createBaseVNode(
                "label",
                _hoisted_60,
                toDisplayString($setup.t("date_period.labels.select_month")),
                1
                /* TEXT */
              ),
              createBaseVNode("div", _hoisted_61, [
                createVNode($setup["BuefyMonthField"], {
                  "model-value": $setup.selectedMonthDate,
                  "value-type": "date",
                  "data-testid": "date-period-other-month-picker",
                  placeholder: $setup.t("date_period.labels.select_month"),
                  disabled: $setup.props.isDisabled || $setup.props.isReadonly,
                  "min-date": $setup.props.restrictions.minDate,
                  "max-date": $setup.props.restrictions.maxDate,
                  events: $setup.props.events,
                  indicators: $setup.props.indicators,
                  "append-to-body": false,
                  inline: "",
                  "onUpdate:modelValue": $setup.handleOtherMonthPickerChange
                }, null, 8, ["model-value", "placeholder", "disabled", "min-date", "max-date", "events", "indicators"])
              ])
            ])
          ]),
          createBaseVNode("footer", _hoisted_62, [
            createBaseVNode(
              "button",
              {
                type: "button",
                class: "button is-light",
                "data-testid": "date-period-other-month-cancel",
                onClick: $setup.closeOtherMonthModal
              },
              toDisplayString($setup.t("common.cancel")),
              1
              /* TEXT */
            )
          ])
        ])
      ]),
      _: 1
      /* STABLE */
    }, 8, ["modelValue"]),
    $setup.visibility.showMonthSelector ? (openBlock(), createElementBlock("div", _hoisted_63, [
      !$setup.isSelectionValid ? (openBlock(), createBlock(_component_b_message, {
        key: 0,
        type: "is-warning",
        iconPack: "fas",
        "has-icon": ""
      }, {
        default: withCtx(() => [
          createTextVNode(
            toDisplayString($setup.t("date_period.messages.invalid_selection")),
            1
            /* TEXT */
          )
        ]),
        _: 1
        /* STABLE */
      })) : $setup.isMultiMonthSelection && $setup.visibility.showMultipleMonthWarning ? (openBlock(), createBlock(_component_b_message, {
        key: 1,
        style: { "width": "100%" },
        type: "is-info",
        iconPack: "fas",
        "has-icon": ""
      }, {
        default: withCtx(() => [
          createTextVNode(
            toDisplayString($setup.t("date_period.messages.multi_month")),
            1
            /* TEXT */
          )
        ]),
        _: 1
        /* STABLE */
      })) : !$setup.isCurrentSelectionEntireMonth && $setup.visibility.showMultipleMonthWarning ? (openBlock(), createBlock(_component_b_message, {
        key: 2,
        closable: false,
        type: "is-info",
        iconPack: "fas",
        "has-icon": ""
      }, {
        default: withCtx(() => [
          createTextVNode(
            toDisplayString($setup.t("date_period.messages.partial_month_prefix")) + " ",
            1
            /* TEXT */
          ),
          createVNode($setup["BTooltip"], {
            label: $setup.t("date_period.messages.partial_month_tooltip"),
            type: "is-dark"
          }, {
            default: withCtx(() => [
              createBaseVNode(
                "span",
                {
                  class: "has-text-weight-bold is-clickable",
                  "data-testid": "date-period-set-entire-month",
                  onClick: $setup.setCurrentSelectionEntireMonth
                },
                toDisplayString($setup.t("date_period.messages.partial_month_action")),
                1
                /* TEXT */
              ),
              _cache[4] || (_cache[4] = createTextVNode(
                ". ",
                -1
                /* CACHED */
              ))
            ]),
            _: 1
            /* STABLE */
          }, 8, ["label"]),
          createTextVNode(
            " " + toDisplayString($setup.t("date_period.messages.partial_month_suffix")),
            1
            /* TEXT */
          )
        ]),
        _: 1
        /* STABLE */
      })) : createCommentVNode("v-if", true)
    ])) : createCommentVNode("v-if", true)
  ]);
}
const DatePeriodSelector = /* @__PURE__ */ _export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-2ff5eb2b"], ["__file", "DatePeriodSelector.vue"]]);

export { DatePeriodSelector as default };
//# sourceMappingURL=DatePeriodSelector-B7d5SXAv.js.map
